0% found this document useful (0 votes)
15 views

Lab 11-12

The document outlines a lab course on advanced edge detection and image segmentation techniques in digital image processing. It covers various methods such as Laplacian, Sobel, Prewitt, Kirsch, and Canny edge detection, along with tasks for implementation and comparison of results. Additionally, it includes instructions for image segmentation using global thresholding and requires submission of code, screenshots, and an analysis report.

Uploaded by

sraximjonov767
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lab 11-12

The document outlines a lab course on advanced edge detection and image segmentation techniques in digital image processing. It covers various methods such as Laplacian, Sobel, Prewitt, Kirsch, and Canny edge detection, along with tasks for implementation and comparison of results. Additionally, it includes instructions for image segmentation using global thresholding and requires submission of code, screenshots, and an analysis report.

Uploaded by

sraximjonov767
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Digital Image Processing

22CS Fall 2024


Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

Name
Student ID
Date

Objectives:

1. Understand and implement advanced edge detection techniques, including Sobel, Prewitt,
Kirsch, and Canny operators.
2. Explore the impact of smoothing on edge detection results.
3. Segment images using global thresholding.

1. Second-Order Differential (Laplacian)

Explanation: The Laplacian operator is a second-order differential filter that highlights regions
of rapid intensity change. It is sensitive to noise, so images may need pre-processing.

Example Code:

import cv2
import numpy as np
import matplotlib.pyplot as plt

def apply_laplacian(image):
laplacian = cv2.Laplacian(image, cv2.CV_64F)
return np.abs(laplacian)

# Load a grayscale image


image = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
laplacian_image = apply_laplacian(image)

plt.imshow(laplacian_image, cmap='gray')
plt.title("Laplacian Edge Detection")
plt.show()
Tasks:
Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

 Task 1: Implement the Laplacian operator with a 3x3 kernel and visualize the result.
 Task 2: Apply Gaussian noise to the image and observe the effect on the Laplacian
output. Try different noise intensities

2. Sobel and Prewitt in X and Y Directions

Explanation: The Sobel and Prewitt operators are first-order differential filters that detect edges
by calculating the gradient in x and y directions. Sobel gives more weight to the central pixel,
while Prewitt treats all pixels equally.

Example Code:

image = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)


def apply_sobel(image, direction='x'):
if direction == 'x':
sobel = cv2.Sobel(image, cv2.CV_64F, 1, 0,
ksize=3)
else:
sobel = cv2.Sobel(image, cv2.CV_64F, 0, 1,
ksize=3)
return np.abs(sobel)

sobel_x = apply_sobel(image, 'x')


sobel_y = apply_sobel(image, 'y')

plt.subplot(1, 2, 1)
plt.imshow(sobel_x, cmap='gray')
plt.title("Sobel X")
plt.subplot(1, 2, 2)
plt.imshow(sobel_y, cmap='gray')
plt.title("Sobel Y")
plt.show()
Tasks:

 Task 3: Calculate the Sobel gradient in x and y directions separately.


Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

 Task 4: Implement Prewitt filters and compare the results with Sobel. Visualize the
magnitude of the gradient by combining x and y results.

3. Sobel and Prewitt in Multiple Directions (x, y, 45°, -45°)

Explanation: Edge detection can be enhanced by using additional directions such as 45° and -
45°, which help in identifying edges that are not aligned with the primary axes.

Tasks:

 Task 5: Apply Sobel in 45° and -45° directions.


 Task 6: Combine all four Sobel results (x, y, 45°, and -45°) to create a comprehensive
edge map. You may simply apply the formula

M =G x +G y + G45+G−45

4. Kirsch Compass Kernel

Explanation: The Kirsch compass kernel enhances edges in multiple directions (eight in total). It
can be particularly useful for detecting edges in images with significant noise or complex
structures.

Example Code:

image = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)


def apply_kirsch(image):
kernels = [
np.array([[5, 5, 5], [-3, 0, -3], [-3, -3, -
3]]), # 0 degrees
Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

np.array([[-3, 5, 5], [-3, 0, 5], [-3, -3, -


3]]), # 45 degrees
# Other directions: 90, 135, etc.
]
max_edge = np.zeros_like(image,
dtype=np.float32)
for kernel in kernels:
edge = cv2.filter2D(image, -1, kernel)
max_edge = np.maximum(max_edge, edge)
return max_edge

