Вы находитесь на странице: 1из 55

Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India.

Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab1: Image View, Display and Exploration

Viewing, display and storing images are the fundamentals to image processing. The Image
Processing toolbox provides a number of image processing apps to view and explore images.
Using the Image viewer app, you can view pixel information, pan and zoom, adjust contrast,
and measure distances etc. The Image Processing Toolbox supports a number of image
display techniques. For example, the function imshow displays any supported image type
with a single function call. Other functions handle more specialized display needs. This lab
further explores the basic display techniques for each image type supported by the toolbox,
as well as how to set the toolbox preferences for the imshow function. It also discusses special
display techniques, such as multiple image display.
Note: If you are new to MATLAB, you should first read Getting Started with MATLAB.

Objectives:

To

(a) understand various types of images such as intensity image, binary image and
storage class.
(b) reading and displaying various types of images.
(c) check the image memory and contents of images
(d) writing / storing the image data.
(e) converting data types of images.
(f) generate images
(g) understand imtool, an open image viewer

Pre-Lab work: All the students are instructed to go through the given reference text books
before proceeding to the examples and exercises.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

1.1 Reading an Image:


Clear the MATLAB workspace of any variables, close open figure windows and clear the
command window.
clear, close all; clc;
To read an image use the imread command. Let’s read in a TIFF image named
cameraman.tif (which is one of the sample images that is supplied with the Image Processing
Toolbox), and store it in an array named im.
im = imread(cameraman.tif);
1.2 Display an image: Now call imshow to display im.
imshow(im)
1.3 Check the Image in Memory
Enter the whos command to see how I is stored in memory.
whos
Name Size Bytes Class
im 291x240 69840 uint8 array
Grand total is 69840 elements using 69840 bytes

What is happening
Step 1: The imread function recognized cameraman.tif as a valid TIFF file and stored it in
the variable im. (For the list of graphics formats supported, see imread in the “Function
Reference” chapter.).
Step 2: The function imshow display graphics images in MATLAB. In general, it is
preferable to use imshow for displaying images because it handles the image-related
MATLAB properties for you. (The MATLAB function image is for low-level programming
tasks.)
Note that if cameraman.tif were an indexed image, the appropriate syntax for imread
would be,
[X, map] = imread(‘cameraman.tif');
(For more information on the supported image types, see “Image Types in the Toolbox”)

Step 3: You called the whos command to see how cameraman.tif had been stored into the
MATLAB workspace. As you saw, cameraman.tif is stored as a 256-by-256 array. Since
cameraman.tif was an 8-bit image, it gets stored in memory as an uint8 array. MATLAB can
store images in memory as uint8, uint16, or double arrays. (See “Reading a Graphics
Image” for an explanation of when the different storage classes are used.).

1.4 Writing Image Data: Imwrite, write image to graphics file


Syntax
imwrite(A, filename, fmt)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Example:
a=imread(‘cameraman.tif’);
imwrite(a, gray(256), 'b.bmp');
imshow('b.bmp')% imshow is used to display image
imwrite (im, 'cameraman.png');
What is happening
Step 4: MATLAB recognized the file extension of 'png' as valid and wrote the image to disk. It wrote
it as an 8-bit image by default because it was stored as a uint8 intensity image in memory. If I2 had
been an image array of type RGB and class uint8, it would have been written to disk as a 24-bit
image. If you want to set the bit depth of your output image, use the BitDepth parameter with imwrite.
This example writes a 4-bit PNG file.
imwrite(im, 'cameraman.png', 'BitDepth', '4');
Note that all output formats do not support the same set of output bit depths. For example, the toolbox
does not support writing 1-bit BMP images. See imwrite in the “Reference” chapter for the list of valid
bit depths for each format. See also “Writing a Graphics Image” for a tutorial discussion on writing
images using the Image Processing Toolbox.

1.5 Check the Contents of the Newly Written File


Now, use the imfinfo function to see what was written to disk. Be sure not to end the line with
a semicolon so that MATLAB displays the results. Also, be sure to use the same path (if any)
as you did for the call to imwrite, above.
imfinfo('pout2.png')
MATLAB responds with
ans =
Filename:'pout2.png'
FileModDate:'03-Jun-1999 15:50:25'
FileSize:36938
Format:'png'
FormatVersion:[]
Width:240
Height:291
BitDepth:8
ColorType:'grayscale'

Note The value in the FileModDate field for your file will be different from what is shown above.
It will show the date and time that you used imwrite to create your image. Note also that we
truncated the number of field names and values returned by this call.

What is happening
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Step 5: When you called imfinfo, MATLAB displayed all of the header fields for the PNG file
format that are supported by the toolbox. You can modify many of these fields by using
additional parameters in your call to imwrite. The additional parameters that are available
for each file format are listed in tables in the reference entry for imwrite. (See “Querying a
Graphics File” for more information about using imfinfo.).

1.6: How to get number of rows and columns of image


Function size gives the rows and columns dimension of image
[r,c]=size(a)
r =
291
c =
240
1.7 Accessing the Pixel data: There is a one-to-one correspondence between pixel
coordinates and the coordinates MATLAB® uses for matrix subscripting. This correspondence
makes the relationship between an image's data matrix and the way the image is displayed
easy to understand. For example, the data for the pixel in the fifth row, second column is stored
in the matrix element (5, 2). You use normal MATLAB matrix subscripting to access values of
individual pixels. For example, the MATLAB code A(2, 15) returns the value of the pixel at row
2, column 15 of the image A.

1.8 Imtool: Open Image Viewer app.

The Image Viewer presents an integrated environment for displaying images and performing
common image processing tasks. The Image Viewer provides all the image display capabilities
of imshow, which optimizes figure, axes, and image object property settings for image display.
The Image Viewer also provides access to several tools for navigating and exploring images,
such as the Pixel Region tool, Image Information tool, and the Adjust Contrast tool.
Example:
clear; close all; clc;
% imtool('board.tif');
im = imread('board.tif');
% im = imread('cameraman.tif'); % Display a grayscale image.
% h = imtool(I,[0 80]); %Display a grayscale image, adjusting the
display range.
% close(h)
imtool(im);
im_Max = max(max(im(:,:,1)))
im_Min = min(min(im(:,:,1)))
imtool(im, [im_Min im_Max]);
imtool(im, [0 120]);
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

1.9 Read and Write 1-Bit Binary Images

Example: This example shows how to read and write 1-bit binary images.
Check the bit depth of the graphics file containing a binary image, text.png. Note that the file
stores the binary image in 1-bit format.
info = imfinfo('text.png');
info.BitDepth
ans = 1

Read the binary image from the file into the workspace. When you read a binary image
stored in 1-bit format, imread represents the data in the workspace as a logical array.
BW = imread('text.png');
whos
Name Size Bytes Class Attributes

BW 256x256 65536 logical


ans 1x1 8 double
info 1x1 4518 struct
Write the binary image to a file in 1-bit format. If the file format supports it, imwrite exports a
binary image as a 1-bit image, by default. To verify this, use imfinfo to get information about
the newly created file and check the BitDepth field. When writing binary files, imwrite sets
the ColorType field to grayscale.
imwrite(BW,'test.tif');
info = imfinfo('test.tif');
info.BitDepth
ans = 1
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Lab1-Exercise Questions

Exercise1: (a) Read an image of cameraman.tif., and display in both unit8 and double.
Comment on the results.
(b) Repeat the above of any image of your choice.
(c) Use imtool and display with various range of gray values
Exercise2: Consider the following Matlab program:

clear, close all; clc;


im = imread(‘cameraman.tif’);
imshow(im)

(a) Identify whether the ‘im’ in the Matlab program is intensity or binary image.
(b) Mention the intensity range values of the above identified image for the following
classes
(i) uint8 (ii) double (iii) uint16
(c) What results are obtained for the following commands. Discuss in terms of intensity
ranges.
(i) imshow(I,[low high]) (ii) imshow(im, [ ])
Exercise3: Compare the function imagesc with the other display functions image and imshow
with an example. What should you do to obtain the same results with all the above three
functions?
Exercise4: Consider the following Matlab program:
clear; close all; clc;
im = im2double(imread('cameraman.tif'));
im1 = uint8(255*im);
im2 = im2uint8(im);

(a) Explain, what signifies the outputs im1 and im2


(b) Display the outputs im, im1 and im2 using display commands imshow, imagesc and
image.
(c) Store the images in png, jpg and .mat files
Exercise5: Discuss how can you read, display and store a binary image. Explain with an
example in Matlab.

Exercise6: Consider the following files attached. Read these files and display. Find their
memory size.
(i) img1.mat (ii) image2.mat
Further save these files in jpg and png formats.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

VIVA Questions

1)
2)
3)

