import cv2
import numpy as np
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):
#smoothing image using low pass filter-Gaussian Filter
image = gaussian_filter(image,5,5)
#Creating horizontal and vertical masking
horizontal_filter = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
vertical_filter = np.array([[-1,-1,-1],[0,0,0],[1,1,1]])
#cv2.filter2D(), to convolve horizontal and vertical mask with image.
vertical_filtered = cv2.filter2D(image,-1,vertical_filter)
horizontal_filtered = cv2.filter2D(image,-1,horizontal_filter)
#calculates absolute values and converts the result to 8-bit.
abs_grad_x = cv2.convertScaleAbs(vertical_filtered)
abs_grad_y = cv2.convertScaleAbs(horizontal_filtered)
#adding images is through blending them so that they both can be visible together. We can give different weights to different images,
#which can make the image transparent or translucent according to the weight added.
grad = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
return grad
#laplacian filter
def laplacian_filter(image):
# cv2.Laplacian(image_name,output_datatype,kernal_size)
laplacian_filtered = cv2.Laplacian(image, cv2.CV_64F, ksize=3)
#calculates absolute values and converts the result to 8-bit.
abs_laplacian_filtered = cv2.convertScaleAbs(laplacian_filtered)
return abs_laplacian_filtered
image = cv2.imread('Challenge_2_1638960812.PNG')
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
prewitt_edges = prewitt_filter(gray_image)
cv2.imwrite('prewitt_challenge2.PNG',prewitt_edges)
cv2.imshow('prewitt image',np.hstack((gray_image,prewitt_edges)))
cv2.waitKey(0)
laplacian_edges = laplacian_filter(gray_image)
cv2.imwrite('laplacian_challenge2.PNG',laplacian_edges)
cv2.imshow('laplacian image',np.hstack((gray_image,laplacian_edges)))
cv2.waitKey(0)
cv2.imwrite('comparison_between_prewitt_and_laplacian_filter_image_challenge2.PNG',np.hstack((prewitt_edges,laplacian_edges)))
cv2.imshow('comparison between prewitt and laplacian filter image',np.hstack((prewitt_edges,laplacian_edges)))
cv2.waitKey(0)
# prewitt filter is first order derivative mask and laplacian filter is second order derivative mask.
#Prewitt filter measures the slope while the Laplacian filter measures the slope change.
#So, the Laplacian filter highlights the regions where the pixel intensities dramatically change.
#Therefore, the Laplacian filter is preferred for edge detection