BAHRIA UNIVERSITY, ISLAMABAD
Department of Computer Science
CEN 444
Digital Image Processing
Lab Journal 9
Student Name: _____________________SAAD AHMED_______
Enrolment No.: _01-134211-077_________________________________
Title: Spatial Filtering
Objectives: to introduce to the process of Filtering. To understand functions for Smoothing and
Sharpening filters.
Tools Used: Python
Procedure: Open IDLE and perform the following tasks
import cv2
import numpy as np
img = cv2.imread("Your_image.jpg")
img = cv2.resize(img, (0, 0), None, .25, .25)
gaussianBlurKernel = np.array(([[1, 2, 1], [2, 4, 2], [1, 2, 1]]), np.float
32)/9
sharpenKernel = np.array(([[0, -1, 0], [-1, 9, -1], [0, -1, 0]]), np.float3
2)/9
meanBlurKernel = np.ones((3, 3), np.float32)/9
gaussianBlur = cv2.filter2D(src=img, kernel=gaussianBlurKernel, ddepth=-1)
meanBlur = cv2.filter2D(src=img, kernel=meanBlurKernel, ddepth=-1)
sharpen = cv2.filter2D(src=img, kernel=sharpenKernel, ddepth=-1)
horizontalStack = np.concatenate((img, gaussianBlur, meanBlur, sharpen), ax
is=1)
Digital Image Processing Lab Journal
cv2.imwrite("Output.jpg", horizontalStack)
cv2.imshow("2D Convolution Example", horizontalStack)
cv2.waitKey(0)
cv2.destroyAllWindows()
The Filter2D operation convolves an image with the kernel. You can perform this operation on an
image using the Filter2D() method of the imgproc class. Following is the documentation of this
method −
filter2D(src, dst, ddepth, kernel)
This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
ddepth − A variable of the type integer representing the depth of the output image.
kernel − A Mat object representing the convolution kernel.
Average Filtering with 5x5 kernel
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('/content/sample_data/images/cameraman.png')
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img,-1,kernel)
plt.figure(figsize=(10,10))
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
plt.show()
Using blur Function
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('/content/sample_data/images/cameraman.png')
blur = cv2.blur(img,(5,5))
plt.figure(figsize=(10,10))
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()
Some other functions:
Digital Image Processing Lab Journal
cv2.GaussianBlur().
cv2.getGaussianKernel().
cv2.medianBlur()
median = cv2.medianBlur(img,5)
LAB PRACTICE TASK 01 :
2d convolution:
import cv2
import numpy as np
img = cv2.imread("myimg.jpeg")
img = cv2.resize(img, (0, 0), None, .25, .25)
gaussianBlurKernel = np.array(([[1, 2, 1], [2, 4, 2], [1, 2, 1]]), np.float32)/9
sharpenKernel = np.array(([[0, -1, 0], [-1, 9, -1], [0, -1, 0]]), np.float32)/9
meanBlurKernel = np.ones((3, 3), np.float32)/9
gaussianBlur = cv2.filter2D(src=img, kernel=gaussianBlurKernel, ddepth=-1)
meanBlur = cv2.filter2D(src=img, kernel=meanBlurKernel, ddepth=-1)
sharpen = cv2.filter2D(src=img, kernel=sharpenKernel, ddepth=-1)
horizontalStack = np.concatenate((img, gaussianBlur, meanBlur, sharpen), axis=1)
cv2.imwrite("Output.jpg", horizontalStack)
cv2.imshow("2D Convolution Example", horizontalStack)
Digital Image Processing Lab Journal
cv2.waitKey(0)
cv2.destroyAllWindows()
LAB PRACTICE TASK 02 :
Average Filtering with 5x5 kernel :
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("myimg.jpeg")
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img,-1,kernel)
plt.figure(figsize=(10,10))
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
plt.show()
Digital Image Processing Lab Journal
LAB PRACTICE TASK 03 :
Using blur Function :
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("myimg.jpeg")
blur = cv2.blur(img,(5,5))
plt.figure(figsize=(10,10))
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
Digital Image Processing Lab Journal
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()
Task 1
Read an image of your choice. Apply average and gaussian filters of size 5x5
individually and identify the differences b/w their results.
import cv2
import numpy as np
# Read the image
image = cv2.imread('myimg.jpeg')
# Apply average filter (also known as box filter)
average_filtered = cv2.blur(image, (5, 5))
Digital Image Processing Lab Journal
# Apply Gaussian filter
gaussian_filtered = cv2.GaussianBlur(image, (5, 5), 0)
# Display the original image and filtered images
cv2.imshow('Original Image', image)
cv2.imshow('Average Filtered Image', average_filtered)
cv2.imshow('Gaussian Filtered Image', gaussian_filtered)
cv2.waitKey(0)
cv2.destroyAllWindows()
Task 2
Read an image of your choice which has salt and pepper noise. Apply rank filter of
size 5x5 using rank = 13. What is the other name of this filtering? If you use rank = 1
or 25, will the noise increase or decrease?
import cv2
import numpy as np
# Read the image with salt and pepper noise
image = cv2.imread('saltpeppernoise.jpeg', cv2.IMREAD_GRAYSCALE)
Digital Image Processing Lab Journal
# Apply median (rank) filter with size 5x5 and rank 5
filtered_image = cv2.medianBlur(image, 5)
# Display the original and filtered images
cv2.imshow('Original Image', image)
cv2.imshow('Filtered Image', filtered_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
Task 3
Read the image. Write a function named ‘mylaplacian’ to MANUALLY code/implement
2nd order derivate of above read image in order to extract horizontal and vertical
edges, collectively. Also, compare your results with ‘Sobel’ filter and state your
findings.
[Code Hint]: You need to perform filtering with the following masks.
Vertical Edges:
g(x, y) = f(x + 1, y) + f(x – 1, y) – 2f(x, y)
Horizontal Edges:
g(x, y) = f(x , y + 1) + f(x, y - 1) – 2f(x, y)
import cv2
Digital Image Processing Lab Journal
import numpy as np
# Read the image
image = cv2.imread('myimg.jpeg', cv2.IMREAD_GRAYSCALE)
# Define the manual Laplacian filter function
def mylaplacian(image):
# Define the masks for vertical and horizontal edges
vertical_mask = np.array([[0, 1, 0],
[0, -2, 0],
[0, 1, 0]])
horizontal_mask = np.array([[0, 0, 0],
[1, -2, 1],
[0, 0, 0]])
# Apply the vertical and horizontal masks
vertical_edges = cv2.filter2D(image, -1, vertical_mask)
horizontal_edges = cv2.filter2D(image, -1, horizontal_mask)
# Combine the vertical and horizontal edges
combined_edges = cv2.addWeighted(vertical_edges, 0.5, horizontal_edges, 0.5, 0)
return combined_edges
# Apply the manual Laplacian filter
manual_laplacian_image = mylaplacian(image)
Digital Image Processing Lab Journal
# Apply the Sobel filter
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
sobel_edges = cv2.addWeighted(cv2.convertScaleAbs(sobel_x), 0.5,
cv2.convertScaleAbs(sobel_y), 0.5, 0)
# Display the results
cv2.imshow('Original Image', image)
cv2.imshow('Manual Laplacian Edges', manual_laplacian_image)
cv2.imshow('Sobel Edges', sobel_edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT :
Submission Date:
Digital Image Processing Lab Journal