Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

lstDIP Lab Manjj-A)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

INDIAN INSTITUTE OF

INFORMATION TECHNOLOGY
BHOPAL

LAB MANUAL

DIGITAL IMAGE PROCESSING

Submitted By:

Yogesh Jadhav (22U03006)

Submitted To:

Dr. BHUPENDRA SINGH KIRAR


Department of INFORMATION TECHNOLOGY Engineering
List of Experiments

Sr. Name of Experiment Date of


No Experiment

1. Introduction to MATLAB commands used in Digital Image 12-08-2024


Processing
2. Write programs to read and display images using 12-08-2024
MATLAB
3. To display and read gray-scale images in MATLAB 03-09-2024

4. To write a program for histogram calculation and 03-09-2024


equalization
• Standard MATLAB function
• Enhancing Contrast using histogram equalization

5. To write and execute programs for image arithmetic 17-09-202


operations
• Addition of two images

• Subtract one image from other image

• Calculate mean value of image


• Different Brightness by changing mean value
6. To write and execute programs for image logical 24-09-2024
operations
• AND operation between two images

• OR operation between two images


• Calculate intersection of two images.
7. To write and execute program for geometric 10-10-2024
transformation of image
• Translation

• Scaling

• Rotation

• Shrinking
• Zooming
8. Write and execute programs for image frequency 10-10-2024
domain filtering
• Spartial resolution
• Intensity resolution

9. Write and execute programs for image frequency 10-10-2024


domain filtering
• Apply FFT on given image
• Perform low pass and high pass filtering in
frequency domain
Apply IFFT to reconstruct image
10.. Write a program in MATLAB for edge detection 17-10-2024
using different edge detection mask

11. Write and execute programs to remove noise 17-10-2024


using spatial filters

• Understand 1-D and 2-D convolution process


• Use 3x3 Mask for low pass filter and high pass
filter
EXPERIMENT NO. 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


Tutorial:
1.) Give following commands in MATLAB, observe output and write
explanation of each command
t = 0:0.01:1
y=sin(2*%pi*10)
plot(y)

2.) Create image of size 512x512 black square using monochrome,256


gray-level using paint or any other relevant software and save it
file name “black.bmp” Read and display image using MATLAB
commands.
EXPERIMENT NO. 2

Aim:Write program to read and display image using MATLAB.

Theory:

A = imread(filename) reads the image from the file specified by filename,


inferring the format of the file from its contents. If filename is a multi-image
file, then imread reads the first image in the file.

A = imread(filename,fmt) additionally specifies the format of the file with the


standard file extension indicated by fmt. If imread cannot find a file with the
name specified by filename, it looks for a file named filename.fmt
A = imread( ,idx) reads the specified image or images from a multi-image file.
This syntax applies only to GIF, PGM, PBM, PPM, CUR, ICO, TIF, and HDF4
files. You must specify a filename input, and you can optionally specify fmt.
A = imread( ,Name,Value) specifies format-specific options using one or more
name-value pair arguments, in addition to any of the input arguments in the
previous syntaxes.
[A,map] = imread( ) reads the indexed image in filename into A and reads
its associated colormap into map. Colormap values in the image file are
automatically rescaled into the range [0,1].
[A,map,transparency] = imread( ) additionally returns the image
transparency. This syntax applies only to PNG, CUR, and ICO files. For PNG
files, transparency is the alpha channel, if one is present. For CUR and ICO
files, it is the AND (opacity) mask.
MATLAB Code:

% Read the file using imread() function my_image =


imread(YOGESHIMG.jpg);

% Show the image using imshow() function


imshow(my_image);
Result:

Conclusion:
Program for reading and displaying image using MATLAB is executed.

Tutorial:
1.) Write a MATLAB command for the following

->Read color image ‘RGBBar.bmp’ given in working directory,


convert it into Grey-scaleimage0

2.) Write MATLAB command for the following

-> Read color image ‘RGBBar.bmp’ given in working directory,


Find size of the image, Resize it to 256x256
EXPERIMENT NO. 3

Aim:

To display the Gray scale images

Theory:

imshow(I) displays the grayscale image I.


