Problems
Loading...
1 / 1

Sobel Edge Detection

Computer Vision
Medium

The Sobel operator detects edges in images by computing the gradient magnitude at each pixel. It uses two 3x3 kernels to estimate horizontal and vertical derivatives, then combines them into a single edge strength value.

Given a 2D grayscale image, apply the Sobel operator with zero-padding and return the gradient magnitude at each pixel.

Algorithm

  1. Pad the image with zeros on all sides (one pixel border).
  2. At each pixel position, convolve with the two Sobel kernels:
Kx=[101202101]Ky=[121000121]K_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix} \qquad K_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & 2 & 1 \end{bmatrix}
  1. Compute the gradient magnitude:
G=Gx2+Gy2G = \sqrt{G_x^2 + G_y^2}
Loading visualization...

Examples

Input:

image = [[0, 0, 10, 10], [0, 0, 10, 10], [0, 0, 10, 10]]

Output:

A 3x4 grid where pixels near the vertical edge (columns 1-2) have high gradient values and pixels in uniform regions have lower values.

Input:

image = [[100]]

Output:

[[0.0]]

A single pixel surrounded by zero-padding has Gx and Gy that cancel due to kernel symmetry, but the padded border creates gradients at image edges for larger images.

Hint 1

Create a zero-padded version of the image first. Then for each output pixel (i,j), the 3x3 patch in the padded image starts at (i, j).

Hint 2

Gx and Gy are computed as element-wise products of the kernel and the image patch, then summed. Use math.sqrt for the final magnitude.

Requirements

  • Apply zero-padding before convolution
  • Compute both Gx and Gy using the standard Sobel kernels
  • Return the magnitude as sqrt(Gx^2 + Gy^2) for each pixel
  • Output has the same dimensions as the input

Constraints

  • Image has at least one pixel
  • Pixel values are non-negative numbers
  • Return a 2D list of floats with the same shape as the input
  • Time limit: 300 ms
Try Similar Problems