0% found this document useful (0 votes)
13 views24 pages

Lecture 4 AI Summary

The document discusses various image processing techniques, including median filtering, Gaussian blur, bilateral filtering, and Canny edge detection, highlighting their advantages and disadvantages. It compares edge detection methods such as Sobel, Prewitt, Laplacian of Gaussian, and Robert's Cross with the Canny method, emphasizing Canny's robustness against noise and its effectiveness in edge detection. Additionally, it provides Python code examples for implementing these techniques using OpenCV and visualizing the results.

Uploaded by

g23ai2114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Lecture 4 AI Summary

The document discusses various image processing techniques, including median filtering, Gaussian blur, bilateral filtering, and Canny edge detection, highlighting their advantages and disadvantages. It compares edge detection methods such as Sobel, Prewitt, Laplacian of Gaussian, and Robert's Cross with the Canny method, emphasizing Canny's robustness against noise and its effectiveness in edge detection. Additionally, it provides Python code examples for implementing these techniques using OpenCV and visualizing the results.

Uploaded by

g23ai2114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Advantages

 Removes noise without blurring edges.

 Works effectively on "salt-and-pepper" noise.

Disadvantages

 Computationally expensive for large kernels.

 Not suitable for Gaussian noise.


import numpy as np

import cv2

import matplotlib.pyplot as plt

def apply_median_filter(image, kernel_size):

"""

Apply a median filter to an image.

Parameters:

image (numpy array): Input grayscale image.

kernel_size (int): Size of the filtering kernel (must be odd).

Returns:

filtered_image (numpy array): Image after applying the median filter.

"""

# Check if kernel size is odd


if kernel_size % 2 == 0:

raise ValueError("Kernel size must be odd.")

# Apply median filter using OpenCV

filtered_image = cv2.medianBlur(image, kernel_size)

return filtered_image

# Load a noisy image

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

# Apply median filter

kernel_size = 3 # 3x3 kernel

filtered_image = apply_median_filter(image, kernel_size)

# Display results

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)

plt.title("Original Image")

plt.imshow(image, cmap='gray')

plt.axis('off')

plt.subplot(1, 2, 2)

plt.title("Median Filtered Image")

plt.imshow(filtered_image, cmap='gray')

plt.axis('off')

plt.show()
import cv2

import numpy as np

import matplotlib.pyplot as plt


def apply_gaussian_blur(image, kernel_size, sigma):

"""

Apply Gaussian blur to an image.

Parameters:

image (numpy array): Input grayscale image.

kernel_size (int): Size of the Gaussian kernel (must be odd).

sigma (float): Standard deviation of the Gaussian kernel.

Returns:

blurred_image (numpy array): Blurred image.

"""

# Apply Gaussian blur using OpenCV

blurred_image = cv2.GaussianBlur(image, (kernel_size, kernel_size), sigma)

return blurred_image

# Load an example image

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

# Apply Gaussian blur

kernel_size = 5 # 5x5 kernel

sigma = 1.5

blurred_image = apply_gaussian_blur(image, kernel_size, sigma)

# Display results

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)

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

plt.axis('off')

plt.subplot(1, 2, 2)

plt.title("Gaussian Blurred Image")

plt.imshow(blurred_image, cmap='gray')

plt.axis('off')

plt.show()
import cv2

import numpy as np

import matplotlib.pyplot as plt

def apply_bilateral_filter(image, diameter, sigma_color, sigma_space):

"""

Apply bilateral filter to an image.

Parameters:

image (numpy array): Input grayscale image.

diameter (int): Diameter of the pixel neighborhood.


sigma_color (float): Filter sigma in the intensity space.

sigma_space (float): Filter sigma in the coordinate space.

Returns:

filtered_image (numpy array): Image after applying the bilateral filter.

"""

# Apply bilateral filter using OpenCV

filtered_image = cv2.bilateralFilter(image, diameter, sigma_color, sigma_space)

