Task: Sobel Edge Detection
Edge detection is a fundamental technique in computer vision used to identify boundaries within images. In this task, you will implement a function sobel_edge_detection(image) that applies the Sobel operator to detect edges in a grayscale image.
Input:
image: A 2D list/array representing a grayscale image with pixel values in range [0, 255]
Output:
- Return the edge magnitude image as a 2D list with integer values normalized to [0, 255]
- The output dimensions will be (H-2, W-2) due to valid convolution (no padding)
- Return
-1for invalid inputs
Edge Cases to Handle:
- Input is not a valid 2D array
- Image dimensions are smaller than 3x3 (minimum required for Sobel)
- Any pixel values are outside the valid range (0-255)
- Empty image
Notes:
- Use the standard Sobel kernels for gradient computation
- Compute gradient magnitude from horizontal and vertical gradients
- Normalize the output to the range [0, 255] based on the maximum magnitude value
Examples
Example 1:
Input:
image = [[0, 0, 255], [0, 0, 255], [0, 0, 255]]
print(sobel_edge_detection(image))Output:
[[255]]Explanation: This 3x3 image has a strong vertical edge (black on left, white on right). The Sobel operator computes: Gx = 1020 (strong horizontal gradient), Gy = 0 (no vertical gradient). The magnitude sqrt(1020^2 + 0^2) = 1020 is normalized to 255 since it's the maximum value.
Starter Code
import numpy as np
def sobel_edge_detection(image):
"""
Apply Sobel edge detection to a grayscale image.
Args:
image: 2D list/array representing a grayscale image
with values in range [0, 255]
Returns:
Edge magnitude image as 2D list with integer values (0-255),
or -1 if input is invalid
"""
# Your code here
passPython3
ReadyLines: 1Characters: 0
Ready