0% found this document useful (0 votes)
4 views12 pages

22aie313 Lab2 22125

The document provides a comprehensive overview of various edge detection techniques using Python and OpenCV, including Prewitt, Sobel, Laplacian, Robinson Compass, Kirsch Compass, and Canny's Edge Detection. Each method involves reading and processing an image, applying specific filters, and visualizing the results through plots. The document includes code snippets for each technique, demonstrating how to implement these filters and visualize the original, grayscale, and filtered images.

Uploaded by

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

22aie313 Lab2 22125

The document provides a comprehensive overview of various edge detection techniques using Python and OpenCV, including Prewitt, Sobel, Laplacian, Robinson Compass, Kirsch Compass, and Canny's Edge Detection. Each method involves reading and processing an image, applying specific filters, and visualizing the results through plots. The document includes code snippets for each technique, demonstrating how to implement these filters and visualize the original, grayscale, and filtered images.

Uploaded by

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

Filters

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

image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

horizontal_filter = np.array([[-1, -1, -1],


[0, 0, 0],
[1, 1, 1]])

vertical_filter = np.array([[-1, 0, 1],


[-1, 0, 1],
[-1, 0, 1]])

horizontal_edges = cv2.filter2D(gray_image, -1, horizontal_filter)


vertical_edges = cv2.filter2D(gray_image, -1, vertical_filter)

fig, axes = plt.subplots(1, 4, figsize=(15, 5))

titles = ["Original Image", "Grayscale Image", "Horizontal Edges",


"Vertical Edges"]
images = [image, gray_image, horizontal_edges, vertical_edges]

for i, ax in enumerate(axes):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))

ax.set_title(titles[i])
ax.axis("off")

plt.tight_layout()
plt.show()
Sobel Filter
import cv2
import numpy as np
import matplotlib.pyplot as plt

image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

horizontal_filter = np.array([[-1, -2, -1],


[0, 0, 0],
[1, 2, 1]])

vertical_filter = np.array([[-1, 0, 1],


[-2, 0, 23],
[-1, 0, 1]])

horizontal_edges = cv2.filter2D(gray_image, -1, horizontal_filter)


vertical_edges = cv2.filter2D(gray_image, -1, vertical_filter)

fig, axes = plt.subplots(1, 4, figsize=(15, 5))

titles = ["Original Image", "Grayscale Image", "Horizontal Edges",


"Vertical Edges"]
images = [image, gray_image, horizontal_edges, vertical_edges]

for i, ax in enumerate(axes):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))

ax.set_title(titles[i])
ax.axis("off")

plt.tight_layout()
plt.show()
Laplacian Filter
import cv2
import numpy as np
import matplotlib.pyplot as plt

image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

laplacian_filter_p = np.array([[0, -1, 0],


[-1, 4, -1],
[0, -1, 0]])

laplacian_filter_n = np.array([[0, 1, 0],


[1, -4, 1],
[0, 1, 0]])

filtered_edges_p = cv2.filter2D(gray_image, -1, laplacian_filter_p)


filtered_edges_n = cv2.filter2D(gray_image, -1, laplacian_filter_n)

fig, axes = plt.subplots(1, 4, figsize=(15, 5))

titles = ["Original Image", "Grayscale Image", "Filtered Image


Positive", "Filtered Image Negative"]
images = [image, gray_image, filtered_edges_p, filtered_edges_n]

for i, ax in enumerate(axes):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))

ax.set_title(titles[i])
ax.axis("off")

plt.tight_layout()
plt.show()
Robinson Compass
import cv2
import numpy as np
import matplotlib.pyplot as plt

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

image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

filtered_images = []
for mask in robinson_masks:
filtered_image = cv2.filter2D(gray_image, -1, mask)
filtered_images.append(filtered_image)

fig, axes = plt.subplots(3, 4, figsize=(10, 10))


axes = axes.ravel()

titles = ["Original Image", "Grayscale Image"] + [f"Robinson Mask


{i+1}" for i in range(len(robinson_masks))]
images = [image, gray_image] + filtered_images

for i, ax in enumerate(axes):
if i < len(images):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap="gray")
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))
ax.set_title(titles[i])
ax.axis("off")
else:
ax.axis("off")

plt.tight_layout()
plt.show()

Kirsch Compass
import cv2
import numpy as np
import matplotlib.pyplot as plt
kirsch_masks = [
np.array([[ 5, 5, 5], [-3, 0, -3], [-3, -3, -3]]),
np.array([[ 5, 5, -3], [ 5, 0, -3], [-3, -3, -3]]),
np.array([[ 5, -3, -3], [ 5, 0, -3], [ 5, -3, -3]]),
np.array([[-3, -3, -3], [ 5, 0, -3], [ 5, 5, -3]]),
np.array([[-3, -3, -3], [-3, 0, -3], [ 5, 5, 5]]),
np.array([[-3, -3, -3], [-3, 0, 5], [-3, 5, 5]]),
np.array([[-3, -3, 5], [-3, 0, 5], [-3, -3, 5]]),
np.array([[-3, 5, 5], [-3, 0, 5], [-3, -3, -3]])
]

image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

filtered_images = []
for mask in kirsch_masks:
filtered_image = cv2.filter2D(gray_image, -1, mask)
filtered_images.append(filtered_image)

fig, axes = plt.subplots(3, 4, figsize=(10, 10))


axes = axes.ravel()

titles = ["Original Image", "Grayscale Image"] + [f"Kirsch Mask {i+1}"


for i in range(len(kirsch_masks))]
images = [image, gray_image] + filtered_images

for i, ax in enumerate(axes):
if i < len(images):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap="gray")
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))
ax.set_title(titles[i])
ax.axis("off")
else:
ax.axis("off")

plt.tight_layout()
plt.show()
Canny's Edge Detection
import numpy as np
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('/content/einstein-8041625_1280.webp')
image = cv2.resize(image, (500, 500))

STEP 1: Smoothening
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
guassian_blur = cv2.GaussianBlur(gray_image, (5,5), 1)
fig, axes = plt.subplots(1, 2, figsize=(10, 5))

titles = ["Original Image", "Smoothen image"]


images = [gray_image, guassian_blur]

for i, ax in enumerate(axes):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))

ax.set_title(titles[i])
ax.axis("off")

plt.tight_layout()
plt.show()

### STEP 2: Finding Gradient Images

horizontal_filter = np.array([[-1, -2, -1],


[0, 0, 0],
[1, 2, 1]])

vertical_filter = np.array([[-1, 0, 1],


[-2, 0, 2],
[-1, 0, 1]])

horizontal_edges = cv2.filter2D(guassian_blur, -1, horizontal_filter)


vertical_edges = cv2.filter2D(guassian_blur, -1, vertical_filter)
fig, axes = plt.subplots(1, 3, figsize=(10, 5))

titles = ["Guassian Blur", "Gx", "Gy"]


images = [guassian_blur, horizontal_edges, vertical_edges]

for i, ax in enumerate(axes):
if len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
else:
ax.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))

ax.set_title(titles[i])
ax.axis("off")

plt.tight_layout()
plt.show()

STEP 3: Calculating gradient magnitude and direction


gradient_magnitude = np.sqrt(horizontal_edges**2 + vertical_edges**2)
gradient_direction = np.arctan2(vertical_edges, horizontal_edges)

fig, axes = plt.subplots(1, 3, figsize=(10, 5))

titles = ["Guassian Blur", "Gradient Magnitude", "Gradient Direction"]


images = [guassian_blur, gradient_magnitude, gradient_direction]

for i, ax in enumerate(axes):
if i == 2:
ax.imshow(images[i], cmap='hsv')
elif len(images[i].shape) == 2:
ax.imshow(images[i], cmap='gray')
ax.set_title(titles[i])
ax.axis("off")
plt.tight_layout()
plt.show()

STEP 4: Non-maximal suppression for each pixel


import numpy as np

def non_max_suppression(gradient_magnitude, gradient_direction):


rows, cols = gradient_magnitude.shape
suppressed = np.zeros_like(gradient_magnitude)

for i in range(1, rows - 1):


for j in range(1, cols - 1):
angle = gradient_direction[i, j] * 180 / np.pi
if angle < 0:
angle += 180

if (0 <= angle < 22.5) or (157.5 <= angle <= 180):


neighbors = [gradient_magnitude[i, j - 1],
gradient_magnitude[i, j + 1]]
elif (22.5 <= angle < 67.5):
neighbors = [gradient_magnitude[i - 1, j - 1],
gradient_magnitude[i + 1, j + 1]]
elif (67.5 <= angle < 112.5):
neighbors = [gradient_magnitude[i - 1, j],
gradient_magnitude[i + 1, j]]
else:
neighbors = [gradient_magnitude[i - 1, j + 1],
gradient_magnitude[i + 1, j - 1]]

if gradient_magnitude[i, j] >= max(neighbors):


suppressed[i, j] = gradient_magnitude[i, j]

return suppressed

suppressed_image = non_max_suppression(gradient_magnitude,
gradient_direction)

fig, ax = plt.subplots(1, 1, figsize=(5, 5))


ax.imshow(suppressed_image, cmap='gray')
ax.set_title("Non-Maximal Suppression")
ax.axis("off")
plt.show()

STEP 5: Hysteresis Thresholding

def hysteresis_thresholding(suppressed_image,
low_threshold_ratio=0.01, high_threshold_ratio=0.09):
high_threshold = suppressed_image.max() * high_threshold_ratio
low_threshold = high_threshold * low_threshold_ratio

rows, cols = suppressed_image.shape


result = np.zeros_like(suppressed_image)

strong_edges = suppressed_image > high_threshold


weak_edges = (suppressed_image >= low_threshold) &
(suppressed_image <= high_threshold)

result[strong_edges] = 255
for i in range(1, rows - 1):
for j in range(1, cols - 1):
if weak_edges[i, j]:
if np.any(strong_edges[i-1:i+2, j-1:j+2]):
result[i, j] = 255

return result

hysteresis_image = hysteresis_thresholding(suppressed_image)

fig, ax = plt.subplots(1, 1, figsize=(5, 5))


ax.imshow(hysteresis_image, cmap='gray')
ax.set_title("Hysteresis Thresholding")
ax.axis("off")
plt.show()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy