Uploaded by Kashish Goyal

DIP

advertisement
INDIAN INSTITUTE OF
INFORMATION
TECHNOLOGY BHOPAL
DIGITAL IMAGE PROCESSING
LAB MANUAL
PREPARED BY:
KASHISH GOYAL (19U02040)
Department of Electronics &
Communication Engineering
List of Experiments
Sr.
No.
Name of Experiment
1.
Introduction to MATLAB commands used in Digital Image Processing
2.
Write programs to read and display images using MATLAB.
3.
To display and read gray-scale images in MATLAB
4.
To write a program for histogram calculation and equalization
5.
6.
7.
•
Standard MATLAB function
•
Enhancing Contrast using histogram equalization
To write and execute programs for image arithmetic operations
•
Addition of two images
•
Subtract one image from other image
•
Calculate mean value of image
•
Different Brightness by changing mean value
To write and execute programs for image logical operations
•
AND operation between two images
•
OR operation between two images
•
Calculate intersection of two images
To write and execute program for geometric transformation of image
•
Translation
•
Scaling
•
Rotation
•
Shrinking
•
8.
Zooming
Write and execute programs for image frequency domain filtering
•
Apply FFT on given image
•
Perform low pass and high pass filtering in frequency domain
•
Apply IFFT to reconstruct image
9.
Write a program in MATLAB for edge detection using different edge
detection mask
10.
Write and execute programs to remove noise using spatial filters
•
Understand 1-D and 2-D convolution process
•
Use 3x3 Mask for low pass filter and high pass filter
EXPERIMENTNO. 1
Aim:
Introduction to MATLAB commands used in Image Processing.
Commands:
Image Type Conversion
gray2ind
Convert grayscale or binary image to indexed image
ind2gray
Convert indexed image to grayscale image
mat2gray
Convert matrix to grayscale image
rgb2lightness
Convert RGB color values to lightness values
im2int16
Convert image to 16-bit signed integers
im2java2d
Convert image to Java buffered image
im2single
Convert image to single precision
im2uint16
Convert image to 16-bit unsigned integers
im2uint8
Convert image to 8-bit unsigned integers
Image Sequences and Batch Processing
implay
Play movies, videos, or image sequences
montage
Display multiple image frames as rectangular montage
Color
rgb2lab
Convert RGB to CIE 1976 L*a*b*
rgb2ntsc
Convert RGB color values to NTSC color space
rgb2xyz
Convert RGB to CIE 1931 XYZ
rgb2ycbcr
Convert RGB color values to YCbCr color space
lab2rgb
Convert CIE 1976 L*a*b* to RGB
lab2xyz
Convert CIE 1976 L*a*b* to CIE 1931 XYZ
ntsc2rgb
Convert NTSC values to RGB color space
xyz2lab
Convert CIE 1931 XYZ to CIE 1976 L*a*b*
xyz2rgb
Convert CIE 1931 XYZ to RGB
ycbcr2rgb
Convert YCbCr color values to RGB color space
Display and Exploration
Basic Display
imshow
Display image
imfuse
Composite of two images
imshowpair
Compare differences between images
montage
Display multiple image frames as rectangular montage
immovie
Make movie from multiframe image
implay
Play movies, videos, or image sequences
Build Interactive Tools
imageinfo
Image Information tool
imcolormaptool
Choose Colormap tool
imcontrast
Adjust Contrast tool
imcrop
Crop image
imcrop3
Crop 3-D image
imagemodel
Image Model object
axes2pix
Convert axes coordinates to pixel coordinates
imattributes
Information about image attributes
imgca
Get current axes containing image
imgcf
Get current figure containing image
imgetfile
Display Open Image dialog box
imputfile
Display Save Image dialog box
imhandles
Get all image objects
Geometric Transformation and Image Registration
Common Geometric Transformations
imcrop
Crop image
imcrop3
Crop 3-D image
imresize
Resize image
imresize3
Resize 3-D volumetric intensity image
imrotate
Rotate image
imrotate3
Rotate 3-D volumetric grayscale image
imtranslate
Translate image
impyramid
Image pyramid reduction and expansion
Generic Geometric Transformations
imwarp
Apply geometric transformation to image
affineOutputView
Create output view for warping images
fitgeotrans
Fit geometric transformation to control point pairs
findbounds
Find output bounds for spatial transformation
fliptform
Flip input and output roles of spatial transformation structure
makeresampler
Create resampling structure
maketform
Create spatial transformation structure (TFORM)
tformarray
Apply spatial transformation to N-D array
tformfwd
Apply forward spatial transformation
tforminv
Apply inverse spatial transformation
images.geotrans.Warper
Apply same geometric transformation to many images efficiently
imref2d
Reference 2-D image to world coordinates
imref3d
Reference 3-D image to world coordinates
affine2d
2-D affine geometric transformation
affine3d
3-D affine geometric transformation
projective2d
2-D projective geometric transformation
geometricTransform2d
2-D geometric transformation object
geometricTransform3d
3-D geometric transformation object
Image Filtering and Enhancement
Image Filtering
imfilter
N-D filtering of multidimensional images
fspecial
Create predefined 2-D filter
fspecial3
Create predefined 3-D filter
roifilt2
Filter region of interest (ROI) in image
nlfilter
General sliding-neighborhood operations
imgaussfilt
2-D Gaussian filtering of images
imgaussfilt3
3-D Gaussian filtering of 3-D images
wiener2
2-D adaptive noise-removal filtering
medfilt2
2-D median filtering
medfilt3
3-D median filtering
ordfilt2
2-D order-statistic filtering
stdfilt
Local standard deviation of image
rangefilt
Local range of image
entropyfilt
Local entropy of grayscale image
imboxfilt
2-D box filtering of images
imboxfilt3
3-D box filtering of 3-D images
fibermetric
Enhance elongated or tubular structures in image
maxhessiannorm
Maximum of Frobenius norm of Hessian of matrix
convmtx2
2-D convolution matrix
padarray
Pad array
imbilatfilt
Bilateral filtering of images with Gaussian kernels
imdiffuseest
Estimate parameters for anisotropic diffusion filtering
imdiffusefilt
Anisotropic diffusion filtering of images
imguidedfilter
Guided filtering of images
imnlmfilt
Non-local means filtering of image
burstinterpolant
Create high-resolution image from set of low-resolution burst mode images
gabor
Create Gabor filter or Gabor filter bank
imgaborfilt
Apply Gabor filter or set of filters to 2-D image
bwareafilt
Extract objects from binary image by size
bwpropfilt
Extract objects from binary image using properties
freqz2
2-D frequency response
fsamp2
2-D FIR filter using frequency sampling
ftrans2
2-D FIR filter using frequency transformation
fwind1
2-D FIR filter using 1-D window method
fwind2
2-D FIR filter using 2-D window method
Contrast Adjustment
imadjust
Adjust image intensity values or colormap
imadjustn
Adjust intensity values in N-D volumetric image
imcontrast
Adjust Contrast tool
imsharpen
Sharpen image using unsharp masking
imflatfield
2-D image flat-field correction
imlocalbrighten
Brighten low-light image
imreducehaze
Reduce atmospheric haze
locallapfilt
Fast local Laplacian filtering of images
localcontrast
Edge-aware local contrast manipulation of images
localtonemap
Render HDR image for viewing while enhancing local contrast
histeq
Enhance contrast using histogram equalization
adapthisteq
Contrast-limited adaptive histogram equalization (CLAHE)
imhistmatch
Adjust histogram of 2-D image to match histogram of reference image
imhistmatchn
Adjust histogram of N-D image to match histogram of reference image
decorrstretch
Apply decorrelation stretch to multichannel image
stretchlim
Find limits to contrast stretch image
intlut
Convert integer values using lookup table
imnoise
Add noise to image
Neighborhood and Block Processing
blockproc
Distinct block processing for image
bestblk
Determine optimal block size for block processing
nlfilter
General sliding-neighborhood operations
col2im
Rearrange matrix columns into blocks
colfilt
Columnwise neighborhood operations
im2col
Rearrange image blocks into columns
ImageAdapter
Interface for image I/O
Image Arithmetic
imabsdiff
Absolute difference of two images
imadd
Add two images or add constant to image
imapplymatrix
Linear combination of color channels
imcomplement
Complement image
imdivide
Divide one image into another or divide image by constant
imlincomb
Linear combination of images
immultiply
Multiply two images or multiply image by constant
imsubtract
Subtract one image from another or subtract constant from image
Image Segmentation and Analysis
Image Segmentation
activecontour
Segment image into foreground and background using active contours
(snakes)
imsegfmm
Binary image segmentation using Fast Marching Method
imseggeodesic
Segment image into two or three regions using geodesic distance-based color
segmentation
imsegkmeans
K-means clustering based image segmentation
imsegkmeans3
K-means clustering based volume segmentation
watershed
Watershed transform
gradientweight
Calculate weights for image pixels based on image gradient
graydiffweight
Calculate weights for image pixels based on grayscale intensity difference
grayconnected
Select contiguous image region with similar gray values
Region and Image Properties
imhist
Histogram of image data
mean2
Average or mean of matrix elements
std2
Standard deviation of matrix elements
corr2
2-D correlation coefficient
bwconncomp
Find connected components in binary image
bwareaopen
Remove small objects from binary image
Image Transforms
hough
Hough transform
dct2
2-D discrete cosine transform
dctmtx
Discrete cosine transform matrix
fan2para
Convert fan-beam projections to parallel-beam
fanbeam
Fan-beam transform
idct2
2-D inverse discrete cosine transform
ifanbeam
Inverse fan-beam transform
iradon
Inverse Radon transform
para2fan
Convert parallel-beam projections to fan-beam
radon
Radon transform
EXPERIMENT NO. 2
Aim:Write program to read and display image using MATLAB.
Theory:
In this experiment ,we will learn how to read and display the images using
matlab.
Following command are used to read and display images in matlab.
To read image- imread()
To display image- imshow()
MATLAB Code:
% 2-write a program to read and display images using matlab
I = imread("kashish2.jpg");
%read the image
imshow(I)
%display the image
Result:
Conclusion:
Program for reading and displaying image using MATLAB is executed.
EXPERIMENT NO. 3
Aim:To display the Gray scale images
Theory:
TheoryIn this experiment, we will learn how to convert rgb images in grayscale and display them.
Following commands are used to perform this experimentTo read image- imread()
To display image- imshow()
To convert image into gray-scale- rgb2gray()
MATLAB Code:
% 3-To display and read gray scale images into matlab
clc;
clear all;
I=imread('kashish2.jpg');
subplot(121);
imshow(I);
title('Original Image');
I1=rgb2gray(I);
subplot(122);
imshow(I1);
title('Gray Image');
Result:
% clear the workspace
% read image I
% dispaly image
% converting I to gray scale
% display I1
Conclusion:
Thus the gray scale image is displayed.
EXPERIMENT NO. 4
Aim: To write a program for histogram calculation and equalization using
MATLAB.
Standard MATLAB function Enhancing Contrast using histogram
equalization
Theory:
In this experiment, we will learn how to do histogram calculation and
equalization.
Following commands are used to perform this experimentTo read image- imread()
To display image- imshow()
To convert image into gray-scale -rgb2gray()
To convert image into histogram equalized image- histeq()
To get the histogram of the image- imhist()
Standard MATLAB function for histogram and histogram
equalization:
[1] imhist function
It computes histogram of given image and plot
Example:
myimage=imread(‘tier.jpg’)
imhist(myimage);
[1] histeq function
It computes histogram and equalize it.
Example:
myimage = imread(‘rice.bmp’);
newimage= histeq(myimage);
MATLAB CODE:
% To write a program for histogram calculation and equalization
MATLAB.
clc;
clear all;
using
I=imread("kashish2.jpg");
I=rgb2gray(I);
% read I
% grayscale image
I1=histeq(I);
% histogram equivalent image
figure,subplot(221);
imshow(I);
title("Original Image");
% display original image
subplot(222);
imshow(I1);
% Histogram equalized image
title("Histogram equalized image");
subplot(223);
imhist(I);
% Histogram of original image
title("Histogram of original image");
subplot(224);
imhist(I1);
% Histogram of equalized image
title("Histogram of equalized image");
Result:
Conclusion:
We have used histogram Equalization to enhance contrast.
EXPERIMENT NO. 5
Aim:To write and execute programs for image arithmetic operations
using MATLAB.
Theory:
In this experiment we will learn how to implement arithmetic operation in
images.
We will do addition, subtraction, multiplication and division of images.
For this ,each image should have same dimensions.
For example ,let there are two images I and J.
And if I have dimension 600*400*3 uint array ,then image J should
also have the same
MATLAB CODE:
clc
close all
I1 = imread('cameraman.tif');
I2 = imread('rice.png');
subplot(2, 2, 1);
imshow(I1);
title('Original image I1');
subplot(2, 2,2);
imshow(I2);
title('Original image I2');
I=I1+I2; % Addition of two images
subplot(2, 2, 3);
imshow(I);
title('Addition of image I1+I2');
I=I1-I2; %Subtraction of two images
subplot(2,2,4);
imshow(I);
title('Subtraction of image I1-I2');figure;
subplot(2, 2, 1);
imshow(I1);
title('Original image I1');
I=I1+50;
subplot(2, 2, 2);
imshow(I);
title('Bright Image I');
I=I1-100;
subplot(2, 2, 3);
imshow(I);
title('Dark Image I');
M=imread('Mask.tif');
M=im2bw(M) % Converts into binary image having 0s and
1sI=uint8(I1).*uint8(M); %Type casting before
multiplicationsubplot(2, 2, 4);
imshow(I);
title('Masked Image I');
Result:
Conclusion:
MATLAB program to implement arithmetic operation on images is
executed.
EXPERIMENT NO. 6
Aim:To write and execute programs for image logical operations
 AND operation between two images
 OR operation between two images
 Calculate intersection of two images