imshow(I,[low high]) displays the grayscale image I, specifying the display
range for I in [low high]. The value low (and any value less than low) displays
as black; the value high (and any value greater than high) displays as white.
Values in between are displayed as intermediate shades of gray, using the
default number of gray levels. If you use an empty matrix ([]) for [low high],
imshow uses [min(I(:)) max(I(:))]; that is, the minimum value in I is displayed
as black, and the maximum value is displayed as white.
MATLAB Code:

image1=imread('YOGESHIMG.jp');

image2=rgb2gray(image1);

[r c d]=size(image1);

z=zeros(r,c); tempr=image1;

tempr(:,:,2)=z;

tempr(:,:,3)=z;

imshow(tempr)

tempg=image1;

tempg(:,:,1)=z;

tempg(:,:,3)=z;

imshow(tempg)

tempb=image1;

tempb(:,:,1)=z;
tempb(:,:,2)=z;

imshow(tempb)

% Create a figure and display the original and grayscale


images side by side figure;

% Display original image


subplot(1, 2, 1);
imshow(image1);
title('ORIGINAL IMAGE');

% Display grayscale image


subplot(1, 2, 2);
imshow(tempb)
title('GRAYSCALE IMAGE');

Result:
Conclusion:

Thus the gray scale image is displayed.

Tutorial:
1.) Write MATLAB program to display grayscale image using image
“cameraman.tif”.

2.) Write MATLAB program to display grayscale image using image


“coins.png”.
EXPERIMENT NO. 4

Aim: To write a program for histogram calculation and equalization


using MATLAB.

Theory:
Histogram is bar-graph used to profile the occurrence of each gray level in the
image.Mathematically it is represented as h(rk)=nk.Where rk is kth grey level
and nk is number of pixel having that greylevel.Histogram can tell us whether
image was scannedproperly or not. It gives us idea about tonal distribution
in the image.Histogram equalization can be applied to improveappearance of
the image.Histogram also tells us about objects in the image. Object in an
image have similar gray levels so histogram helps us to select threshold value
for object detection.Histogram can be used for image segmentation.

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:
close all;

clear all;

% Read the image

myimage = imread('YOGESHIMG.jpg');

% Convert to grayscale if the image is RGB

if(size(myimage,3) == 3)

myimage = rgb2gray(myimage);

end

% Display the histogram of the original image figure;

subplot(2, 2, 1);

imshow(myimage);

title('Original Image');

subplot(2, 2, 3);

imhist(myimage);

title('Histogram of Original Image');

% Perform histogram equalization

newimage = histeq(myimage);

% Display the histogram equalized image and its histogram subplot(2,

2, 2);

imshow(newimage);
title('Histogram Equalized Image'); subplot(2, 2, 4);

imhist(newimage);

title('Histogram of Equalized Image');

Result:

Conclusion:

We have used histogram Equalization to enhance contrast.

Tutorial:

1.) Take your own photograph in dark area. Improve its appearance using
histogram equalization technique.(Copy and paste your original image,
its histogram, equalized image and its histogram)
EXPERIMENT NO. 5

Aim:To write and execute programs for image arithmetic operations


using MATLAB.

Theory:
Arithmetic operations like image addition, subtraction, multiplication
and division is possible. If there is two images I1 and I2 then addition of
image can be given by:

I(x,y) = I1(x,y) + I2(x,y)

Where I(x,y) is resultant image due to addition of two images. x and y


are coordinates of image. Image addition is pixel to pixel. Value of pixel
should not cross maximum allowed value that is 255 for 8 bit grey scale
image. When it exceeds value 255, it should be clipped to 255.

To increase overall brightness of the image, we can add some constant


value depending on brightness required. In example program we will add
value 50 to the image and compare brightness of original and modified
image.

To decrease brightness of image, we can subtract constant value. In


example program, value 100 is subtracted for every pixel. Care should
be taken that pixel value should not less than 0 (minus value). Subtract
operation can be used to obtain complement (negative) image in which
every pixel is subtracted from maximum value i.e. 255 for 8 bit grey scale
image.

Multiplication operation can be used to mask the image for obtaining


region of interest. Black and white mask (binary image) containing 1s
and 0s is multiplied with image to get resultant image. To obtain binary
image function im2bw() can be used. Multiplication operation can also
be used to increase brightness of the image

