import cv2 # cv2 is the importing for Opencv
# Opencv is a library of Python bindings designed to solve computer vision problems
import numpy as np # np is an alias for numpy
# general-purpose array-processing package.
# It provides a high-performance multidimensional array object and tools for working with these arrays
# Gaussian filter
def gaussian_filter(image, filter_size, sigma):
filtered_image = cv2.GaussianBlur(image, (filter_size, filter_size), sigma)
return filtered_image
# Prewitt filter
def prewitt_filter(image):
image = gaussian_filter(image,5,5)
# vertical filter
vertical_filter = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
# horizontal filter
horizontal_filter = np.array([[-1,-1,-1],[0,0,0],[1,1,1]])
vertical_filtered = cv2.filter2D(image,-1,vertical_filter)
horizontal_filtered = cv2.filter2D(image,-1,horizontal_filter)
abs_grad_x = cv2.convertScaleAbs(vertical_filtered)
abs_grad_y = cv2.convertScaleAbs(horizontal_filtered)
grad = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
return grad
# Laplacian filter
def laplacian_filter(image, ddepth, ksize):
G_filtered_image = gaussian_filter(image,5,5)
gray_image = cv2.cvtColor(G_filtered_image, cv2.COLOR_BGR2GRAY)
laplace_image = cv2.Laplacian(gray_image, ddepth = ddepth, ksize=ksize)
filtered_image = cv2.convertScaleAbs(laplace_image)
return filtered_image
# MAIN FUNCTION
image = cv2.imread('Challenge2.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
prewitt_filtered_image = prewitt_filter(gray_image)
cv2.imshow('Prewitt Filter', np.hstack((gray_image, prewitt_filtered_image)))
cv2.imwrite('Prewitt_Image.png', prewitt_filtered_image)
cv2.waitKey(0)
image = cv2.imread('Challenge2.png')
laplacian_filtered_image = laplacian_filter(image,cv2.CV_16S,3)
cv2.imshow('Laplacian Filter', np.hstack((gray_image, laplacian_filtered_image)))
cv2.imwrite('Laplacian_Image.png', laplacian_filtered_image)
cv2.waitKey(0)
# Comparing Prewitt filtered Image v/s Laplacian filtered Image
cv2.imwrite('Prewitt_Laplacian.png',np.hstack((prewitt_filtered_image,laplacian_filtered_image)))
# Compare both the images and justify which output is better than the other
'''
By comparing both the images, Laplacian filtered image is more detailed than Prewitt filtered image. So Laplacian output is better than Prewitt output.
As we know, the Laplacian filter is a second-order derivative that gives fine, thick visible edges
and where Prewitt filter is first-order derivative which gives fine and thick edges but some are invisible edges
'''