References:

1. Digital Image Processing using Matlab by Gonzalez


2. Mathswork Image Processing Toolbox documentation
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


2. Arithmetical and Logical Operations on Images

Image arithmetic applies one of the standard arithmetic operations or a logical operator to
two or more images. The operators are applied in a pixel-by-pixel way, i.e. the value of a pixel
in the output image depends only on the values of the corresponding pixels in the input images.
Hence, the images must be of the same size. Although image arithmetic is the simplest form
of image processing, there is a wide range of applications. A main advantage of arithmetic
operators is that the process is very simple and therefore fast.

Logical operators are often used to combine two (mostly binary) images. In the case of
integer images, the logical operator is normally applied in a bitwise way.

In this lecture we will talk about arithmetic operations such as subtraction and averaging as
well as logic operations such as Not, AND, and OR. In this lecture we will see how we can
remove noise from an image by using image averaging.

Objectives:

To

(h) understand the arithmetic operations such as addition, subtraction multiplication,


division and averaging.
(i) explore the logic operations such as NOT, OR, AND, and XOR etc.

2.1 Image Arithmetic: An image is represented in a matrix format. To perform image


arithmetic the size of the two matrices should be same. The operation on two images results
in a new image.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

2.1.1 Image Addition: To add two images or a constant value, use ‘imadd’ function which
is built in function. Imadd method can be used to brighten an image by adding a constant value
to each pixel.

Example 2.1: Image addition by a constant value


Refer DIP_2_1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Example 2.2: Addition of two images
Refer DIP_2_2.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
2.1.2 Image Subtraction: ‘imsubtract’ is builtin Matlab function to subtract each pixel value in
one of the input images from another, or subtract a constant value from an image. Image
subtraction can be used for more complex image processing. Image subtraction is used to
detect images in a series of images of the same scene. For this operation the images must be
the same size and class.
(a) Image subtraction from a constant value.
Example 3:
Refer DIP_2_3.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
(b) Image subtraction from another image.
Example 4:
Refer DIP_2_4.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
2.1.3 Image Multiplication: ‘immultiply’ multiplies each pixel value in one of the input images
from the corresponding pixel in the other input image or multiply a constant value and returns
the result in the corresponding pixel in an output image. If elements of output image exceeding
the range of integer type are truncated, and fractional values are rounded. Image multiplication
can be used for more complex image processing. For this operation the images must be the
same size and class.
(a) Image multiplication with a constant value.
Example 5:
Refer DIP_2_5.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

(b) Image multiplication with another image.


Example 6:
Refer DIP_2_6.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

2.1.4: Image division:


(a) Divide an Image by a Constant Factor
Example 7:
Refer DIP_2_7.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
(b) Divide Image by another image
Example 8:
Refer DIP_2_8.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

2.2 Logical Operations: Logic operations provide a powerful complement to implementa-


tion of image processing algorithms based on morphology. The logic operations are applied
for binary images. These operations consist of 4 basic binary operations: AND, OR, and XOR
and a unary operator NOT. Secondary operators can be created by combining the three binary
operators with the unary operator, yielding: NAND, NOR, and XNOR. Logic operations are
performed on a pixel by pixel basis between corresponding pixels of two or more images
(except NOT, which operates on the pixels of a single image).
Example 9:
Refer DIP_2_9.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Lab2-Exercise Questions

Exercise1: Write a Matlab code for the following flipped images

Exercise2: Consider the following figure. Write a Matlab program to extract the appropriate
rectangular portion of the image (shown in a red color rectangular) and display in a separate
window. Identify the size of the resultant image and calculate the memory size.

Exercise3: Consider the following figure which is a rectangular in size. Write a matlab program
to display the image in a suitable square image (2n X2n).

imtool(J,'DisplayRange',[]);

Exercise4: Consider the following image of size 180X180. Develop Matlab code to display
the image using arithmetic and logic operations.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Exercise5: Write a Matlab code to read and display an image 'board.tif'. Now
display a portion of the image that has the dimensions of 256X256.
Exercise6: Enter the following Matlab code and observe the results
clear; close all; clc;
im = imread('cameraman.tif');

im1=imdivide(im,64);
im2=immultiply(im1,64);
figure();
subplot(1,3,1); imshow(im,[]); title('Original Image');
subplot(1,3,2); imshow(im1,[]); title('Divided by 4');
subplot(1,3,3); imshow(im2,[]); title('Multiply by 4');

Comment on the result. Why is the result not equivalent to the original image?

VIVA Questions

1)

2)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


3. Fourier Analysis of Images
Frequency domain analysis is a very important part in image processing, especially in image
enhancement, noise reduction and image filtering. The processing in frequency domain
simplifies the design of filters and reduces the computational complexity. Frequency domain
representation gives you control over the whole images, where you can enhance (eg edges)
and suppress (eg smooth shadow) different characteristics of the image very easily.

Objectives:
To
(a) find the magnitude and phase spectrum of various images.
(b) understand the importance of phase information.
(c) recognise the importance of zero padding
(d) discover the properties of 2D FFT such as rotation and shifting.

Basic Theory:
The two-dimensional discrete Fourier transform (DFT) of an image f(x,y) of size M x N is
represented by:

The corresponding inverse of the above discrete Fourier transform is given by the following
equation:

The magnitude and phase spectrum of an image f (x, y) is represented by


Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

where R(u, v) and I(u, v) are the real and imaginary components of the spectrum F(u, v).
Similarly the power spectrum is represented by

Example1: Generate an image of size 30x30 with zero magnitudes. Then create a
rectangular of size 5x20 with unity magnitude. Find the magnitude spectrum and display.
Use fftshift to display the spectrum in the center. Use zero padding for fine resolution. For
more visibility use log of magnitude spectrum.
Refer DIP_Ex_3_1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Example2: Find and display of magnitude and phase spectrum of a synthetic image
(parameters are given in the Matlab code). Rotate the image by 45O. Now reconstruct the
image:
(a) Using both magnitude and phase spectrums.
(b) Using only magnitude spectrum.
(c) Using only phase spectrum.
(d) Comment on the results
Refer DIP_Ex_3_2.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Example2: Repeat the above for various images of choice.


Refer DIP_Ex_3_3.m
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

< Type the Matlab codes here >


< Plot the figures and type the results here >

Lab3-Exercise Questions

Exercise1: (a) Write a Matlab code to generate the following images. Assume that the width
of the white pixel for Fig(a) and height of the white pixel Fig(b) are unity.

(b) Find and display the magnitude and phase spectrums.


(c) Suppose the vertical line in Fig(a) and horizontal line in Fig(b) are rotated by
(i) ±30O, (ii) ±45O and (iii) ±90O. Find and display the magnitude and phase
spectrums. Comment on the results.
Exercise2: (a) Write a Matlab code to generate the following images. Assume that the radius
of circle is 32 for Fig(a).
(b) Find and display the magnitude and phase spectrums.

Exercise3: Read an image of your choice.


(a) Find and display the magnitude and phase spectrum of image.
(b) Now reconstruct the image with
(i) Only magnitude spectrum
(ii) Only phase spectrum
(iii) Combining the magnitude and phase spectrum.
(iv) With the above results, discuss the importance of phase information of
image.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Exercise4: Read two images of your choice.


(a) Find and display the magnitude and phase spectrums of two images.
(b) Now swap the phase response of two images, while keeping the magnitude
responses are same and reconstruct the two images. Based on the results
illustrate the importance of the phase response.
Exercise5: (a) Write a Matlab code to generate the following images.

(b) Find and display the magnitude and phase spectrums.


(c) Suppose the white rectangular images are rotated by
(i) ±45O and (ii) ±120O. Find and display the magnitude and phase
spectrums. Comment on the results.

< Type the Matlab codes here >


< Plot the figures and type the results here >

VIVA Questions

1)

2)

3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


4. Image Enhancement by Simple Intensity Transformations

The principal objective of enhancement is to process an image so that the result is more
suitable than the original image for a specific application. Image enhancement is one of the
most interesting and visually appealing areas of image processing. The most basic type of
image-processing operation is a point transform which maps the values at individual points
(i.e. pixels) in the input image without any knowledge of its surrounds to corresponding points
(pixels) in an output image.

4.1 Image Negative (or Complement): The negative of a digital image is obtained by using
the transformation function s = T(r) shown in Fig4.1, where L is the
number of gray levels. The idea is to reverse the order from black
to white, so that the intensity of the output image decreases as the
intensity of the input increases. Negatives of digital images are
useful in numerous applications such as displaying medial images
and photographing a screen with monochrome positive.

Example1:

Refer DIP_Ex_4_1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
4.2 Power-Law Transformation: In power-law transform in which each input pixel value is
raised to a fixed power: 𝐼𝑜𝑢𝑡 (𝑖, 𝑗) = 𝑐 ∗ (𝐼𝑖𝑛 (𝑖, 𝑗))𝛾
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

In general, a value of γ > 1 enhances the contrast of high-value portions of the image at
the expense of low-value regions, whilst we see the reverse for γ > 1. Here c is a constant
value that changes the intensity.

Gamma Correction using imadjust: The following example below illustrates gamma
correction. Notice that in the call to imadjust, the data ranges of the input and output images
are specified as empty matrices. When you specify an empty matrix, imadjust uses the default
range of [0,1]. In the example, both ranges are left empty; this means that gamma correction is
applied without any other adjustment of the data.
Example2:
Refer DIP_Ex_4_2.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Example3:
Refer DIP_Ex_4_3.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

3.3 Contrast stretching: Contrast stretching is a simple image enhancement technique that
improves the contrast in an image by expanding the dynamic range of intensity values
it contains. It can only apply a linear scaling function to the image pixel values.
Mathematical Modelling: It is necessary to specify the upper and lower pixel value limits
over which the image is to be normalized. Often these limits will just be the minimum and
maximum pixel values that the image type concerned allows. For
example for 8-bit gray level images the lower & upper limits might
be 0 and 255. Call the lower and the upper
limits a and b respectively. The simplest of stretching scans
the image to find the lowest & highest pixel values in the image.
Call these c and d. Then each pixel P is scaled using the following
function:
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Values below 0 are set to 0 and values about 255 are set to 255.
MATLAB implementation of the above concept of Contrast Stretching on an image is as
below:
Example4:
Refer DIP_Ex_4_4.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Function imadjust: The function imadjust is the basic IPT tool for intensity transformations
of grayscale images. It has the syntax

g = imadjust(f, [low_in high_in], [low_out high_out], gamma)

Example5:
Refer DIP_Ex_4_5.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

3.4 Bit-plane slicing: Instead of highlight in gray-level ranges, highlighting the contribution
made to total image appearance by specific bits might be desired.

Example6:
Refer DIP_Ex_4_6.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Lab4-Exercise Questions
Exercise1: Consider the following images depicts about the contrast enhancement.
Develop Matlab codes for contrast enhancement based on these functions on various images.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

VIVA Questions
1)
2)
3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab 5-Histogram Processing

Histograms are the basis for numerous spatial domain processing techniques. Histogram
manipulation can be used effectively for image enhancement. In addition to providing useful
image statistics, we shall see in subsequent chapters that the information inherent in
histograms also is quite useful in other image processing applications, such as image
compression and segmentation. Histograms are simple to calculate in software and also lend
themselves to economic hardware implementations, thus making them a popular tool for real-
time image processing.

The focus of this experiment is on obtaining, plotting, and using histograms for image
enhancement.

Objectives:

(a) Generating and Plotting Image Histograms


(b) Histogram Equalization
(c) Histogram Modification
(d) Histogram Specification

5.1 Generating and Plotting Image Histograms: The histogram of a digital image with L total
possible intensity levels in the range [0, G] is defined as the discrete function
ℎ(𝑟𝑘 ) = 𝑛𝑘
where 𝑟𝑘 is the kth intensity level in the interval [0, G] and 𝑛𝑘 is the number of pixels in the
image whose intensity level is 𝑟𝑘 . The syntax for histogram in Matlab is
h = imhist(f, b);
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

where f is the input image, h is its histogram, and b is the number of bins used in forming
the histogram
Often, it is useful to work with normalized histograms, obtained simply by dividing all elements
of ℎ(𝑟𝑘 ) by the total number of pixels in the image, which we denote by n:
ℎ(𝑟𝑘 )
𝑝(𝑟𝑘 ) =
𝑛
The syntax for normalized histogram in Matlab is given by
p = imhist(f, b)/numel(f)

Example 5.1: Representation of histograms in various formats


Refer DIP_Ex_5_1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Refer chapter 3.3 of Digital Image Processing using Matlab by Gonzalez

5.2 Histogram Equalization: The Histogram Equalization algorithm enhances the contrast of
images by transforming the values in an intensity image so that the histogram of the output
image is approximately uniform. The method is useful in images with backgrounds and
foregrounds that are both bright or both dark. A key advantage of the method is that it is a
fairly straightforward technique and an invertible operator.
Histogram equalization is implemented in the toolbox by function histeq, which has the
syntax
g = histeq(f, nlev)
where f is the input image and nlev is the number of intensity levels specified for the output
image.
Example 2:
Refer DIP_Ex_5_2.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Ref: https://in.mathworks.com/help/images/histogram-equalization.html

4.3 Histogram Modification: The method is used to enhance the low contrast image by
making its histogram modified so that it matches the histogram of high contrast image.
Refer DIP_Ex_5_3.m
< Type the Matlab codes here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

< Plot the figures and type the results here >

%% Histogram Modification ISP Lab 10


% AliArshad Kothawala
% 13/4/2015