return filtered_image

# Load an example image

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

# Apply bilateral filter

diameter = 9 # Diameter of the kernel

sigma_color = 75 # Color intensity standard deviation

sigma_space = 75 # Spatial standard deviation

filtered_image = apply_bilateral_filter(image, diameter, sigma_color, sigma_space)

# Display results

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)

plt.title("Original Image")

plt.imshow(image, cmap='gray')

plt.axis('off')

plt.subplot(1, 2, 2)

plt.title("Bilateral Filtered Image")


plt.imshow(filtered_image, cmap='gray')

plt.axis('off')

plt.show()
Non-Maximum Suppression

For each pixel, compare the gradient magnitude with its neighbors along the gradient
direction:

 Retain the pixel if it is greater than its neighbors.

 Otherwise, suppress it.

Hysteresis Thresholding

If a weak edge is connected to a strong edge, retain it; otherwise, discard it.

import cv2

import numpy as np

import matplotlib.pyplot as plt

def canny_edge_detection(image, sigma, low_threshold, high_threshold):

"""
Apply Canny edge detection to an image.

Parameters:

image (numpy array): Input grayscale image.

sigma (float): Standard deviation for Gaussian smoothing.

low_threshold (float): Low threshold for hysteresis.

high_threshold (float): High threshold for hysteresis.

Returns:

edges (numpy array): Binary edge map.

"""

# Step 1: Gaussian smoothing

blurred_image = cv2.GaussianBlur(image, (5, 5), sigma)

# Step 2: Compute gradients using Sobel filters

Gx = cv2.Sobel(blurred_image, cv2.CV_64F, 1, 0, ksize=3)

Gy = cv2.Sobel(blurred_image, cv2.CV_64F, 0, 1, ksize=3)

gradient_magnitude = np.sqrt(Gx**2 + Gy**2)

gradient_direction = np.arctan2(Gy, Gx) # Orientation in radians

# Step 3: Apply OpenCV's Canny for comparison

edges = cv2.Canny(image, low_threshold, high_threshold)

return edges

# Load an example image

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


# Apply Canny edge detection

sigma = 1.0

low_threshold = 50

high_threshold = 150

edges = canny_edge_detection(image, sigma, low_threshold, high_threshold)

# Display results

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)

plt.title("Original Image")

plt.imshow(image, cmap='gray')

plt.axis('off')

plt.subplot(1, 2, 2)

plt.title("Canny Edge Detection")

plt.imshow(edges, cmap='gray')

plt.axis('off')

plt.show()
Comparison of Edge Detection Methods

Edge detection methods are crucial for identifying object boundaries and significant
transitions in images. Here’s a detailed comparison of the Canny Edge Detector with other
common edge detection methods:

1. Sobel Operator

The Sobel operator detects edges using convolution with derivative filters.

 Advantages:

o Simple and computationally efficient.

o Provides gradient magnitude and direction for edge orientation.


 Disadvantages:

o Sensitive to noise.

o Produces thick edges due to lack of post-processing.

 Applications:

o Quick and approximate edge detection for basic tasks.

 Comparison with Canny:

o Canny incorporates noise reduction (Gaussian smoothing), gradient


magnitude suppression (NMS), and edge tracking, making it more robust and
accurate.

2. Prewitt Operator

Similar to the Sobel operator but uses simpler kernels for gradient calculation.

 Advantages:

o Simpler computation compared to Sobel.

o Useful for detecting vertical and horizontal edges.

 Disadvantages:

o Less accurate for diagonal edges.

o Does not include noise suppression.

 Applications:

o Lightweight tasks requiring edge direction information.

 Comparison with Canny:

o Prewitt lacks noise reduction, non-maximum suppression (NMS), and


hysteresis thresholding, leading to more noise and less precise edges.

3. Laplacian of Gaussian (LoG)

