Edge Dedection Exp-6
import cv2
import matplotlib.pyplot as plt
import numpy as np
# Canny
img = cv2.imread('butterfly.jpg')
# converting the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0) # the second parm is the size of the kernel
# wider the threshold range, more the edges
canny = cv2.Canny(img, threshold1=180, threshold2=200)
fig, axs = plt.subplots(2, 2)
titles = ['Original', 'Grayscale', 'Gaussian Blur', 'Canny']
axs[0, 0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
axs[0, 0].set_title(titles[0])
axs[0, 0].axis('off')
axs[0, 1].imshow(cv2.cvtColor(gray, None))
axs[0, 1].set_title(titles[1])
axs[0, 1].axis('off')
axs[1, 0].imshow(cv2.cvtColor(blur, None))
axs[1, 0].set_title(titles[2])
axs[1, 0].axis('off')
axs[1, 1].imshow(cv2.cvtColor(canny, None))
axs[1, 1].set_title(titles[3])
axs[1, 1].axis('off')
# Sobel
sobelx = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=3) # along the X
axis
sobely = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=3) # along the Y
axis
sobelxy = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=3) # Combined X & Y
fig, axs = plt.subplots(2, 2)
titles = ['Original', 'Sobel along X-axis', 'Sobel along Y-axis', 'Sobel along both X
and Y axis']
axs[0, 0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
axs[0, 0].set_title(titles[0])
axs[0, 0].axis('off')
axs[0, 1].imshow(sobelxy, cmap='gray')
axs[0, 1].set_title(titles[3])
axs[0, 1].axis('off')
axs[1, 0].imshow(sobelx, cmap='gray')
axs[1, 0].set_title(titles[1])
axs[1, 0].axis('off')
axs[1, 1].imshow(sobely, cmap='gray')
axs[1, 1].set_title(titles[2])
axs[1, 1].axis('off')
# Prewitt
# Defining the kernels
kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
# Applying convolution
img_prewittx = cv2.filter2D(blur, -1, kernelx)
img_prewitty = cv2.filter2D(blur, -1, kernely)
img_prewitt = img_prewittx + img_prewitty
fig, axs = plt.subplots(2, 2)
titles = ['Original', 'Kernel X', 'Kernel Y', 'Kernel X and Y']
axs[0, 0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
axs[0, 0].set_title(titles[0])
axs[0, 0].axis('off')
axs[0, 1].imshow(img_prewitt, cmap='gray')
axs[0, 1].set_title(titles[3])
axs[0, 1].axis('off')
axs[1, 0].imshow(img_prewittx, cmap='gray')
axs[1, 0].set_title(titles[1])
axs[1, 0].axis('off')
axs[1, 1].imshow(img_prewitty, cmap='gray')
axs[1, 1].set_title(titles[2])
axs[1, 1].axis('off')
Comments
Post a Comment