%===================================================================
================================
% Read the images
%===================================================================
=================================
im1=imread('inp_image.pgm'); % Given Image
im2=imread('ref_image.pgm'); % Reference Image
M = zeros(256,1,'uint8'); %Store mapping - Cast to uint8 to respect
data type
figure;subplot(121);imshow(im1);title('Original
Image');subplot(122);imshow(im2);title('Reference Image');
%===================================================================
==================================
% Compute the Histograms
%===================================================================
==================================
hist1 = Histo(im1); %Compute histograms
hist2 = Histo(im2);
%===================================================================
==================================
% Cumulative distribution Function
%===================================================================
==================================
cdf1 = cumsum(hist1) / numel(im1); %Compute CDFs
cdf2 = cumsum(hist2) / numel(im2);
%===================================================================
==================================
% Compute the mapping
%===================================================================
===================================
for idx = 1 : 256
[mmm,ind] = min(abs(cdf1(idx) - cdf2));
M(idx) = ind-1;
end

% Apply the mapping to first image to make the image look like the
distribution of the second image
out = M(double(im1)+1);
figure;imshow(out);

Histogram modelling: If the function F denotes a cumulative function distribution (CDF) and

F −1 denotes its inverse, and if U denotes a set of number with a uniform distribution on an
interval [0,1] (in this case it means that the image’s pixel values are uniformly distributed
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

between 0 and 1), then a set of numbers F −1 (U) has a pixel value distribution equal to
F. This fact can be used for histogram modeling:

Example 2:

[img,map]=imread(’salona.png’); % Read the image


img=ind2gray(img,map); % Convert it to grayscale
imgEQ=histeq(img); % Equalize the histogram to obtain approx. uniform
% distribution
imgMEQ=imscale(img,[0 1]); % Rescale the values to [0 1]
imgMEQ=norminv(imgMEQ,0,10); % Model the histogram to a normal distribution with a
% mean value 0 and a deviation 10
Exercise 3:

1. Choose an arbitrary image. Model its histogram to obtain a desired distribution function.

2. Read the image auto.tif. Model its histogram until the number on the car’s registration plate
becomes visible. (Hint: Check the interval of pixel values in the register plate area, and
determine the mapping of this interval to a larger one.)

4.4 Histogram Matching / Specification: The method used to generate a processed image
that has a specified histogram is called histogram matching or histogram specification. The
histogram specification is more appropriate and can be employed both as a means for
improving visual contrast and for regularizing an image prior to subsequent processing or
analysis.

Example: In this example, we specify a linearly ramped PDF as the target distribution t and
we can see the resulting output together with the modified image histograms.

I=imread(‘pout.tif’);
pz = 0:255; %Define ramp like pdf as desired output histogram
Im = histeq(I, pz); %Supply desired histogram to perform matching
subplot(2,3,1), imshow(I); %Display image
subplot(2,3,2), imshow(Im); %Display result
subplot(2,3,3), plot(pz); %Display distribution t
subplot(2,3,4), imhist(I); %Display histogram of image
subplot(2,3,5), imhist(Im); %Display histogram of result
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

VIVA Questions
1)
2)
3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab 6-Noise Filtering in Spatial Domain

Spatial filtering is an image processing technique for changing the intensities of a pixel
according to the intensities of the neighboring pixels. The spatial filtering can be character-
rized as a “fold, shift multiply and add” operation: the kernel folds and shifts over the initial
image producing a mask and multiplies its value with the corresponding pixel values of the
image. The resultant average is a new value that replaces the central value of the mask in the
new image. For example, filtering an image results in emphasize certain features or remove
other features. Image processing operations implemented with filtering include smoothing,
sharpening, and edge enhancement.

Noise Removal: Digital images are prone to various types of noise. Noise is the result of
errors in the image acquisition process that result in pixel values that do not reflect the true
intensities of the real scene. There are several ways that noise can be introduced into an
image, depending on how the image is created. For example:

a) If the image is scanned from a photograph made on film, the film grain is a source of
noise. Noise can also be the result of damage to the film, or be introduced by the
scanner itself.
b) If the image is acquired directly in a digital format, the mechanism for gathering the
data (such as a CCD detector) can introduce noise.
c) Electronic transmission of image data can introduce noise.

To simulate the effects of some of the problems listed above, the toolbox provides
the imnoise function, which you can use to add various types of noise to an image. The
examples in this section use this function.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Remove Noise by Linear Filtering: Linear filtering is used to remove certain types of
noise. Certain filters, such as averaging or Gaussian filters, are appropriate for this purpose.
For example, an averaging filter is useful for removing grain noise from a photograph. Because
each pixel gets set to the average of the pixels in its neighborhood, local variations caused by
grain are reduced.

The Mathlab Image Processing Toolbox supports a number of predefined 2-D linear spatial
filters, obtained by using function fspecial, which generates a filter mask, w, using the
syntax

w = fspecial('type', parameters)

where 'type' specifies the filter type, and parameters further define the specified filter.

Refer for the spatial filters supported by fspecial are summarized in Table 3.4, section 3.5
of text book Digital Image Processing using Matlab by Gonzalez.

The students are advised to study about the various types of noise corrupted the images in
various applications.

Mean Fltering: The mean filter is perhaps the simplest linear filter and operates by giving
1
equal weight 𝑊𝑘 to all pixels in the neighbourhood. A weight of 𝑊𝑘 = is used for an N x
𝑀𝑁

M neighbourhood and has the effect of smoothing the image, replacing every pixel in the
output image with the mean value from its NM neighbourhood. This weighting scheme
guarantees that the weights in the kernel sum to one over any given neighbourhood size.
Mean filters can be used as a method to suppress noise in an image. Another common use is
as a preliminary processing step to smooth the image in order that some subsequent
processing operation will be more effective.

Example1: Removing the Gaussian noise using Average filtering


Refer DIP_Ex_6_1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Example2: Removing the Salt and Pepper noise using Average filtering
Refer DIP_Ex_6_2.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Exercise 6.1: (a) Comment on the results of the above two examples.
(b) Now apply 5X5 and 7X7 average filter kernels for suppressing the Gaussian
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

noise. Now display the resultant denoised images. What affects you
are
observed on the resulting images? Comment on the results.
(c) Now change the noise variance as (i) 0.1 and (ii) 0.5 for both Gaussian
and Salt and Pepper and apply to the above image. Display the resultant
noisy images. What do you observed in these noisy images?
(d) Apply the average filters with kernels, 3X3, 5X5, and 7X7 for the images
generated in (c) and display the resultant denoised images. What affects
you are observed on the resulting images? Comment on the results.
(e) Repeat the above steps for any image of your choice.

Median filtering: Another commonly used filter is the median filter that overcomes the main
limitations of the mean filter, albeit at the expense of greater computational cost. As each pixel
is addressed, it is replaced by the statistical median of its N X M neighbourhood rather than
the mean. The median filter is superior to the mean filter in that it is better at preserving
sharp high-frequency detail (i.e. edges) whilst also eliminating noise, especially isolated noise
spikes (such as ‘salt and pepper’ noise). By definition, the median operator requires an
ordering of the values in the pixel neighbourhood at every pixel location. This increases the
computational requirement of the median operator.
Example3:
Refer DIP_Ex_6_3.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Exercise2:
(a) Comment on the results.
(b) Now apply 5X5 and 7X7 filter kernels and display the resultant denoised
images. What affects you are observed on the resulting images? Comment
on the results.
(c) Now change the noise variance as (i) 0.1 and (ii) 0.5 for both Gaussian
and Salt and Pepper and apply to the original image. Display the resultant
noisy images. What do you observed in these noisy images?
(d) Apply the average filters 3X3, 5X5, and 7X7 to the noisy images generated
in (c) i.e., and display the resultant denoised images. What affects you are
observed on the resulting images? Comment on the results.
(e) Repeat the above steps for any image of your choice.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Rank filtering: The median filter is really just a special case of a generalized order (or rank)
filter. Order filters which select the maximum and minimum values in the defined
neighbourhood are (unsurprisingly) called maximum and minimum filters.
clear; close all; clc;
I = imread(‘eight.tif’); %Read in image
% Add Gaussian noise (with 0.02 variance)
Ig = imnoise(I,‘gaussian’,0.02);
% Add Salt and Pepper noise (with 0.03 variance)
Isp = imnoise(I,‘salt & pepper’,0.03);

% Apply order statistical filter with kernel size 3X3, order=25 to


% the original image
Im = ordfilt2(I,25,ones(5,5));

%Apply order statistical filter with size 3X3, order=25 to the


Gaussian noisy %image
Igm = ordfilt2(Ig,25,ones(5,5)));

% Apply order statistical filter with size 3X3, order = 25 to the


% salt & pepper noisy image
Ispm = ordfilt2(Isp,25,ones(5,5)));

Figure();
%Display the order statistical filtered original image
subplot(1,3,1);imshow(Im);
title(‘order statistical filtered original image’);
subplot(1,3,2);imshow(Igm);
title(‘order statistical filtered Gaussian noisy image’);
subplot(1,3,3);imshow(Ispm);
title(‘order statistical filtered salt & pepper noisy image’);
Exercise3:
(a) Comment on the results.
(b) Now apply 5X5 and 7X7 filter kernels and display the resultant denoised
images. What affects you are observed on the resulting images? Comment
on the results.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