LoG combines Gaussian smoothing with the Laplacian operator to detect edges.

 Advantages:

o Detects edges based on second-order derivatives.

o Suitable for identifying edge-like regions.


 Disadvantages:

o Sensitive to noise despite Gaussian smoothing.

o May detect false edges due to double-zero crossings.

 Applications:

o Tasks requiring fine edge localization.

 Comparison with Canny:

o LoG does not use gradient direction or hysteresis thresholding, making it less
effective in producing thin, connected edges compared to Canny.

4. Robert’s Cross Operator

Detects edges using diagonal gradient approximations.

 Advantages:

o Computationally inexpensive.

o Operates on very small kernels (2×2).

 Disadvantages:

o Very sensitive to noise.

o Poor performance for large-scale images.

 Applications:

o Low-resolution image edge detection.

 Comparison with Canny:

o Robert’s operator is simpler but much less accurate, especially in noisy images
and when edges are complex.
Python code to compare the outputs of different edge-detection methods side by side. It
processes an example grayscale image using the Sobel, Prewitt, LoG, Robert's Cross, and
Canny methods.

import cv2

import numpy as np

import matplotlib.pyplot as plt


# Load an example image in grayscale

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

# 1. Sobel Edge Detection

def sobel_edge_detection(image):

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

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

sobel = cv2.magnitude(sobel_x, sobel_y)

return cv2.convertScaleAbs(sobel)

sobel_edges = sobel_edge_detection(image)

# 2. Prewitt Edge Detection

def prewitt_edge_detection(image):

kernel_x = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])

kernel_y = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])

prewitt_x = cv2.filter2D(image, -1, kernel_x)

prewitt_y = cv2.filter2D(image, -1, kernel_y)

prewitt = cv2.magnitude(prewitt_x, prewitt_y)

return cv2.convertScaleAbs(prewitt)

prewitt_edges = prewitt_edge_detection(image)

# 3. Laplacian of Gaussian (LoG)

def log_edge_detection(image):

blurred = cv2.GaussianBlur(image, (5, 5), 0)

log = cv2.Laplacian(blurred, cv2.CV_64F, ksize=3)


return cv2.convertScaleAbs(log)

log_edges = log_edge_detection(image)

# 4. Robert's Cross Edge Detection

def roberts_edge_detection(image):

kernel_x = np.array([[1, 0], [0, -1]])

kernel_y = np.array([[0, 1], [-1, 0]])

roberts_x = cv2.filter2D(image, -1, kernel_x)

roberts_y = cv2.filter2D(image, -1, kernel_y)

roberts = cv2.magnitude(roberts_x, roberts_y)

return cv2.convertScaleAbs(roberts)

roberts_edges = roberts_edge_detection(image)

# 5. Canny Edge Detection

canny_edges = cv2.Canny(image, 50, 150)

# Visualize the results

plt.figure(figsize=(15, 10))

plt.subplot(2, 3, 1)

plt.title("Original Image")

plt.imshow(image, cmap='gray')

plt.axis('off')

plt.subplot(2, 3, 2)

plt.title("Sobel Edge Detection")


plt.imshow(sobel_edges, cmap='gray')

plt.axis('off')

plt.subplot(2, 3, 3)

plt.title("Prewitt Edge Detection")

plt.imshow(prewitt_edges, cmap='gray')

plt.axis('off')

plt.subplot(2, 3, 4)

plt.title("LoG Edge Detection")

plt.imshow(log_edges, cmap='gray')

plt.axis('off')

plt.subplot(2, 3, 5)

plt.title("Roberts Edge Detection")

plt.imshow(roberts_edges, cmap='gray')

plt.axis('off')

plt.subplot(2, 3, 6)

plt.title("Canny Edge Detection")

plt.imshow(canny_edges, cmap='gray')

plt.axis('off')

plt.tight_layout()

plt.show()

pip install opencv-python matplotlib

You might also like