Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

176. Edge detection filters

medium
GeneralGeneral
senior

Implement a simple edge-detection filter for grayscale images by convolving the image with horizontal and vertical Sobel kernels and combining their responses into an edge-magnitude map.

The edge strength GG at each pixel is computed from the horizontal gradient GxG_x and vertical gradient GyG_y as:

G=Gx2+Gy2G = \sqrt{G_x^2 + G_y^2}

Requirements

Implement the function

python

Rules:

  • Use the Sobel kernels:
    • (K_x=\begin{bmatrix}-1&0&1\-2&0&2\-1&0&1\end{bmatrix}), (K_y=\begin{bmatrix}-1&-2&-1\0&0&0\1&2&1\end{bmatrix})
  • Compute (G_x) and (G_y) by 2D convolution with zero padding so the output stays shape ((H, W)).
  • Compute edge magnitude per pixel as (G=\sqrt{G_x^2+G_y^2}).
  • Return the output as np.ndarray of float type.
  • Use only NumPy (and Python built-ins); don’t use OpenCV/SciPy convolution helpers.

Example

python

Output:

python
Input Signature
ArgumentType
imagenp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Use NumPy only; no SciPy/OpenCV.

  • Zero padding; output shape equals input.

  • Return np.ndarray of shape (H, W).

Hint 1

Ensure image is a float NumPy array first; it simplifies padding and 3×3 window math.

Hint 2

Use np.pad(img, ((1,1),(1,1)), mode='constant') so every output pixel corresponds to a 3×3 neighborhood centered on the original pixel.

Hint 3

For each (i,j), slice region = padded[i:i+3, j:j+3], compute gx = (region*kx).sum(), gy = (region*ky).sum(), then magnitude sqrt(gx**2 + gy**2).

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
sobel-filter
2d-convolution
image-processing
numpy
38 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit