0% found this document useful (0 votes)
55 views

DIP Lab Manual No 06

This document discusses various image filtering techniques in digital image processing, including low-pass filters, high-pass filters, and different types of blurring filters. It provides examples of averaging filtering, Gaussian filtering, median filtering, and bilateral filtering using OpenCV functions. It also discusses image sharpening using Laplacian operators. The learning outcomes are to blur images with various low-pass filters, apply custom filters using 2D convolution, and apply a sharpening filter. The lab task is to add Gaussian and salt-and-pepper noise to an image.

Uploaded by

myfirst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

DIP Lab Manual No 06

This document discusses various image filtering techniques in digital image processing, including low-pass filters, high-pass filters, and different types of blurring filters. It provides examples of averaging filtering, Gaussian filtering, median filtering, and bilateral filtering using OpenCV functions. It also discusses image sharpening using Laplacian operators. The learning outcomes are to blur images with various low-pass filters, apply custom filters using 2D convolution, and apply a sharpening filter. The lab task is to add Gaussian and salt-and-pepper noise to an image.

Uploaded by

myfirst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING


COMPUTER ENGINEERING DEPARTMENT

Digital Image Processing

Lab Manual No 06

Image Filtering, Filters and Filter specifications

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

Learning Outcomes:-

• Blur images with various low pass filters


• Apply custom-made filters to images (2D convolution)
• Apply sharpening filter on the images

2D Convolution (Image Filtering):

As for one-dimensional signals, images also can be filtered with various low-pass filters (LPF),
high-pass filters (HPF), etc. A LPF helps in removing noise, or blurring the image. A HPF filters
helps in finding edges in an image. OpenCV provides a function, cv2.filter2D(), to convolve a
kernel with an image. As an example, we will try an averaging filter on an image. A 5x5 averaging
filter kernel can be defined as follows:

Filtering with the above kernel results in the following being performed: for each pixel, a 5x5
window is centered on this pixel, all pixels falling within this window are summed up, and the
result is then divided by 25. This equates to computing the average of the pixel values inside that
window. This operation is performed for all the pixels in the image to produce the output filtered
image. Try this code and check the result:
import cv2

import numpy as np

from matplotlib import pyplot as plt

img = cv2.imread('opencv_logo.jpg')

kernel = np.ones((5,5),np.float32)/25

dst = cv2.filter2D(img,-1,kernel)

plt.subplot(121),plt.imshow(img),plt.title('Original')

plt.xticks([]), plt.yticks([])

plt.subplot(122),plt.imshow(dst),plt.title('Averaging')

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

plt.xticks([]), plt.yticks([])

plt.show()

Image Blurring (Image Smoothing):

Image blurring is achieved by convolving the image with a low-pass filter kernel. It is useful for
removing noise. It actually removes high frequency content (e.g: noise, edges) from the image
resulting in edges being blurred when this is filter is applied. (Well, there are blurring techniques
which do not blur edges). OpenCV provides mainly four types of blurring techniques.

Averaging:

This is done by convolving the image with a normalized box filter. It simply takes the average of
all the pixels under kernel area and replaces the central element with this average. This is done by
the function cv2.blur() or cv2.boxFilter(). We should specify the width and height of kernel. A
3x3 normalized box filter would look like this:

If you don’t want to use a normalized box filter, use cv2.boxFilter() and pass the argument
normalize=False to the function.

Check the sample demo below with a kernel of 5x5 size:


import cv2

import numpy as np

from matplotlib import pyplot as plt

img = cv2.imread('opencv_logo.jpg')

blur = cv2.blur(img,(5,5))

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([])

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

plt.show()

Gaussian Filtering:

In this approach, instead of a box filter consisting of equal filter coefficients, a Gaussian kernel is
used. It is done with the function, cv2.GaussianBlur(). We should specify the width and height of
the kernel which should be positive and odd. We also should specify the standard deviation in
the X and Y directions, sigmaX and sigmaY respectively. If only sigmaX is specified, sigmaY is
taken as equal to sigmaX. If both are given as zeros, they are calculated from the kernel size.
Gaussian filtering is highly effective in removing Gaussian noise from the image.

If you want, you can create a Gaussian kernel with the function, cv2.getGaussianKernel().

The above code can be modified for Gaussian blurring:


blur = cv2.GaussianBlur(img,(5,5),0)

Median Filtering:

Here, the function cv2.medianBlur() computes the median of all the pixels under the kernel
window and the central pixel is replaced with this median value. This is highly effective in
removing salt-and-pepper noise. One interesting thing to note is that, in the Gaussian and box
filters, the filtered value for the central element can be a value which may not exist in the original
image. However this is not the case in median filtering, since the central element is always replaced
by some pixel value in the image. This reduces the noise effectively. The kernel size must be a
positive odd integer.

In this demo, we add a 50% noise to our original image and use a median filter. Check the result:
median = cv2.medianBlur(img,5)

Bilateral Filtering:

As we noted, the filters we presented earlier tend to blur edges. This is not the case for the bilateral
filter, cv2.bilateralFilter(), which was defined for, and is highly effective at noiseremoval while
preserving edges. But the operation is slower compared to other filters. We already saw that a
Gaussian filter takes a neighborhood around the pixel and finds its Gaussian weighted average.
This Gaussian filter is a function of space alone, that is, nearby pixels are considered while
filtering. It does not consider whether pixels have almost the same intensity value and does not
consider whether the pixel lies on an edge or not. The resulting effect is that Gaussian filters tend
to blur edges, which is undesirable.

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

The bilateral filter also uses a Gaussian filter in the space domain, but it also uses one more
(multiplicative) Gaussian filter component which is a function of pixel intensity differences. The
Gaussian function of space makes sure that only pixels are ‘spatial neighbors’ are considered for
filtering, while the Gaussian component applied in the intensity domain (a Gaussian function of
intensity differences) ensures that only those pixels with intensities similar to that of the central
pixel (‘intensity neighbors’) are included to compute the blurred intensity value. As a result, this
method preserves edges, since for pixels lying near edges, neighboring pixels placed on the other
side of the edge, and therefore exhibiting large intensity variations when compared to the central
pixel, will not be included for blurring.

The sample below demonstrates the use of bilateral filtering.


blur = cv2.bilateralFilter(img,9,75,75)

Image Sharpening:

Laplacian Operator is also a derivative operator which is used to find edges in an image. The major
difference between Laplacian and other operators like Prewitt, Sobel, Robinson and Kirsch is that
these all are first order derivative masks but Laplacian is a second order derivative mask. In this
mask we have two further classifications one is Positive Laplacian Operator and other is Negative
Laplacian Operator.

Positive Operator:

0 1 0

1 -4 1

0 1 0

Negative Operator:

0 -1 0

-1 4 -1

0 -1 0

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

Laplacian is a derivative operator; its uses highlight gray level discontinuities in an image and try
to deemphasize regions with slowly varying gray levels. This operation in result produces such
images which have grayish edge lines and other discontinuities on a dark background. This
produces inward and outward edges in an image

The important thing is how to apply these filters onto image. Remember we can’t apply both the
positive and negative Laplacian operator on the same image. we have to apply just one but the
thing to remember is that if we apply positive Laplacian operator on the image then we subtract
the resultant image from the original image to get the sharpened image. Similarly, if we apply
negative Laplacian operator then we have to add the resultant image onto original image to get the
sharpened image.

Example:
import cv2
import numpy as np# Reading in and displaying our image
image = cv2.imread('images/input.jpg')
cv2.imshow('Original', image)# Create our shapening kernel, it must equal to one
eventually
kernel_sharpening = np.array([[-1,-1,-1],
[-1, 9,-1],
[-1,-1,-1]])# applying the sharpening kernel to the
input image & displaying it.
sharpened = cv2.filter2D(image, -1, kernel_sharpening)
cv2.imshow('Image Sharpening', sharpened)cv2.waitKey(0)
cv2.destroyAllWindows()

Lab Task:

1. Take your own image, add Gaussian noise and salt and pepper noise, compare
the effect of blurring via box, Gaussian, median and bilateral filters
for both noisy images, as you change the level of noise.
2. Apply Laplacian, Prewitt, Sobel, Robinson and Kirsch masks on
laplacian.jpg and your own image and interpret the results and compare
and analyze the effects of different masks.
3. Write a Python program to apply a mean filter on an image with salt- and-
pepper noise. Describe the output, including the mean filter’s ability to
remove the noise.
4. Describe how effective the mean filter is in removing salt-and-pepper
noise. Based on your understanding of the median filter, can you
explain why the mean filter cannot remove salt-and-pepper noise?
5. Read image eight_pepper.tif and eight_salt.tif and perform median and
average filtering without using built-in python functions.

Digital Image Processing Lab Instructor:- Sheharyar Khan


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT

6. Read task6.tif image and design an algorithm to remove the noise from
the image.
7. Implement the contrast stretching by histogram modification method. Make
the range of histogram values [a,b]and [ZI,Zk]as variables. Take a poor
contrast image and do experiments to see the effect of contrast
enhancement by histogram modification. Implement several different
contrast enhancement methods and comment on their performance.
8. Implement the Gaussian smoothing filter. Apply this filter to an image
by selecting several (at least five) different values of (σ See the
amount of smoothing. How would you select the correct (σ value for an
image?

Digital Image Processing Lab Instructor:- Sheharyar Khan

You might also like