(c) Now change the noise variance as (i) 0.1 and (ii) 0.5 for both
Gaussian
and Salt and Pepper and apply to the original image. Display the resultant
noisy images. What do you observed in these noisy images?
(d) Apply the average filters 3X3, 5X5, and 7X7 to the noisy images generated
in (c) i.e., and display the resultant denoised images. What affects you are
observed on the resulting images? Comment on the results.
(e) Change the order from 9, 16 and 36 to the above in (d) display the results.
(f) Repeat the above steps for any image of your choice.

Gaussian filtering: The Gaussian filter has the effect of smoothing the image, but it is used
in a way that is somewhat different to the mean filter. First, the degree of smoothing is
controlled by the choice of the standard deviation parameters, not by the absolute value of the
kernel size (which is the case with the mean filter). Second, the Gaussian function has a rather
special property, namely that its Fourier transform is also a Gaussian function, which makes
it very convenient for the frequency-domain analysis of filters.

clear; close all; clc;


I = imread(‘eight.tif’); %Read in image
% Add Gaussian noise (with 0.02 variance)
Ig = imnoise(I,‘gaussian’,0.02);
% Add Salt and Pepper noise (with 0.03 variance)
Isp = imnoise(I,‘salt & pepper’,0.03);

K = fspecial(‘gaussian’, [5 5], 2); %Define Gaussian filter with σ = 2


Ig = imfilter(I,k); %Apply to original image
Ispg = imfilter(Isp,k); %Apply to salt and pepper image
Igg = imfilter(Ig,k); %Apply to Gaussian image
subplot(1,3,1); imshow(Ig); %Display result image
subplot(1,3,2); imshow(Ispg); %Display result image
subplot(1,3,3); imshow(Igg); %Display result image
Exercise4:
(a) Comment on the results.
(b) Now apply 5X5 and 7X7 filter kernels and display the resultant denoised
images. What affects you are observed on the resulting images? Comment
on the results.
(c) Now change the noise variance as (i) 0.1 and (ii) 0.5 for both Gaussian
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

and Salt and Pepper and apply to the original image. Display the
resultant
noisy images. What do you observed from these noisy images?
(d) Apply the average filters 3X3, 5X5, and 7X7 to the noisy images generated
in (c) i.e., and display the resultant denoised images. What affects you are
observed on the resulting images? Comment on the results.
(e) Change the sigma for various values (i) σ = 3 (ii) σ = 5, and (iii) σ = 7.
(f) Repeat the above steps for any image of your choice.

Periodic Noise suppression:

a)

SALT & PEPPER NOISE


I = imread('cameraman.tif');
subplot(2,2,1);imshow(I)title('Original Image')
J = imnoise(I,'salt & pepper',0.05);
subplot(2,2,2);imshow(J);title('Image with Salt & Pepper Noise')
K = filter2(fspecial('average',3),J)/255;
subplot(2,2,3);imshow(K);title('Filtered Image by Mean filter')
M = medfilt2(J);
subplot(2,2,4); imshow(M)title('Filtered Image by Median filter')

b)

GAUSSIAN NOISE
I=imread('cameraman.tif');

subplot(221);imshow(I)title('Original Image')

J=imnoise(I,'gaussian',0.02);

subplot(222);imshow(J)title('Image with Gaussian Noise')

K=wiener2(J,[55]);

subplot(223);imshow(K);title('Filtered Image by Wiener Filter')

c)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

SPECKLE NOISE
I=imread('cameraman.tif');
subplot(221);imshow(I);title('Original Image')
J=imnoise(I,'speckle',0.02);
subplot(222);imshow(J);title('Image with Speckle Noise');
K=wiener2(J,[55]);
subplot(223);imshow(K);title('Filtered Image by Wiener Filter')
M = medfilt2(J);
subplot(2,2,4);imshow(M)title('Filtered Image by Median filter')

POISSON NOISE
I=imread('cameraman.tif');

subplot(221);imshow(I)title('Original Image')

J=imnoise(I,'poisson’);

subplot(222);imshow(J);title('Image with Poisson Noise');

K=wiener2(J,[55]);

subplot(223);imshow(K);title('Filtered Image by Wiener Filter')

M = filter2(fspecial('average',3),J)/255;

subplot(2,2,3);imshow(M)title('Filtered Image by Mean filter')

VIVA Questions
1)
2)
3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab7-Image Filtering: Frequency Domain Analysis

Filtering of an image corresponds to applying an LSI system on that image. These


operations can be calculated by means of the 2D convolution in the spatial domain or in the
transform (frequency) domain. Filtering in the transform domain is performed by multiplication
the Fourier transform coefficients of the image with the Fourier transform coefficients of the
impulse response of the desired filter.

Objectives:
To
➢ Understand the low pass filtering of images using ideal, Gaussian and Butterwoth
filtering kernels.
➢ Explore image sharpening using high pass filtering kernels such as ideal, Gaussian
and Butterwoth filtering kernels.
➢ Plot (i) 2D image, (ii) 3D mesh and (iii) horizontal line intensity profiles for both the
impulse response and transfer functions.
7.1 Basic Theory: As we know that, based on the property that multiplying the FFT of two
functions from the spatial domain produces the convolution of those functions, we can use
Fourier transforms as a fast convolution on large images. The processing in frequency domain
simplifies the design of filters and reduces the computational complexity. The basic scheme of
the frequency domain filtering is illustrated in the following block diagram
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Fig 7.1: Frequency domain filtering process


The transfer function of an LSI system equals to the transform of the impulse response of the
system.

The basic steps in filtering operations in the frequency domain are summerized as below:
Step1: Read the given image
im = imread(‘xxxxxxxx.yyy’);
Step2: Obtain the padding parameters using function paddedsize:
PQ = paddedsize(size(im));

Importance of zero padding: When applying Fourier transforms, zero padding is very
important. Note that, because images are infinitely tiled in the frequency domain, filtering
produces wrap-around artefacts, if you don't zero pad the image to a larger size. The
paddedsize function below calculates a correct padding size to avoid this problem. The
paddedsize function can also help optimize the performance of the DFT by providing power
of 2 padding sizes. See paddedsize 's help header for details on how to do this.

Step3: Find the Fourier transform with padding and cantering the image:
imF = fftshift(fft2(im, PQ(1), PQ(2)));
Step4: Generate a desired filter function, H, the same size as the image
Step5: Multiply the transformed image by the filter:
imG = H.*imF;
Step6: Obtain the real part of the inverse FFT of G:
img = real(ifft2(imG));
Step7: Crop the top, left rectangle to the original size:
img = img(1:size(im, 1), 1:size(im, 2));
(Refer from page 121 of Digital Image Processing Using MATLAB, by Gonzalez):

Frequency Domain Specific Filters: However, we can also create filters directly in the
frequency domain. The following two filters in the frequency domain are discussed here for
experimentation.
(a) Lowpass filters (smoothing filters).
(b) Highpass filters (sharpening filters).

7.2 Low Pass Filters (smoothing):: A low-pass filter is a filter that passes low-frequency
signals and attenuates signals with frequencies higher than the cut-off frequency. The actual
amount of attenuation for each frequency varies depending on specific filter design.
Smoothing is fundamentally a lowpass operation in the frequency domain. There are
several standard forms of lowpass filters are Ideal, Butterworth and Gaussian lowpass filter.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

In this lab experiment, we use lpfilter.m that is attached. The details of the
function lpfilter.m are described as below:
H = lpfilter(type, M, N, D0, n), where the input arguments are:
Type = ’gaussian’, ’ideal’ or ’btw’ (for Butterworth filters)
M,N = dimensionality of filter frequency response
D0 = filter cutoff frequency (normalized to range [0, M] or [0, N]).
n = filter order for Butterworth filters

7.2.1 Ideal Low Pass Filter: The simplest low pass filter is a filter that “cuts off” all high-
frequency components of the Fourier Transform that are at a distance greater than a
specified distance D0 from the origin of the Transform.

The transfer function of an ideal low pass filter

1, if D(u, v)  D0
H (u, v) = 
0, if D(u, v)  D0
where D (u , v ) is the distance from point (u , v) to the center of their frequency.

(u − M2 ) + ( v − N2 )
2 2
D(u, v) =

The structure of an ideal low pass filter is illustrated in the following figure.

Fig 7.2: Ideal LPF structure in (a) 2D image and (b) 3D mesh

Example 7.1: Design an ideal low pass filter with a cut-off frequency of 10% of width and apply
to an image of your choice. Write a Matlab code for the same and display the results.

Solution: Refer DIP_7_1.m.

Exercise7.1: (a) Consider the above example. Find the impulse response of the system and
display the following: (i) 2D image, (ii) 3D mesh, and (iii) Horizontal line intensity profile.
(b) Repeat the ideal filtering of the above example for various cut-off frequencies:
(i) 5%, (ii) 20%, (iii) 50% ,and 80%.
(c) Repeat the above steps for various images (at least two images) of your choice.
(d) Write a Matlab function (code) for zero padding of (i) 3 (ii) 4 times the size of the original
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

image based on the paddedsize.m. Then do the ideal filtering and display the results.

7.2.2 Gaussian Lowpass Filters: The transfer function of a Gaussian low pass filter is
defined as:
− D2 (u ,v )/2 D02
H (u, v) = e

Fig 7.3: Gaussian LPF structure in (a) 2D image and (b) 3D mesh

Exercise7.2: (a) Based on example7.1, develop Matlab code for Gaussian low pass filtering
of cameraman image using the following functions provided: dftuv.m paddedsize.m
and lpfilter.m.
(b) Display the following in respect to the Gaussian low Pass filtering kernel:
(i) 2D image (frequency domain) (ii) 3D mesh image (frequency domain), and (iii) Horizontal
spectral line intensity profile of transfer function.
(c) Repeat the tasks given in Exercise7.1.

7.2.3 Butterworth Lowpass Filters: Design frequency-domain filter to remove high-


frequency noise with minimal loss of signal components in the specified pass-band with order
n
1
H (u, v) = 2n
1 +  D (Du ,v ) 
 0 

Fig 7.3: Butterworth LPF structure in (a) 2D image and (b) 3D mesh

Exercise7.3: Repeat the exercise7.2 in respect to the Butterworth Low pass Filters
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

7.3 High Pass Filters (sharpening): A high-pass filter is a filter that passes high frequencies
well, but attenuates frequencies lower than the cut-off frequency. Sharpening is fundamentally
a high pass operation in the frequency domain. There are several standard forms of high pass
filters such as Ideal, Butterworth and Gaussian high pass filter. All high pass filter ( H hp ) is

often represented by its relationship to the low pass filter ( H lp ).

H hp = 1 − H lp

Exercise7.4: Based on the above equation for high pass filter transfer function H hp = 1 − H lp
or using a function hpfilter.m, repeat the exercises 7.1 to 7.3 for high pass filtering.

VIVA Questions

1)

2)

3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


8. Image Segmentation-Edge Detection
Image segmentation is a commonly used technique in digital image processing and analysis
to partition an image into multiple parts or regions, often based on the characteristics of the
pixels in the image. Image segmentation could involve separating foreground from back-
ground, or clustering regions of pixels based on similarities in color or shape. Edge detection
is basically a method of segmenting an image into regions based on discontinuity, i.e. it allows
the user to observe those features of an image where there is a more or less abrupt change
in grey level or texture, indicating the end of one region in the image and the beginning of
another. Enhancing (or amplifying) the presence of these discontinuities in the image allows
us to improve the perceived image quality under certain conditions. However, like other
methods of image analysis, edge detection is sensitive to noise.
Objectives
To
(a) Understand the basic point detection.
(b) Explore various line detection techniques.
(c) Explore the edge detection using various processes.
(d) Understand the intensity thresholding based segmentation.

Pre lab work:

(a) Study and understand the basic theory required for this lab.
(b) Run the Matlab scripts given for examples and study the results.
(c) Prepare the Matlab codes for the given laboratory exercises well before the
commencement of lab scheduled time. Discuss with your lab instructors for further
clarifications.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

1. Point detection: The point detection of isolated points embedded in areas of constants
or nearly constant intensity in image.
Example1: Refer seg1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >

Exercise1: (a) Find the threshold value in seg1.m.


(b) Change the threshold value as (i) halve value (ii) one third value of the
maximum value of the parameter img in seg1.m. Comment on the
results.
(c) Repeat the above for (a) and (b) various images of your choice.
(d) Repeat the above (a), (b) and (c) by considering the following matrix.

 −1 −2 −1
 −2 12 −2 
 
 −1 −2 −1

< Type the Matlab codes here >


< Plot the figures and type the results here >
2. Line Detection: The following examples illustrate the detection of both horizontal and
vertical lines in an image. The function edge.m is used for this purpose.
Example2: Detection of vertical and horizontal lines in an image using sobel
operators.
Refer seg2.m
Exercise2:
(a) Repeat the example2 for prewitt operator.
(b) Choose an image of your choice and find the horizontal and vertical edges using
both (i) sobel (ii) prewitt operators.

3. Edge Detection: Edge detection makes use of differential operators to detect changes in
the gradients of the grey or colour levels in the image.
3.1 First-order edge detection: A number of filter kernels have been proposed which
approximate the first derivative of the image gradient. Three of the most common are
Roberts, Prewitt and Sobel edge-detector filter kernels. All three are implemented as a
combination of two kernels: one for the x-derivative and one for the y-derivative.
Example3: Edge detection using Roberts operator. Refer seg3.m

Exercise3: Repeat the above example for various images of your choice.
< Type the Matlab codes here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

< Plot the figures and type the results here >
Example4: Edge detection using Prewitt operator. Refer seg4.m

Exercise4: Repeat the above example for various images of your choice.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Example5: Edge detection using Sobel operator. Refer seg5.m

Exercise5: Repeat the above example for various images of your choice.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Example6: Edge detection using three operators: Roberts, Prewitt and Sobel operators.
Refer seg6.m
Exercise6: Repeat the above example for various images of your choice.
< Type the Matlab codes here >
< Plot the figures and type the results here >

2.2 Second-order edge detection: The Laplacian operator. The second-order derivative
property that allows the Laplacian to produce a fine edge response corresponding to a change
in gradient, rather than the less isolated response of the first-order edge filters, makes it
suitable as the first stage of digital edge enhancement. However, as the Laplacian kernels
approximate a second derivative over the image they are in fact very sensitive to noise.

Example7: Refer seg7.m

Exercise7a: Repeat the example for various images of your choice.


Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Exercise7b: Write a Matlab code to display the following figure.

< Type the Matlab codes here >


< Plot the figures and type the results here >
2.3 Laplacian of Gaussian: To counter the high noise sensitivity of the Laplacian filter, the
standard Laplacian kernel is commonly combined with the Gaussian kernel referred as the
Laplacian of Gaussian (LoG) filter to produce a robust filtering method.

Example8: Refer seg8.m

Exercise7: Repeat the example for various images of your choice.


< Type the Matlab codes here >
< Plot the figures and type the results here >

2.4 Zero-crossing detector: The zero-crossing detector is used to locate pixels at which the
value of the Laplacian passes through zero (i.e. points where the Laplacian changes sign).
This occurs at ‘edges’ in the image where the intensity of the image changes rapidly (or in
areas of intensity change due to noise).

Example9: Refer seg9.m

Exercise9: Repeat the example for various images of your choice.


Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

< Type the Matlab codes here >


< Plot the figures and type the results here >

3. Intensity thresholding: The basic idea of using intensity thresholding in segmentation is