Division operation results into floating point numbers. So data type


required is floating point numbers. It can be converted into integer data
type while storing the image. Division can be used to decrease the
brightness of the image. It can also used to detect change in image.

MATLAB CODE:

clc close
all
I1 = imread('YOGESHIMG.jp'); I2 =
imread('Background.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=false(size(I1));
% Set a rectangular region to 1 (true)
M(50:150, 50:150) = true;
%Type casting before multiplication
I=uint8(I1).*uint8(M);
subplot(2, 2, 4); imshow(I);
title('Masked Image I');
Result:
b

Conclusion:

MATLAB program to implement arithmetic operation on images is


executed.

Tutorial:

1.) In above program, use functions imadd() functions to addition,


imsubtract() for subtraction immultiply() for multiplication operations.
Use imcomplement() function to get complement of image.

2.) Write Program to read any image, resize it to 256x256. Apply


square mask shown in following figure so that only middle part of the
image is visible.

256
128
EXPERIMENT NO. 6
Aim:To write and execute programs for image logical operations

Theory: Bitwise logical operations can be performed between pixels of


one or more than one image.
AND/NAND Logical operations can be used for following applications:
Compute intersection of the images
Design of filter masks
Slicing of gray scale images
OR/NOR logical operations can be used for following applications:
Merging of two images
XOR/XNOR operations can be used for following applications:
To detect change in gray level in the image
Check similarity of two images NOT operation is used for:
To obtain negative image
Making some features clear

MATLAB Code:
% Read and convert Image A and B to grayscale
myimageA = imread('YOGESHIMG.jp');
binaryImageA= rgb2gray(myimageA);

myimageB = imread('Background.png');
binaryImageB= rgb2gray(myimageB);

% Convert the grayscale images into binary


(black and white)
% You can adjust the threshold value (0.5)
as per your requirement binaryImageA =
im2bw(myimageA, 0.5);
% Convert Image A to binary binaryImageB
= im2bw(myimageB, 0.5);
% Convert Image B to binary

% Display Image A subplot(3, 2,


1); imshow(binaryImageA);
title('Image A (Binary)');
% Display Image B subplot(3, 2,
2); imshow(binaryImageB);
title('Image B (Binary)');

% Perform complement of Image A


cimageA = ~binaryImageA;

