Challenge

Project 2

#Prewitt Filter

import cv2
import numpy as np


def read_image(image_path):
    """This function reads any image from a given path"""
    image = cv2.imread(image_path)
    return image

def gaussian_filter(image,filter_size,sigma):
    """This function uses gaussian filter to remove image noise"""
    filtered_image = cv2.GaussianBlur(image,(filter_size, filter_size),sigma)
    return filtered_image

def prewitt_filter(any_image):
    """This function uses gaussian filter to remove image noise"""
    image = gaussian_filter(any_image,filter_size=filter_dim,sigma=sigma_val)
    vertical_filter = np.array([[-1,-1,-1],[0,0,0],[1,1,1]])
    horizontal_filter = np.array([[-1,0,1],[-1,0,1],[-1,0,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)  #0.5 is the sqrt of the abs values
    return grad

def save_image(image_name_format, image):
    """This function saves any image to a given path"""
    cv2.imwrite(image_name_format, image)
    
    
filter_dim = 5 #A matrix for the gaussian filter
sigma_val = 5 #sigma is the standard deviation

image = read_image('Challenge_2.PNG')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #converts the RGB color first into grey sale using opencv function

prewitt_filtered_image = prewitt_filter(gray_image)

cv2.imshow('Prewitt Edge Detection', np.hstack((gray_image,prewitt_filtered_image)))
cv2.waitKey(0)

save_image("result image\\Gray_image_saved.jpg",gray_image)
save_image("result image\\Prewitt_image_saved.jpg",prewitt_filtered_image)
#Laplacian filter

import cv2
import numpy as np

def read_image(image_path):
    """This function reads any image from a given path"""
    image = cv2.imread(image_path)
    return image


def laplacian_filter(image, ksize):
    """This function uses laplacian filter to detect image edges"""
    filtered_image = cv2.Laplacian(image,ksize=ksize, ddepth=cv2.CV_64F)
    return filtered_image

def save_image(image_name_format, image):
    """This function saves any image to a given path"""
    cv2.imwrite(image_name_format, image)

ksize=5

image = read_image('Challenge_2.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #converts the RGB color first into grey sale using opencv function

laplacian_filtered_image = laplacian_filter(gray_image, ksize=ksize)

cv2.imshow('Laplacian Edge Detection', np.hstack((gray_image, laplacian_filtered_image)))
cv2.waitKey(0)

save_image("result image\\laplacian_image_saved_ksize5.jpg",laplacian_filtered_image)
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.