Detailed Assignment: Sobel Edge Detection in Python
Write a Python program to implement Sobel edge detection on a grayscale image without
using any built-in convolution functions. You will detect both vertical and horizontal edges
using Sobel kernels and combine them to find the edge magnitude.
Step 1: Import necessary libraries
- Import OpenCV (cv2) for image handling.
- Import NumPy (numpy) for numerical operations.
- Import matplotlib.pyplot for displaying results.
Step 2: Load the image in grayscale
- Use cv2.imread() to load the image named pancard.jpeg.
- Read it in grayscale mode using cv2.IMREAD_GRAYSCALE.
- Store it in a variable named image.
Step 3: Define the Sobel kernels
- Create a 3 × 3 NumPy array for sobel_x (detects vertical edges):
[ [1, 0, -1],
[2, 0, -2],
[1, 0, -1] ]
- Create a 3 × 3 NumPy array for sobel_y (detects horizontal edges):
[ [1, 2, 1],
[0, 0, 0],
[-1, -2, -1] ]
Step 4: Get image dimensions
- Use .shape to get image_height and image_width.
Step 5: Create output images
- Use np.zeros_like(image, dtype=np.float32) to create output_x and output_y for storing
convolution results.
Step 6: Pad the input image
- Calculate pad_height = 1 and pad_width = 1 for a 3×3 kernel.
- Use np.pad() to pad the image with zeros on all sides.
- Store the padded image in padded_image.
Step 7: Perform convolution for sobel_x
- Loop through each pixel (i, j) of the image.
- Extract a Region of Interest (ROI) from padded_image of size 3×3.
- Multiply the ROI and sobel_x element-wise, sum the result, and store in output_x[i, j].
Step 8: Perform convolution for sobel_y
- Repeat the same process as Step 7 but use sobel_y instead of sobel_x.
- Store the result in output_y[i, j].
Step 9: Combine both directions
- Calculate gradient magnitude using: sqrt(output_x**2 + output_y**2).
- Store this in output_combined.
Step 10: Normalize the results
- Use cv2.normalize() to scale each output between 0 and 255.
- Convert to uint8 for display.
Step 11: Display the results
- Display the original image, Vertical edges (Sobel X), Horizontal edges (Sobel Y), and
Combined edges side by side using matplotlib.
- Remove axis ticks using plt.axis('off').
- Add titles to each subplot for clarity.