very simple. We choose some threshold value such that pixels possessing values greater than
the threshold are assigned to one region whilst those that fall below the threshold are assigned
to another (adjoint) region. Thresholding creates binary image g ( x, y ) from an intensity image

f ( x, y ) according to the simple criterion

1, if f ( x, y)  Th
g ( x, y ) = 
0, otherwise

Example10: Refer seg10.m

Exercise10: Repeat the example for various images of your choice.


< Type the Matlab codes here >
< Plot the figures and type the results here >

In lab Session:
(a) Execute the Matlab codes prepared for the exercises and observe the results.
(b) Compute all the tasks given in the exercises. Show the results to your instructor and
get it signed with assigned marks.
(c) Note the results and store the necessary figures and data for the lab report.

Post Lab Session:


(a) Complete the lab work in all aspects in the given specified lab time.
(b) Answer for the given questions.
(c) Submit the lab report to the lab in-structure and get the signature in time.
(d) Type the complete description of commands used in the lab

VIVA Questions
1)

2)

3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab9- Image Restoration

Image Restoration is an operation that takes a corrupt / noisy image and estimates
the clean, original image. Degradation may come in many forms such as motion
blur, noise and camera mis-focus etc. Image restoration is performed by reversing the
process that blurred the image and such is performed by imaging a point source and use
the point source image, which is called the Point Spread Function (PSF) to restore the
image information lost to the blurring process.

Objectives:
To
(a) Understand the various degradation process
(b) Understand the corruption by noise
(c) Explore the various restoration techniques

9.1 Basic Theory: The basic theory of degradation and restoration process is illustrated in
the following figure.

Fig.9.1 Image degradation and restoration process


Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Mathematical analysis: In the spatial domain the degradation out may be represented
by g ( x, y ) = f ( x, y ) h( x, y) +  ( x, y)
where f ( x, y ) is the original image

h( x, y ) is the degradation (convolution) function, also known as impulse


response of the system or point spread function (PSF)
 ( x, y ) noise content
g ( x, y ) blurred and noisy (degraded) image

hr ( x, y ) , is restoration or deconvolution filter, and


)
f ( x, y ) is the estimated image.
In the frequency domain, we represent the degradation process as
G (u , v) = H (u , v) F (u , v) + N (u , v)
where F (u , v ) , N (u , v ) and G (u , v ) are the 2D, FFT of f ( x, y ) ,  ( x, y ) and g ( x, y )
respectively.
H (u , v ) is referred to as Optical Transfer Function (OTF)
H r (u , v ) is the reconstruction (deconvolution) filter transfer function.
)
F (u , v) is the estimated signal.

Example9.1: Select a 256 x 256 image of your choice. Degrade the image using a Gaussian
blurring kernel and additive white Gaussian noise with say variance 20. Develop Matlab code
to perform various restoration algorithms with and without noise and display the results.

Solution:
clear; close all; clc;
%%%% Read an Image
im = double(imread('cameraman.tif'));
[M,N] = size(im); % Size of the image

% Display the original image


figure();imshow(uint8(im)); title('Original Image');

% FFT of the original image and centering


imF = fftshift(fft2(im));
Consider the case of Blurred image and no noise.
% Generation of Gaussian blurring kernel with radius cut-off
% frequency of D = 15, and order of the filter 2.
H = lbutter(im,15,2);
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

% Generation of Blurried image


imFH = imF.*H;

Exercise9.1: Display the following signals:


(a) Centered horizontal intensity line profile of the original image.
(b) Log spectrum of the original image
(c) Optical Transfer Function (OTP) in (i) 2D image and (ii) 3D mesh.
(d) Point Spread Function (PSF) in (i) 2D image and (ii) 3D mesh.
(e) Centered horizontal intensity line profile of OTP.
(f) Centered horizontal intensity line profile of PSF.
(g) Log spectrum of blurred image.
(h) Develop Matlab code to find the blurred image in spatial domain and display
(i) Centered horizontal intensity line profile of the spatial domain blurred image.
Overlap this plot with the plot of original image in (a) with different colours.
(j) Repeat the above for various cut off frequency radius of (i) 8, (ii) 30, and
(iii) 60 and order of (i) 5, (ii) 10 and (iii) 15 of the degradation filter
(k) Repeat the above for the images of size 512 x 512 and 1024 x 1024.

< Type the Matlab codes here >


< Plot the figures and type the results here >
9.2 Inverse Filtering: Ideally the reconstruction filter must be inverse process of degradation
function.
1
That is H r (u, v) =
H (u, v)
Then the estimated signal is represented by
)
F (u, v) = G (u , v) H r (u , v) = {H (u , v) F (u , v) + N (u , v )}H r (u , v )
1
= {H (u , v) F (u , v) + N (u , v)}
H (u , v)
N (u , v)
= F (u , v) +
H (u , v)
N (u , v)
Hence the inverse filtered image is the sum of original image plus . Ideally the term
H (u , v)
N (u , v)
must be smaller values if the H (u , v ) coefficients are higher values. If few of the
H (u , v)
coefficients values of H (u , v ) are either zero or smaller values in amplitudes, it amplifies the
noise and the resultant estimated image will be the highly degraded. In order to overcome
these undesired results, two methods are implemented as below;
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Example1 cont..
Write a Matlab code imfh which is the absolute and inverse FFT of imFH

< Type the Matlab codes here >


< Plot the figures and type the results here >
% Inverse Filtering: Attempt to recover the original image by
% dividing by the filter:
imc1 = fftshift(fft2(imfh))./ H;
imLa = real(ifft2(imc1));
imshow(uint8(imLa)); title('Inverse Filtering');
Exercise9.2: (a) Repeat the inverse filtering for various cut off frequency radius of (i) 8,
(ii) 30, and (iii) 60 and order of (i) 5, (ii) 10 and (iii) 15 of the degradation
filter
(b) Repeat the above for the images of size 512 x 512 and 1024 x 1024.
(c) Display the centered horizontal intensity line profile of the inverse filtered
image. Overlap this plot with the plot of original image and blurred image
with different colours.
< Type the Matlab codes here >
< Plot the figures and type the results here >
9.2.1. Method1: Low Pass Filtering: Apply a low pass filter to eliminate very low (or zero)
values:
) G (u, v) )  N (u, v) 
F (u, v) = F (u, v) =  F (u, v) +
H (u, v) 
H LPF (u, v) H LPF (u, v)
H (u, v) 

%% Method1: Applying a LPF to eliminate the small values


imbf = fftshift(fft2(imfh));
imL = (imbf./H).*lbutter(im,25,5);
imLP = abs(ifft2(imL));
imshow(uint8(imLP));title('Low Pass Filtering');

Exercise9.3: Repeat the Exercise2 for the low pass filtering based restoration with various
cur-off frequency radius and order of the filter.

9.2.2. Method2: Constrained division: Choose a threshold value Th, and if | H (u , v) |  Th ,

we don't perform a division, but just keep our original value. Thus

 G (u, v)  N (u, v)
)  , if | H (u, v) |  Th )  F (u, v) + , if | H (u, v) |  Th
F (u , v) =  H (u, v) F (u, v) =  H (u, v)
 G (u, v), if | H (u, v) |  Th  G (u, v) , if | H (u, v) |  Th
 
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

% Method2:Constrained division: Choose a threshold value


Th = % 0.1
Th = 0.1;
b = lbutter(im,15,2);b(b<Th)=1;
imc1 = imFH./b;
imca=abs(ifft2(imc1));
imshow(uint8(imca)); title('Constrained Division');
Exercise9.4: Repeat the Exercise3 for the constrained division based restoration for the
various values of threshold.
< Type the Matlab codes here >
< Plot the figures and type the results here >

