Implement the Sobel edge detection operator. Apply Sobel kernels in the x and y directions to a grayscale image, then compute the gradient magnitude.
import math
def sobel_edge_detection(image: list[list[float]]) -> list[list[float]]:
"""
image: [H, W] grayscale image
Returns: [H, W] edge magnitude image
"""
H = len(image)
W = len(image[0])
# Sobel kernels
Gx = [[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]
Gy = [[-1, -2, -1],
[ 0, 0, 0],
[ 1, 2, 1]]
# Pad image with zeros
padded = [[0.0] * (W + 2) for _ in range(H + 2)]
for h in range(H):
for w in range(W):
padded[h + 1][w + 1] = image[h][w]
result = [[0.0] * W for _ in range(H)]
for h in range(H):
for w in range(W):
sx = 0.0
sy = 0.0
for kh in range(3):
for kw in range(3):
pixel = padded[h + kh][w + kw]
sx += pixel * Gx[kh][kw]
sy += pixel * Gy[kh][kw]
result[h][w] = round(math.sqrt(sx * sx + sy * sy), 4)
return resultsqrt(Gx^2 + Gy^2).