Theory: In this experiment ,we will learn how to perform logical operations
between two images
And how to calculate intersection of two images.To perform this experiment
,prior knowledge about AND and OR is required.
MATLAB Code:
clc;
close all;
%close all
clear scr;
%clear screen
%Read 1st Image
I1=imread('https://images.unsplash.com/photo-1632918425579fd8b2a59edc6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=1854&q=80');
I1=rgb2gray(I1);
%Read 2nd Image
I2=imread('https://images.unsplash.com/photo-16329321978186b131c21a961?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=387&q=80');
I2=rgb2gray(I2);
[row,column,col]=size(I1);
I2=imresize(I2,[row,column]);
figure;
%Display 1st image
subplot(331);imshow(I1);title('First Image');
%Display 2nd image
subplot(332);imshow(I2);title('Second Image');
%Or Operation
LogOr=bitor(I1,I2);subplot(333);imshow(LogOr);title('Or of images');
%And Operation
LogAnd=bitand(I1,I2);subplot(334);imshow(LogAnd);title('And of Images');
%Complement of 1st image
c= imcomplement(I1);subplot(335);imshow(c);title('Complement of 1st');
%Complement of 2nd image
c2= imcomplement(I2);subplot(336);imshow(c2);title('Complement of 2nd');
%xor
xor=bitxor(I1,I2);subplot(337);imshow(xor);title('Xor of images');
%xnor
xnor=imcomplement(xor);subplot(338);imshow(xnor);title('Xnor of images');
%xnand
nand=imcomplement(LogAnd);subplot(339);imshow(n
and);title('Nand of images');
Result:
Conclusion:
MATLAB program to implement logical operations is implemented.
EXPERIMENT NO. 7
Aim: To write and execute programs for geometric transformation of images