kirsch_edge = apply_kirsch(image)
plt.imshow(kirsch_edge, cmap='gray')
plt.title("Kirsch Compass Edge Detection")
plt.show()
Tasks:

 Task 7: Apply the Kirsch compass kernel in all eight directions and combine results.
 Task 8: Compare the Kirsch edge map with Sobel and Prewitt edge maps.

5 & 6. Sobel with and without Smoothing as Pre-Processing

Explanation: Smoothing the image before edge detection (typically with a Gaussian filter)
reduces noise and results in cleaner edges, though it may slightly blur fine details.

Example Code:

image = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)


def sobel_with_smoothing(image, ksize=3):
smooth_image = cv2.GaussianBlur(image, (ksize,
ksize), 0)
sobel = cv2.Sobel(smooth_image, cv2.CV_64F, 1,
0, ksize=3)
return np.abs(sobel)

smooth_sobel = sobel_with_smoothing(image)
Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

plt.imshow(smooth_sobel, cmap='gray')
plt.title("Sobel with Smoothing")
plt.show()
Tasks:

 Task 9: Compare Sobel results on smoothed and non-smoothed images.


 Task 10: Document differences in edge clarity.

7. Edge detection by finding gradients, magnitude and thresholding

Explanation: Thresholding is used to emphasize strong edges by setting weaker gradients to


zero and only keeping values above a certain threshold.

Step-by-Step Task:

1. Calculate Gradients: Use the Sobel filter to compute g x and g y , the gradients in the x
and y directions.
2. Compute Gradient Magnitude and Direction:
o Calculate the magnitude M ( x , y )=√ g x + g y.
2 2

−1 g y
o Calculate the direction α ( x , y )=tan .
gx
3. Apply Thresholding:
o Define a threshold value T . Set any values in M(x,y) below T to zero, and set
value above or equal to T to 255 (or 1 in normalized image).
o This step will help isolate only the most prominent edges.

Python Code Example

Here’s a Python example using OpenCV and NumPy to achieve this:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load a grayscale image


image = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)

# Step 1: Calculate gradients using Sobel filter


Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

g_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) #


Gradient in x direction
g_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3) #
Gradient in y direction

# Step 2: Calculate gradient magnitude and direction


magnitude = np.abs(g_x) + np.abs(g_y)
direction = np.arctan2(g_y, g_x) * (180 / np.pi) #
Direction in degrees

# Step 3: Apply thresholding


threshold = 100 # You can adjust this value
magnitude_thresholded = np.where(magnitude >
threshold, magnitude, 0)

# Display Results
plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')

plt.subplot(2, 2, 2)
plt.title("Gradient Magnitude")
plt.imshow(magnitude, cmap='gray')

plt.subplot(2, 2, 3)
plt.title("Direction (Degrees)")
plt.imshow(direction, cmap='jet') # Display with
color map for orientation

plt.subplot(2, 2, 4)
plt.title("Thresholded Magnitude")
plt.imshow(magnitude_thresholded, cmap='gray')
Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

plt.tight_layout()
plt.show()

8. Canny Edge Detector

Explanation: Canny edge detection is a multi-stage algorithm involving smoothing, gradient


calculation, non-maximum suppression, and edge tracking by hysteresis, producing cleaner
edges than simpler operators.

def apply_canny(image, low_thresh=50,


high_thresh=150):
return cv2.Canny(image, low_thresh, high_thresh)

canny_edges = apply_canny(image)
plt.imshow(canny_edges, cmap='gray')
plt.title("Canny Edge Detection")
plt.show()

Tasks:

 Task 12: Experiment with different threshold values and levels of smoothing.

9. Image Segmentation Using Global Thresholding

Explanation: Thresholding is a basic image segmentation technique, dividing the image into
foreground and background regions based on intensity levels.

Tasks:

 Task 13: Implement the global thresholding discussed in the provided slides.

Additional Tasks:
Digital Image Processing
22CS Fall 2024
Lab: 11-12 (Graded) Advanced Edge Detection and Image Segmentation

Task 14: Modify the source code of box filter to create a function named Edge_sodel that
calculate sobel g x , g y , M (x , y) in the loop. Once loop calculate M (x , y ) for each pixel, apply
threshold outside of the loop. The function should take threshold and input image as input and
return the edge image.

Submission

Submit the following:

 Screenshots: Capture before-and-after images for each task.


 Code: Submit well-documented code for each task.
 Analysis Report: Summarize the effects of different operators and techniques on edge
detection and segmentation.

You might also like