% Display the complement of Image A subplot(3, 2,


3);
imshow(cimageA); title('Complement of
Image A');

% Perform Ex-OR of Image A and Image B


xorimage = xor(binaryImageA,
binaryImageB);

% Display the result of XOR operation subplot(3, 2,


4);
imshow(xorimage); title('Image A
XOR Image B');

% Perform OR of Image A and Image B


orimage = binaryImageA | binaryImageB;

% Display the result of OR operation subplot(3, 2, 5);


imshow(orimage); title('Image A
OR Image B');

% Perform AND of Image A and Image B


andimage = binaryImageA & binaryImageB;

% Display the result of AND operation subplot(3, 2,


6);
imshow(andimage); title('Image A
AND Image B');
Result:

Conclusion:

MATLAB program to implement logical operations is implemented.

Tutorial:

1.) Prepare any two images of size 256x256 in paint. Save it in JPEG
format 256 gray levels. Perform logical NOR, NAND operations
between two images. Write program and paste your results.
EXPERIMENT NO. 7

Aim:To write and execute program for geometric transformation of


image

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:

Scaling: Scaling means enlarging or shrinking. Mathematically scaling


can be represented by:

Rotation: Image can be rotated by an angle θ, in matrix form it


can be represented asIfθ is substituted with -θ, this matrix rotates
the image in clockwise direction.
Shearing: Image can be distorted (sheared) either in x direction
or y direction. Shearing can be represented as:

In matrix form rotation is represented by:

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.

MATLAB Code:
%To rotate given image using standard Matlab function
imrotate() %To transform image using standard Matlab
function imtransform() % using shearing matrix.
x=imread('YOGESHIMG.jpg');

x=rgb2gray(x);

subplot(2,2,1);

imshow(x);

title('Orignial Image');
y=imrotate(x,45,'bilinear','crop');

subplot(2,2,2); imshow(y);

title('Image rotated by 45 degree');


y=imrotate(x,90,'bilinear','crop');

subplot(2,2,3); imshow(y);

title('Image rotated by 90 degree');

y=imrotate(x,-45,'bilinear','crop');

subplot(2,2,4);

imshow(y);

title('Image rotated by -45 degree'); x =

imread('ProfilePhoto.png');

tform = maketform('affine',[1 0 0; .5 1 0; 00
1]);

y = imtransform(x,tform);

figure;

subplot(2,2,1); imshow(x);

title('Orignial Image');

subplot(2,2,2);

imshow(y);
title('Shear in X direction');

tform = maketform('affine',[1 0.5 0; 0 1 0; 0 0


1]);

y = imtransform(x,tform);

subplot(2,2,3); imshow(y);

title('Shear in Y direction');

tform = maketform('affine',[1 0.5 0; 0.5 1 0; 0


0 1]);

y = imtransform(x,tform);

subplot(2,2,4); imshow(y); title('Shear in X-Y direction');


Result:
Conclusion:

Different geometrical transforms are applied successfully

Tutorial:

1.) In above program, modify matrix for geometric transformation and use
imtransform() function for modified matrix. Show the results and your
conclusions.
EXPERIMENT NO. 8
Aim: Write and execute programs for image frequency domain filtering
• Spartial resolution
• Intensity resolution
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.
Spatial resolution refers to the number of pixels in an image and
determines the level of detail captured.
Higher spatial resolution provides more detail, whereas lower spatial
resolution can make the image appear pixelated.

Intensity resolution, on the other hand, refers to the number of distinct


intensity levels available for representing pixel values, often related to the
bit depth.

Higher intensity resolution means more subtle differences in intensity can


be captured.

Frequency domain filtering techniques can be applied to analyze how


resolution affects image detail by manipulating both spatial and intensity
resolutions.

MATLAB Code:

%Program for frequency domain filtering


% Load the image
img = imread('YOGESHIMG.jpg'); % replace with your image file
img_gray = rgb2gray(img); % Convert to grayscale

% Display original image


figure;
imshow(img_gray);
title('Original Image');

% Step 1: Spatial Filtering with Gaussian Filter


h = fspecial('gaussian', [5 5], 2); % Create a Gaussian filter
filtered_img = imfilter(img_gray, h); % Apply the filter

% Display filtered image


Figure
Result:
The MATLAB program has been successfully executed to analyze the impact of spatial
and intensity resolution adjustments on images using frequency domain filtering.

Conclusion:
1. Spatial Resolution: Lowering spatial resolution decreases the level of detail in
the image. This can be observed in both the filtered and unfiltered images, where
lower resolutions result in less clarity.
2. Intensity Resolution: Reducing intensity resolution impacts the contrast and
depth, with lower resolutions appearing posterized. Frequency domain filtering
applied to these images demonstrates the limitations in detail that arise with
lower intensity levels.
Tutorial:
1. Experiment with different cutoff frequencies in the low-pass filter to observe
changes in detail for various resolutions.
2. Analyze how different levels of down-sampling and quantization affect the clarity
and frequency representation of images.
EXPERIMENT NO. 9

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.

Fourier transform of image f(x,y) of size MxN can be given by:

Where, u = 0,1,2 ……. M-1 and v = 0,1,2……N-1

Inverse Fourier transform is given by:

Where, x = 0,1,2 ……. M-1 and y = 0,1,2……N-1

Basic steps for filtering in frequency domain:


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; closeall;

clear all;
% Read the image, resize it to 256 x 256
% Convert it to grey image and display it

myimg=imread('YOGESHIMG.jpg');
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; mybandpa
ssmask(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); title('Low

Pass mask');
subplot(2,1,2);imshow(mybandpassmask); title('Band

Pass mask');

Result:
Conclusion:
MATLAB program for frequency domain filtering is executed.

Tutorial:
1.) Instead of following pre-processing step in above program use
fftshift function to shift FFT in the center. See changes in the result
and write conclusion.

%Preprocessing
of the image for
x=1:M
for y=1:N
myimg1(x,y)=myimg(x,y
)*((-
1)^(x+y)); end
end

Remove above step and use


following commands.
myfftimage = fft2(myimg);
myfftimage=fftshift(myfftimage)
;
EXPERIMENT NO. 10
Aim: Write a program in MATLAB 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:
clear all;
clc;

% Prompt the user to select an image file


filename = 'model.jpg'; % Replace with your image path
data = imread(filename);

if size(data, 3) == 3
data = rgb2gray(data);
end

imshow(data);
figure;

% Edge detection with different masks


BW = edge(data, 'prewitt');
subplot(3, 2, 1); imshow(BW); title('Edge detection with Prewitt mask');
BW = edge(data, 'canny');
subplot(3, 2, 2); imshow(BW); title('Edge detection with Canny mask');
BW = edge(data, 'sobel');
subplot(3, 2, 3); imshow(BW); title('Edge detection with Sobel mask');
BW = edge(data, 'roberts');
subplot(3, 2, 4); imshow(BW); title('Edge detection with Roberts mask');
BW = edge(data, 'log');
subplot(3, 2, 5); imshow(BW); title('Edge detection with LoG');
BW = edge(data, 'zerocross');
subplot(3, 2, 6); imshow(BW); title('Edge detection with Zero-Cross');

MATLAB Code for edge detection using convolution in spatial domain


% Program for point and edge detection masks
while true
K = menu('Choose mask', 'Select Image File', ...
'Point Detect', 'Horizontal Line Detect', ...
'Vertical Line Detect', '+45 Detect', '-45 Detect', ...
'Rectangle Detect', 'Exit');

switch K
case 1
filename = 'path_to_your_image.jpg'; % Replace with your image path
data = imread(filename);
if size(data, 3) == 3
data = rgb2gray(data);
end
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]; % Rectangle mask
case 8
break;
otherwise
msgbox('Select a proper mask');
continue;
end
outimage = conv2(double(data), double(M), 'same');
figure;
imshow(mat2gray(outimage));
title('Filtered Image');
end

close all;
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
clear all;
clc;

% Prompt user to select an image file


[filename, pathname] = uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpeg;*.gif','IMAGE Files
(*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'}, 'Choose Image File');
data = imread(fullfile(pathname, filename));

if size(data, 3) == 3
data = rgb2gray(data);
end

% Display original image


figure;
imshow(data);
title('Original Image');

% Prewitt Edge Detection


prewitt_x = [-1 0 1; -1 0 1; -1 0 1];
prewitt_y = [1 1 1; 0 0 0; -1 -1 -1];

edges_prewitt_x = conv2(double(data), prewitt_x, 'same');


edges_prewitt_y = conv2(double(data), prewitt_y, 'same');
edges_prewitt = sqrt(edges_prewitt_x.^2 + edges_prewitt_y.^2);

subplot(2, 2, 1); imshow(mat2gray(edges_prewitt)); title('Prewitt Edge Detection');

% Sobel Edge Detection


sobel_x = [-1 0 1; -2 0 2; -1 0 1];
sobel_y = [1 2 1; 0 0 0; -1 -2 -1];

edges_sobel_x = conv2(double(data), sobel_x, 'same');


edges_sobel_y = conv2(double(data), sobel_y, 'same');
edges_sobel = sqrt(edges_sobel_x.^2 + edges_sobel_y.^2);

subplot(2, 2, 2); imshow(mat2gray(edges_sobel)); title('Sobel Edge Detection');

% Canny Edge Detection


edges_canny = edge(data, 'canny');
subplot(2, 2, 3); imshow(edges_canny); title('Canny Edge Detection');
% Show all results
sgtitle('Edge Detection Results');

2.) Write a MATLAB code for edge detection of a grayscale image without using
in-built function of edge detection.

clear all;
clc;

[filename, pathname] = uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpeg;*.gif','IMAGE Files


(*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'}, 'Choose Image File');
data = imread(fullfile(pathname, filename));
if size(data, 3) == 3
data = rgb2gray(data);
end

imshow(data);
title('Original Image');

prewitt_x = [-1 0 1; -1 0 1; -1 0 1];


prewitt_y = [1 1 1; 0 0 0; -1 -1 -1];

edges_prewitt_x = conv2(double(data), prewitt_x, 'same');


edges_prewitt_y = conv2(double(data), prewitt_y, 'same');
edges_prewitt = sqrt(edges_prewitt_x.^2 + edges_prewitt_y.^2);
edges_prewitt = mat2gray(edges_prewitt);

sobel_x = [-1 0 1; -2 0 2; -1 0 1];


sobel_y = [1 2 1; 0 0 0; -1 -2 -1];

edges_sobel_x = conv2(double(data), sobel_x, 'same');


edges_sobel_y = conv2(double(data), sobel_y, 'same');
edges_sobel = sqrt(edges_sobel_x.^2 + edges_sobel_y.^2);
edges_sobel = mat2gray(edges_sobel);

figure;
subplot(1, 2, 1); imshow(edges_prewitt); title('Prewitt Edge Detection');
subplot(1, 2, 2); imshow(edges_sobel); title('Sobel Edge Detection');
EXPERIMENT NO. 11

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:
clc;
close all;
clear all;
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];

myimage = imread('model.jpg');
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), 'same');
subplot(3,2,2); imshow(filt_image, []); title('Filtered image with mask L1');