9.2.3 Simple Wiener Filtering: Inverse filtering does not necessarily produce particularly
pleasing results. The situation is even worse if the original image has been corrupted by noise.
In such a situation the presence of noise can have a catastrophic effect on the inverse filtering:
the noise can completely dominate the output, making direct inverse filtering impossible. To
overcome this problem, a Wiener filter may be used.
)  1 | H (u, v) | 2 
F (u, v) =   G(u, v) ,
 H (u, v) | H (u, v) | + K 
2

where K is a constant. This constant can be used to approximate the amount of noise:
% Wiener Filtering
K = 0.0001;
wn = imFH.*(abs(H).^2./(abs(H).^2 + K))./H; % Equation
wnr = abs(ifft2(wn));
imshow(uint8(wnr));title('Simple Wiener Filtering');
Exercise9.5: Repeat the Exercise2 for the Wiener filtering based restoration for the various
values of K.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Exercise9.6: Repeat the all above exercises by considering the noise of variance (i) 10, (ii)
25 and (iii) 40.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Exercise9.7: Consider the following commands related to the performance (quality)
measure of the restoration algorithms.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Let an image ‘input_image’ is applied to a restoration technique and the corresponding


restored image is ‘output_image’. It is assumed that both are gray scale images with highest
magnitude of 256.
1. Mean Squared Error (MSE): The Matlab code for mean square error is as follows.
[r,c] = size(input_image);
org = double(org);
est = double(est);
err = org - est; % Error image
DIP_mse = sum(sum(err.*err))/(r*c);

2. Signal to Noise ratio (SNR): The Matlab code for SNR is given by

DIP_SNR = 20*log10(norm(input(:))/norm(input(:)-output(:)));

3. Peak Signal to Noise ratio (PSNR): The Matlab code for PSNR is given by
DIP_PSNR = 10 * log10( 256^2 / DIP_mse);
DIP_PSNR = round(100* DIP_PSNR)/100;

Now find the MSE, SNR and PSNR values for the various restoration algorithms applied to
the blurred and noisy images in the above exercises and tabulate them for each case.

Parameters Blurred and Inverse Low pass Constrained


Wiener
Noisy filtering filtering division
MSE
SNR
PSNR

< Type the Matlab codes here >


< Plot the figures and type the results here >
In lab Session:
(d) Execute the Matlab codes prepared for the exercises and observe the results.
(e) Compute all the tasks given in the exercises. Show the results to your instructor and
get it signed with assigned marks.
(f) Note the results and store the necessary figures and data for the lab report.

Post Lab Session:


(e) Complete the lab work in all aspects in the given specified lab time.
(f) Answer for the given questions.
(g) Submit the lab report to the lab in-structure and get the signature in time.

(h) Type the complete description of commands used in the lab.


Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

VIVA Questions

1)

2)

3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Name: Lab Section: Id No:

Pre-lab Session In-Lab Session Post Lab session Viva Total Marks
work (5M) work (15M) work (5M) (5M) 30M

Remarks if any:

Date: Signature of the Instructor Marks awarded

Digital Image Processing-Lab (15-EC 4110L)


Lab10 - Colour Image Processing

For human beings, colour provides one of the most important descriptors of the world around
us. The human visual system is particularly attuned to two things: edges, and colour. It is well
known that the human visual system is not particularly good at recognizing subtle changes in
grey values. In this experiment, we shall investigate colour briefly, and then some methods of
processing colour images
Objectives
To
(e) Understand the fundamentals of colour image processing.
(f) Discover the primary and secondary colours of colour images.
(g) Conversion of colours from one model other models.
(h) Explore Simple operations on colour images.

Pre lab work:

(d) Study and understand the basic theory required for this lab.
(e) Run the Matlab scripts given for examples and study the results.
(f) Prepare the Matlab codes for the given laboratory exercises well before the
commencement of lab scheduled time. Discuss with your lab instructors for further
clarifications.

10.1 Basic Theory: The human visual system tends to perceive colour as being made up of
varying amounts of red, green and blue are referred to as primary colours. That is, human
vision is particularly sensitive to these colours; this is a function of the cone cells in the retina
of the eye. If we add together any two primary colours, we obtain the secondary colours:
Magenta (purple) = red + blue, cyan = green + blue and yellow = red + green
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Example10.1: (a) Read a colour image of your choice, divide into three primary colour
channels (Red, Green and Blue images) and display them.
(b) Combine all the three colours and test the resultant image is original colour image or not?
Comment.
Solution: Refer DIP_10.1.m
< Type the Matlab codes here >
< Plot the figures and type the results here >
Exercise10.1:
(a) Display the following combination of the primary colour components and comment on these
results. (i) x = 0.5 Red +blue (ii) y = 0.3 Red + 0.6Blue – 0.5 green, and
(iii) z = 0.299 Red + 0.587 Green + 0.114 Blue
(b) Generate and display the secondary colours, cyan, Magenta and yellow colour images
from primary colour images. Now add these complement components and display. Is the
resultant image is just complement of original colour image? Comment.
(c) Display the following combination of the secondary colour components.
(ii) Magenta - 0.5 yellow (ii) 0.3 Magenta - 0.6cyan +1.2 green
(d) Generate and display the complement of the primary colour components and display them
separately. Now add these complement components and display. Is the resultant image is just
complement of original colour image? Comment.
(e) Is CMY image = 1 - RGB image?
(f) Generate the YIQ image from the primary colour components and vise versa with the
following conversion matrices.

Y  0.299 0.587 0.114   R   R  1.000 0.956 0.621   Y 


 I  = 0.596 −0.274 −0.322  G  , and G  = 1.000 −0.272 −0.647   I 
         
Q   0.211 −0.523 0.312   B   B  1.000 −1.106 1.703  Q 

(g) Using the command rgb2hsv.m, find and display the H, S, and V components.
(h) Using the command rgb2ntsc.m, find and display the Y, I, and Q components.
(i) Find and display the histograms of Red, Green and Blue components of the original colour
image.
(j) Find and display the histograms of secondary colour components (cyan, Magenta and
yellow) of the original image.
(k) Change the brightness and contrast and display the histograms in single window image.
(i) Convert the RGB colour image into indexed image and display. What observations you are
made from these two images? Comment.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

10.2 Contrast enhancement for colour images: Contrast enhancement for colour
images can be done in two ways as illustrated below:
Method1: RGB processing: Colour enhancement using RGB processing method is
illustrated ab below:

Fig 10.1 Block diagram of histogram equalization by RGB processing

Exercise2: (a) Perform the histogram equalization for three primary colour components
obtained in the example DIP_10.1.m, as shown in the above block diagram.
(b) Display the histogram equalized images and compare with the primary colour components.
(c) Now combine the histogram equalized images and display the results.
< Type the Matlab codes here >
< Plot the figures and type the results here >
Method2: Intensity processing: Colour enhancement using intensity processing method is
illustrated ab below:

Fig 10.2 Block diagram of histogram equalization by Intensity processing

Exercise3: (a) Collect YIQ components generated in exercise10.1(f). Now perform histogram
equalization to the Y component only as shown in the above block diagram.
(b) Compare the histogram equalized Y component with the original Y component.
(c) Now combine the histogram equalized Y component with I and Q components and display
the results.
(d) Compare and contrast the two methods of enhancement techniques with the above results.
Exercise4: Repeat the above exercises for various colour images of different size.
< Type the Matlab codes here >
< Plot the figures and type the results here >

In lab Session:
(g) Execute the Matlab codes prepared for the exercises and observe the results.
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

(h) Compute all the tasks given in the exercises. Show the results to your
instructor and get it signed with assigned marks.
(i) Note the results and store the necessary figures and data for the lab report.

Post Lab Session:


(i) Complete the lab work in all aspects in the given specified lab time.
(j) Answer for the given questions.
(k) Submit the lab report to the lab in-structure and get the signature in time.
(l) Type the complete description of commands used in the lab.

VIVA Questions

1)

2)

3)
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:
Digital Image Processing Lab, Dept. of ECE, KL University, A.P., India. Student Id No:

Вам также может понравиться