Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs
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 at each pixel is computed from the horizontal gradient and vertical gradient as:
Implement the function
Rules:
np.ndarray of float type.Output:
| Argument | Type |
|---|---|
| image | np.ndarray |
| Return Name | Type |
|---|---|
| value | np.ndarray |
Use NumPy only; no SciPy/OpenCV.
Zero padding; output shape equals input.
Return np.ndarray of shape (H, W).
Ensure image is a float NumPy array first; it simplifies padding and 3×3 window math.
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.
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).