← back

Sobel Edge Detection

#241 · Computer Vision · Medium

⊣ Solve on deep-ml.com

Problem

Implement the Sobel edge detection operator. Apply Sobel kernels in the x and y directions to a grayscale image, then compute the gradient magnitude.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 result

Explanation

  1. Define the 3x3 Sobel kernels for horizontal (Gx) and vertical (Gy) gradients.
  2. Pad the image with zeros to handle border pixels.
  3. For each pixel, convolve with both Gx and Gy to get gradient components.
  4. Compute the gradient magnitude: sqrt(Gx^2 + Gy^2).
  5. High magnitude values indicate strong edges in the image.

Complexity

  • Time: O(H W 9) = O(H * W) for the 3x3 convolution
  • Space: O(H * W) for the output and padded image