L2 = L2 / sum(L2(:));
filt_image = conv2(double(myimage), double(L2), 'same');
subplot(3,2,3); imshow(filt_image, []); title('Filtered image with mask L2');

L3 = L3 / sum(L3(:));
filt_image = conv2(double(myimage), double(L3), 'same');
subplot(3,2,4); imshow(filt_image, []); title('Filtered image with mask L3');

filt_image = conv2(double(myimage), H1, 'same');


subplot(3,2,5); imshow(filt_image, []); title('Filtered image with mask H1');

filt_image = conv2(double(myimage), H2, 'same');


subplot(3,2,6); imshow(filt_image, []); title('Filtered image with mask H2');

figure;
subplot(2,2,1); imshow(myimage); title('Original Image');
gaussmask = fspecial('gaussian', 3);
filtimg = imfilter(myimage, gaussmask);
subplot(2,2,2); imshow(filtimg, []), title('Output of Gaussian filter 3 X 3');

avgfilt = ones(7) / 49;


convimage = conv2(double(myimage), double(avgfilt), 'same');
subplot(2,2,3); imshow(convimage, []); title('Average filter with conv2()');

filt_image = conv2(double(myimage), H3, 'same');


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.

Mathematical Expression of Spatial Filtering

For an image f(x,y) of size M×N and a mask W of size a×b, the output image g(x,y)
after applying spatial filtering can be expressed mathematically as:

Where:
g(x,y) is the output pixel value at position (x,y).
W(i,j) is the weight of the mask at position (i,j).

The summation iterates over the mask dimensions, centering it at each pixel
(x,y)(x, y)(x,y) of the input image.

2.) What is need for padding? What is zero padding? Why it is required?

Need for Padding


Why Padding is Needed:
Boundary Effects: When applying a mask (filter) to an image, the mask needs
neighboring pixel values to compute the output for edge pixels. Without padding,
the output would be smaller than the input image, and edge pixels would not be
processed correctly, leading to artifacts.
Output Size Control: Padding helps maintain the output size, ensuring it matches
the input image dimensions.

Zero Padding:
Zero padding is a technique where the borders of the image are extended by adding
a layer of zeros around the original image. For example, if we have an image of size
M×NM \times NM×N and we apply zero padding, the new image size will be
(M+2p)×(N+2q)(M + 2p) where p and q are the number of rows and columns of zeros
added.

Why Zero Padding is Required:


It allows the filter to be applied uniformly across the entire image, including the
edges and corners, without reducing the size of the output image.

It helps in avoiding the loss of information at the boundaries, ensuring that all
pixels can be processed.

3.) What is the effect of increasing size of mask?


Effect of Increasing Size of Mask
Smoothing Effect: Increasing the size of the mask (filter) generally results in a
stronger smoothing effect on the image. Larger masks tend to average out more
pixel values, reducing noise but also blurring important details.

Computational Load: A larger mask increases the number of computations


required for filtering, leading to higher processing times.

Artifact Introduction: Larger masks can introduce artifacts or distortions,


especially if the mask is not designed appropriately for the specific features of the
image.

Loss of Edge Definition: With larger masks, the definition of edges may be lost, as
more pixels are averaged together. This can be detrimental in applications where
edge detection is crucial.

You might also like