Translation
Scaling
Rotation
Shrinking
Zooming
Theory: We will perform following geometric transformations on the
image in this experiment
Translation- Translation is movement of image to new position.
Mathematically translation is represented as:
x’=x+δx
and y’=y+δy
Scaling- Scaling means enlarging or shrinking.
Mathematically scaling can be represented as:
x’=x*Sx
and y’=y*Sy
Rotation- Image can be rotated by an angle θ ,in matrix form it can be
represented as if -θ. This matrix rotates the image in clockwise
direction
Zooming-Zooming of image can be done by process called pixel
replication or interpolation .Linear interpolation or some non-linear
interpolation like cubic interpolation can be performed for better
result.
Shearing- Image can be distorted (sheared) either in x direction or y
direction.
Shearing can be represented as:
x’=shx * y and y’=y
MATLAB Code:
%% TRANSLATION
%
%
%
%
%
Syntax
B= imtranslate(A,translation)
[B,RB] =imtranslate(A,RA,translation)
_=imtranslate(_,method)
_=imtranslate(_,Name,Value)
x=imread('https://images.unsplash.com/photo-1632918425579fd8b2a59edc6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=1854&q=80');
figure,subplot(221); imshow(x);title("Original image");
y=imtranslate(x,[25,25])
subplot(222); imshow(y);title("Translated image");
y=imtranslate(x,[-20,25])
subplot(223); imshow(y);title("Translated image");
y=imtranslate(x,[25,-20])
subplot(224); imshow(y);title("Translated image");
x=imread('https://images.unsplash.com/photo-16329321978186b131c21a961?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=387&q=80');
figure,subplot(221); imshow(x);title("Original image");
y=imtranslate(x,[125,125])
subplot(222); imshow(y);title("Translated image");
y=imtranslate(x,[-120,125])
subplot(223); imshow(y);title("Translated image");
y=imtranslate(x,[125,-120])
subplot(224); imshow(y);title("Translated image");
Result:
%% ROTATION
% J= imrotate(I,angle)
% J=imrotate(I,angle,method)
% J=imrotate(I,angle,method,bbox)
x=imread('https://images.unsplash.com/photo-1632918425579fd8b2a59edc6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=1854&q=80');
figure,subplot(221); imshow(x); title("Original Image");
y=imrotate(x,45,"bilinear");
subplot(222); imshow(y); title("Image rotated by 45 degree");
y=imrotate(x,90,"bilinear");
subplot(223); imshow(y); title("Image rotated by 90 degree");
y=imrotate(x,-45,"bilinear");
subplot(224); imshow(y); title("Image rotated by -45 degree");
%% Rotated image to be cropped
x=imread('https://images.unsplash.com/photo-1632918425579fd8b2a59edc6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=1854&q=80');
figure,subplot(221); imshow(x); title("Original Image");
y=imrotate(x,45,"bilinear","crop");
subplot(222); imshow(y); title("Image rotated by 45 degree");
y=imrotate(x,90,"bilinear","crop");
subplot(223); imshow(y); title("Image rotated by 90 degree");
y=imrotate(x,-45,"bilinear","crop");
subplot(224); imshow(y); title("Image rotated by -45 degree");
Output
Cropped image after rotation
%% SHEARING
x=imread('https://images.unsplash.com/photo-16329321978186b131c21a961?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=387&q=80');
figure; subplot(221); imshow(x); title("Original Image");
tform = maketform("affine",[1 0 0; .5 1 0; 0 0 1]);
y=imtransform(x,tform);
subplot(222); imshow(y); title("Shear in x direction");
tform = maketform("affine",[1 .5 0; .5 1 0; 0 0 1]);
y=imtransform(x,tform);
subplot(223); imshow(y); title("Shear in y direction");
tform = maketform("affine",[1 0.5 0; .5 1 0; 0 0 1]);
y=imtransform(x,tform);
subplot(224); imshow(y); title("Shear in x-y direction");
Output-
%% SCALING
% imresize- resize the image
x=imread('https://images.unsplash.com/photo-16329321978186b131c21a961?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=387&q=80');
figure; subplot(221); imshow(x); title("Originl Image");
y=imresize(x,[100,200]);
subplot(222); imshow(y); title("Resized Image by [100,200]");
y=imresize(x,[75,75]);
subplot(223); imshow(y); title("Resized Image by [75,75]");
y=imresize(x,1.5);
subplot(224); imshow(y); title("Resized Image by 1.5");
Output-
Conclusion:
Different geometrical transforms are applied successfully
EXPERIMENT NO. 8
Aim: Write and execute programs for image frequency domain filtering
Theory:
In spatial domain, we perform convolution of filter mask with image
data. In frequency domain, we perform multiplication of Fourier
transform of image data with filter transfer function.
Basic steps for filtering in frequency domain:
Pre-processing: Multiply input image f(x,y) by (-1)x+y to center the
transform
Computer Discrete Fourier Transform F(u,v) of input image f(x,y)
Multiply F(u,v) by filter function H(u,v) Result: H(u,v)F(u,v)
Computer inverse DFT of the result
Obtain real part of the result
Post-Processing: Multiply the result by (-1)x+y
MATLAB Code:
%Program for frequency domain filtering
clc;
close all;
clear all;
% Read the image, resize it to 256 x 256
% Convert it to grey image and display it
myimg=imread('https://images.unsplash.com/photo-16329321978186b131c21a961?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb1.2.1&auto=format&fit=crop&w=387&q=80');
if(size(myimg,3)==3)
myimg=rgb2gray(myimg);
end
myimg = imresize(myimg,[256 256]);
myimg=double(myimg);
subplot(2,2,1);
imshow(myimg,[]),title('Original Image');
[M,N] = size(myimg); % Find size
%Preprocessing of the image
for x=1:M
for y=1:N
myimg1(x,y)=myimg(x,y)*((1)^(x+y));
end
end
% Find FFT of the image
myfftimage = fft2(myimg1);
subplot(2,2,2);
imshow(myfftimage,[]); title('FFT Image');
% Define cut off frequency
low = 30;
band1 = 20;
band2 = 50;
%Define Filter Mask
mylowpassmask = ones(M,N);
mybandpassmask = ones(M,N);
% Generate values for ifilter pass mask
for u = 1:M
for v = 1:N
tmp = ((u-(M/2))^2 +(v-(N/2))^2)^0.5;
if tmp > low
mylowpassmask(u,v) = 0;
end
if tmp > band2 || tmp < band1;
mybandpassmask(u,v) = 0;
end
end
end
% Apply the filter H to the FFT of the Image
resimage1 = myfftimage.*mylowpassmask;
resimage3 = myfftimage.*mybandpassmask;
% Apply the Inverse FFT to the filtered image
% Display the low pass filtered image
r1 = abs(ifft2(resimage1));
subplot(2,2,3);
imshow(r1,[]),title('Low Pass filtered image');
% Display the band pass filtered image
r3 = abs(ifft2(resimage3));
subplot(2,2,4);
imshow(r3,[]),title('Band Pass filtered image');
figure;
subplot(2,1,1);imshow(mylowpassmask);
subplot(2,1,2);imshow(mybandpassmask);
Result:
Conclusion:
MATLAB program for frequency domain filtering is executed.
EXPERIMENT NO. 9
Aim:Write MATLAB code for edge detection using different edge
detection mask.
Theory:
Image segmentation is to subdivide an image into its component
regions or objects. Segmentation should stop when the objects of
interest in an application have been isolated. Basic purpose of
segmentation is to partition an image into meaningful regions for
particular application The segmentation is based on measurements
taken from the image and might be grey level, colour, texture, depth or
motion.
There are basically two types of image segmentation approaches:
[1] Discontinuity based: Identification of isolated points, lines or
edges [2] Similarity based: Group pixels which has similar
characteristics by thresholding, region growing, region splitting
and merging .
Edge detection is discontinuity based image segmentation approach.
Edges play a very important role in many image-processing
applications. It provides outline of an object. In physical plane, edges
are corresponding to changes in material properties, intensity
variations, and discontinuity in depth. Pixels on the edges are called
edge points. Edge detection techniques try to find out grey level
transitions.
First order derivative and second order derivative operators can do edge
detection.
First order line detection 3x3 mask are:
Popular edge detection masks:
Sobel operator performs well for image with noise compared to Prewitt
operator because Sobel operator performs averaging along with edge
detection.
Because Sobel operator gives smoothing effect, spurious edges will not be
detected by it.
Second derivative operators are sensitive to the noise present in the image
so it is not directly used to detect edge but it can be used to extract
secondary information like …
Used to find whether point is on darker side or white side depending on sign
of the result
Zero crossing can be used to identify exact location of edge whenever there
is a gradual transition in the image
MATLAB CODE:
Using standard functions:
% Program for edge detection
using standard masks
clear all;
[filename,pathname]=uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpeg;*.
gif','IMAGE Files (*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'},'Choose
Image');
A=imread(
filename)
;if(size(
A,3)==3)A
=rgb2gray
(A);end
imshow(A
);figure
;
BW = edge(A,'prewitt');
subplot(3,2,1); imshow(BW);title('Edge
detection with prewitt mask');
BW = edge(A,'canny');
subplot(3,2,2); imshow(BW);;title('Edge
detection with canny mask');
BW = edge(A,'sobel');
subplot(3,2,3); imshow(BW);;title('Edge
detection with sobel mask');
BW = edge(A,'roberts');
subplot(3,2,4); imshow(BW);;title('Edge detection
with roberts mask');
BW = edge(A,'log');
subplot(3,2,5); imshow(BW);;title('Edge
detection with log ');
BW = edge(A,'zerocross');
subplot(3,2,6); imshow(BW);;title('Edge detection
with zerocorss');
MATLAB Code for edge detection using convolution in spatial
domain
% Program to demonstrate various point and
edge detection mask
clear all;
clc;
while 1:
K = menu('Choose mask','Select Image File','Point
Detect','Horizontal line detect','Vertical line detect','+45
Detect','-45 Detect','ractangle Detect','exit')
M=[-1 0 -1; 0 4 0; -1 0 -1;]
% Default mask
switch K
case 1,
[namefile,pathname]=uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpeg;*.
gif','IMAGE Files (*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'},'Chose
GrayScale Image');
data=imread(strcat(pathname,namefile));
%data=rgb2gray(data);
imshow(data);
case 2,
M=[-1 -1 -1;-1 8 -1;-1 -1 -1];
% Mask for point detection
case 3,
M=[-1 -1 -1; 2 2 2; -1 -1 -1]; %
Mask for horizontal edges
case 4,
M=[-1 2 -1; -1 2 -1; -1 2 -1];
% Mask for vertical edges
case 5,
M=[-1 -1 2; -1 2 -1; 2 -1 -1]; %
Mask for 45 degree diagonal line
case 6,
M=[2 -1 -1;-1 2 -1; -1 -1 2]; % Mask
for -45 degree diagonal line
case 7,
M=[-1 -1
-1;-1 8 -1;-1 -1
-1];
case 8,break;
otherwise,
msgbox('Select proper mask');
end
outimage=conv2(double(data),double(M));figure;
imshow(outimage);
end
close all
%Write an image to a file
imwrite(mat2gray(outimage),'outimage.jpg','quality'
,99);
Result:
Conclusion
MATLAB program for edge detection is executed.
Tutorial:
1.) Get mask for “Prewitt”, “Canny”, “Sobel” from the literature and
write MATLAB/SCILAB program for edge detection using
2Dconvolution
2.) Write a MATLAB code for edge detection of a grayscale image
without using in-built function of edge detection.
EXPERIMENT NO. 10
Aim:
Write and execute programs to remove noise using spatial filters
•
Understand 1-D and 2-D convolution process
•
Use 3x3 Mask for low pass filter and high pass filter
Theory:
Spatial Filtering is sometimes also known as neighborhood processing.
Neighborhood processing is an appropriate name because you define a
center point and perform an operation (or apply a filter) to only those
pixels in predetermined neighborhood of that center point. The result
of the operation is one value, which becomes the value at the center
point's location in the modified image. Each point in the image is
processed with its neighbors. The general idea is shown below as a
"sliding filter" that moves throughout the image to calculate the value
at the center location.
In spatial filtering, we perform convolution of data with filter
coefficients. In image processing, we perform convolution of 3x3 filter
coefficients with 2-D image data. In signal processing, we perform
convolution of 1-D data with set of filter coefficients.
MATLAB CODE:
1D convolution (Useful for 1-D Signal Processing):
clear;
clc;
x=input("Enter value of x: ")
y=input("Enter value of y: ")
n=length(x)
k=length(y)
for z=n+1:n+k-1
x(z)=0;
end
for u=k+1:n+k-1
y(u)=0;
end
for i=1:n+k-1
s(i)=0
for j=1:i
s(i)=(x(j)*y(i-j+1))+s(i)
end
end
subplot(3,1,1)
plot2d3(x)
subplot(3,1,2)
plot2d3(y)
subplot(3,1,3)
plot2d3(s)
Take value of x: [ 1 2 3 4 5 6 7 8 9 0 10 11 12 13 14 15]
Y: [-1 1]
Program for 2D convolution:
clear;
clc;
x=input("Enter value of x in matrix form: ")
y=input("Enter value of y in matrix form: ")
[xrows,xcols]=size(x);
[yrows,ycols]=size(y);
result=zeros(xrows+yrows,xcols+ycols)
for r = 1:xrows-1
for c = 1:xcols-1
sum=0;
for a=0:yrows
for b=0:ycols
sum=sum+x(r+a,c+b)*y(a+1,b+1);
end
end
result(r,c)=sum;
end
end
MATLAB Code:
% Experiment No. 10 Spatial filtering using
standard MATLAB function
% To apply spatial filters on given image
clc;
close all;
clear all;
%Define spatial filter masks
L1=[1 1 1;1 1 1;1 1 1];
L2=[0 1 0;1 2 1;0 1 0];
L3=[1 2 1;2 4 2;1 2 1];
H1=[-1 -1 -1;-1 9 -1;-1 -1 -1];
H2=[0 -1 0;-1 5 -1;-0 -1 0];
H3=[1 -2 1;-2 5 -2;1 -2 1];
% Read the test image and display it
[filename,pathname]=uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpe
g;*.gif','IMAGE Files
(*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'},'Chose Image File');
myimage = imread(cat(2,pathname,filename));
if(size(myimage,3)==3)
myimage=rgb2gray(myimage);
end
subplot(3,2,1);
imshow(myimage); title('Original Image');
L1 = L1/sum(L1);
filt_image= conv2(double(myimage),double(L1)); subplot(3,2,2);
imshow(filt_image,[]);
title('Filtered image with mask L1');
L2 = L2/sum(L2);
filt_image= conv2(double(myimage),double(L2));
subplot(3,2,3);
imshow(filt_image,[]); title('Filtered image with mask L2');
L3 = L3/sum(L3);
filt_image= conv2(double(myimage),double(L3));
subplot(3,2,4); imshow(filt_image,[]); title('Filtered image
with mask L3');
filt_image= conv2(double(myimage),H1);
subplot(3,2,5); imshow(filt_image,[]); title('Filtered image
with mask H1');
filt_image= conv2(double(myimage),H2);
subplot(3,2,6); imshow(filt_image,[]); title('Filtered image
with mask H1');
figure; subplot(2,2,1); imshow(myimage); title('Original
Image'); % The command fspecial() is used to create mask
% The command imfilter() is used to apply the gaussian filter
mask to the image
% Create a Gaussian low pass filter of size 3
gaussmask = fspecial('gaussian',3);
filtimg = imfilter(myimage,gaussmask);
subplot(2,2,2); imshow(filtimg,[]),title('Output of Gaussian
filter 3 X 3');
% Generate a lowpass filter of size 7 X 7
% The command conv2 is used the apply the
filter
% This is another way of using the filter
avgfilt = [ 1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1];
avgfiltmask = avgfilt/sum(avgfilt);
convimage= conv2(double(myimage),double(avgfiltmask));
subplot(2,2,3); imshow(convimage,[]); title('Average filter
with conv2()');
filt_image= conv2(double(myimage),H3);
subplot(3,2,6); imshow(filt_image,[]); title('Filtered image
with mask H3');
Result:
Conclusion:
MATLAB program spatial filtering is executed.
Tutorial:
1.) Write mathematical expression of spatial filtering of image f(x,y) of
size M*N using mask W of size a*b.
2.) What is need for padding? What is zero padding? Why it
isrequired?
3.) What is the effect of increasing size ofmask?
Download