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

IMAGE PROCESSING

2014

INDEX
Sr.
No

Topic

1.

Image Enhancement in Spatial


Domain.

2.

Image Enhancement in Frequency


Domain.

3.

Image Enhancement using


Statistical Filters.

4.

Wavelet Analysis.

5.

Error Free Image Compression.

6.

Lossy Image Compression.

7.

Morphological Algorithms.

8.

Edge Detection.

9.

Image Segmentation.

10.

Region Filling.

11.

Morphological Operations.

12.

Logical Operations.

13.

Sampling and Quantization

14.

Histogram of Granular Image

15.

Thresh holding Algorithms

Date

Page-No

Signature

IMAGE PROCESSING

2014

Practical No: 1
Topic: - Image Enhancement in Spatial Domain.
Problem Statement: Apply following image enhancement algorithms to the given input image. Display
the resulting image.
1. Contrast stretching: - Display dark, bright, low-contrast and high contrast
images by applying contrast stretching on an input image by manipulating the
mapped gray-levels in an input image.
2. Histogram Equalization: -Apply the histogram equalization technique on an
input image.
3. Image averaging: - Implement image averaging technique to remove the noise
from an image by using an averaging filter.
4. Smoothing: -Apply the smoothing effect to an input image by using appropriate
filter masks.
Used Functions Details: -

1) Function Name: imread


Prototype: A = IMREAD(FILENAME,FMT)
Description: It reads a grayscale or truecolor image named filename into A.
Parameters:
o
FILENAME: Name of the image file to be read.
o FMT: Format of the input file.
2)

Function Name: iptsetpref

Prototype: IPTSETPREF(PREFNAME,VALUE)

Description: Sets the Image Processing Toolbox


preference specified by the string PREFNAME to VALUE. The setting persists
until the end of the current MATLAB session or until you change the setting.

Parameters:
o PREFNAME: Specified Preference.
o VALUE: Preference Value

3)

Function Name: imshow


Prototype: IMSHOW(I)
Description: It displays the grayscale image I.
Parameters:
I: Image to be displayed.

4) Function Name: imadjust

Prototype: J = IMADJUST(I,[low_in; high_in],[low_out;


high_out])

Description: It maps the values in I to new values in J


such that values between low_in and high_in map to values between low_out
and high_out. Values below low_in and above high_in are clipped; that is,
values below low_in map to low_out, and those above high_in map to
high_out. You can use an empty matrix ([]) for [low_in high_in] or for [low_out
high_out] to specify the default of [0 1].

Parameters:
o
I: Input Image.
2

IMAGE PROCESSING
o
o

2014

[low_in; high_in]: Intensity values.


[low_out; high_out]: Intensity values.

5) Function Name: imhist


Prototype: IMHIST(I)
Description: It displays histogram of image data.
Parameters:
o
I: Input Image
6) Function Name: histeq
Prototype: HISTEQ(I)
Description: It enhances image contrast using histogram equalization.
Parameters:
o
I: Input Image
7) Function Name: imnoise
Prototype: J = IMNOISE(I,TYPE,...)
Description: Add noise of a given TYPE to the intensity image
I. TYPE is a string that can have one of these values:
'gaussian' - Gaussian white

noise with constant mean and variance

'localvar' - Zero-mean Gaussian


white noise with an intensity- dependent variance.

poisson' - Poisson noise

'salt & pepper' - "On and Off"


pixels

'speckle'
Multiplicative
noise
Parameters:
o
I: Input Image
o
TYPE: Noise type.

8) Function Name: imsubtract


Prototype: Z = IMSUBTRACT(X,Y)
Description: It subtracts each element in array Y from the corresponding
element in array X and returns the difference in the corresponding element of
the output array Z.
Parameters:
o
X: Image
9) Function Name: imsubtract
Prototype: Z = IMSUBTRACT(X,Y)
Description: It subtracts each element in array Y from the corresponding
element in array X and returns the difference in the corresponding element of
the output array Z.
Parameters:
o
X, Y: Images for suntraction
10)
Function Name: fspecial
Prototype: H = FSPECIAL(TYPE)
Description: creates a two-dimensional filter H of the specified type.
Possible values for TYPE are:
3

IMAGE PROCESSING

2014

'average' - Averaging filter


'disk' - Circular averaging filter
'gaussian' - Gaussian lowpass filter
'laplacian' - Filter approximating the 2-D Laplacian operator
'log' - Laplacian of Gaussian filter
'motion' - Motion filter
'prewitt' - Prewitt horizontal edge-emphasizing filter
'sobel' - Sobel horizontal edge-emphasizing filter
'unsharp' - Unsharp contrast enhancement filter
Parameters:
o
TYPE: Type of the filter.
11) Function Name: medfilt2
Prototype: B = MEDFILT2(A)

Description: It filters performs median


filtering of the matrix A i.e. image in this context using the default 3-by-3
neighborhood.
Parameters:
o A: Image
12) Function Name: filter2
Prototype: Y = FILTER2(B,X)

Description: It filters the data in X with the


2-D FIR filter in the matrix B. The result, Y, is computed using 2-D
correlation and is the same size as X.
Parameters:
o B: Filter
o X: Image
13) Function Name: fir1
Prototype: B = FIR1(N,Wn)

Description: It designs an N'th order


lowpass FIR digital filter.
Parameters:
o N: Order of the filter.
o Wn: The cut-off frequency Wn must be between 0 < Wn < 1.0, with
1.0.
14) Function Name: imfilter
Prototype: B = IMFILTER(A,H)

Description: It filters the multidimensional


array A in this case its an image with the multidimensional filter H.
Parameters:
o A: Image
o H: Filter.

IMAGE PROCESSING

2014

Source Code: 1. Contrast Stretching


clc; clear all; close all;
% Images files can be found in directory: ..\Matlab\toolbox\images\imdemos
iptImg = imread('kids.tif'); %Reads the image file to iptImg%
figure;
subplot(3,2,1); imshow(iptImg); title('Original Image');
subplot(3,2,2); imhist(iptImg); title('Original Image Histogram');
% Displaying Dark Image
%------------------------------------------darkImg = imadjust(iptImg,[0 1],[0.1 0.4]);
subplot(3,2,3); imshow(darkImg); title('Dark Image');
subplot(3,2,4) ; imhist(darkImg); title('Dark Image Histogram');
% Displaying Bright Images
%------------------------------------------brightImg = imadjust(iptImg,[0 1],[0.5 1]);
subplot(3,2,5); imshow(brightImg); title('Bright Image');
subplot(3,2,6); imhist(brightImg);title('Bright Image Histogram');
figure;
subplot(3,2,1); imshow(iptImg); title('Original Image');
subplot(3,2,2); imhist(iptImg); title('Original Image Histogram');
% Disaplying Low contrast Images
%------------------------------------------lowContrastImg = imadjust(iptImg,[0,1],[0.4 0.6]);
subplot(3,2,3); imshow(lowContrastImg); title('Low Contrast Image');
subplot(3,2,4) ; imhist(lowContrastImg); title('Low Contrast Image Histogram');
% Disaplying High contrast Images
%------------------------------------------highContrastImg = imadjust(iptImg,[0,1],[0.1 0.9]);
subplot(3,2,5); imshow(highContrastImg); title('High Contrast Image');

IMAGE PROCESSING

2014

subplot(3,2,6) ; imhist(highContrastImg); title('High Contrast Image


Histogram');Output:

Figure 1: Dark & Bright Images and their Histograms

Figure 2: Low & High Contrast Images and their Histograms

IMAGE PROCESSING

2014

Source Code: 2. Histogram Equalization.


clc; clear all; close all;
figure;
% Images files can be found in directory: ..\Matlab\toolbox\images\imdemos
iptImg = imread('pout.tif'); %Reads the image file to iptImg%
subplot(2,2,1); imshow(iptImg); title('Original Image');
subplot(2,2,2); imhist(iptImg); title('Original Image Histogram');
% Histogram Equalization
%------------------------------------------imgHistEq = histeq(iptImg);
subplot(2,2,3);
imshow(imgHistEq);
title('Image after Histogram Equalization');
subplot(2,2,4);
imhist(imgHistEq);
title('Histogram of Image after Histogram Equalization');

Output: -

IMAGE PROCESSING

2014

Source Code: 3. Image Averaging


clc; clear all; close all; figure;
% Images files can be found in directory: ..\Matlab\toolbox\images\imdemos
iptImg = imread('cameraman.tif'); %Reads the image file to iptImg%
subplot(2,2,1); imshow(iptImg); title('Original Image');
subplot(2,2,2); imhist(iptImg); title('Original Image Histogram');
% Average Filter
%------------------------------------------%Add noise to the image
noisyImg = imnoise(iptImg,'salt & pepper', 0.02);
subplot(2,2,2); imshow(noisyImg); title('Noisy Image');
%Subtract Image
subImage = imsubtract(iptImg, noisyImg);
subplot(2,2,3); imshow(subImage); title('Subtracted Image');
%Create an average filter
matSize = [3 3];
avgFilter = fspecial('average',matSize); % creating 2D Average filter
filteredImg = filter2(avgFilter, noisyImg)/300;
subplot(2,2,4); imshow(filteredImg); title('Noise removal using an Average
Filter');

Output: -

IMAGE PROCESSING

2014

Source Code: 4. Image Smoothing


clc; clear all; close all; figure;
iptImg = imread('trees.tif'); %Reads the image file to iptImg%
subplot(2,2,1); imshow(iptImg); title('Original Image');
subplot(2,2,2); imhist(iptImg); title('Original Image Histogram');
% Adding Gaussian Noise
%------------------------------------------noisyImg = imnoise(iptImg,'gaussian', 0.0001,0.01);
% It adds Gaussian white noise of mean M and variance V to the image I.
% When unspecified, M and V default to 0 and 0.01 respectively.
subplot(2,2,2); imshow(noisyImg); title('Noisy Image');
%Subtract Image
subImage = imsubtract(iptImg, noisyImg);
subplot(2,2,3); imshow(subImage); title('Subtracted Image');
%Applying Smoothning Mask:
N = 10;
% The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0
Wn = 0.5;
% Designs an N'th order lowpass FIR digital filter
mask = fir1(N, Wn);
imgSmooth = imfilter(noisyImg, mask);
subplot(2,2,4); imshow(imgSmooth); title('After applying Smoothening Filter');

Output: -

IMAGE PROCESSING

2014

Practical No: 2
Topic: - Image Enhancement in Frequency Domain.
Problem Statement: A filter function from one of the following filters along with a set of values
for the parameter list is provided. For this filter function derive the an (k x k)
filter mask for one of the values of k, k = 3,5,9. The filter mask is to be applied
to the given input image and the enhanced image is to be displayed.
1. Gaussian Low Pass Filter
2. Butterworth Low Pass Filter
3. Ideal High Pass Filter
4. Ideal Low Pass Filter
Used Functions Details:

1)
Function Name: butter
Prototype: [B,A] = BUTTER(N,Wn)
Description: It designs an Nth order lowpass digital Butterworth filter and
returns the filter coefficients in length N+1 vectors B (numerator) and A
(denominator).
Parameters:
o
N: Order of the filter
o
Wn: The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0.
Function Name: fir1
Prototype: B = FIR1(N,Wn,X)
Description: It designs an N'th order X pass FIR digital filter.
Parameters:
o N: Order of the filter.
o Wn: The cut-off frequency Wn must be between 0 < Wn < 1.0, with
1.0.
o X: The value can be high or low to design highpass or lowpass filter
respectively.

10

IMAGE PROCESSING

2014

Source Code: 1. Gaussian Low Pass Filter.


clc; clear all; close all; figure;
iptImg = imread('moon.tif'); %Reads the image file to iptImg%
subplot(2,2,1); imshow(iptImg); title('Original Image');
subplot(2,2,2); imhist(iptImg); title('Original Image Histogram');
%Gaussian Low Pass Filter Application
%--------------------------------------HSIZE=[6 6];
SIGMA=5; % SIGMA <> 0
% This returns a rotationally symmetric Gaussian lowpass filter
% of size HSIZE with standard deviation SIGMA (positive).
gFilter = fspecial('gaussian',HSIZE,SIGMA);
filtImg = imfilter(iptImg,gFilter);
subplot(2,2,3);
imshow(filtImg);
title('Image After Applying Gaussian LPF');
subplot(2,2,4);
imhist(filtImg);
title('Histogram of Modified Image');

Output: -

11

IMAGE PROCESSING

2014

Source Code: 2. Butterworth Low Pass Filter.


%Butterworth Low Pass Filter Application
%--------------------------------------N=2; % Order of the filter
Wn = 0.6; % The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0
H = butter(N, Wn, 'low');
filtImg = imfilter(iptImg,H);
subplot(2,2,3);
imshow(filtImg);
title('Image After Applying Butterworth LPF');
subplot(2,2,4);
imhist(filtImg);
title('Histogram of Modified Image');

Output: -

12

IMAGE PROCESSING

2014

Source Code: 3. Ideal High Pass Filter.


%Ideal High Pass Filter Application
%--------------------------------------N=6; % Order of the filter
% Choose an even value for the order of the filter otherwise it generates a
warning message.
Wn = 0.3; % The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0.
H = fir1(N, Wn, 'high');
filtImg = imfilter(iptImg,H);
subplot(2,2,3);
imshow(filtImg);
title('Image After Applying Ideal HPF');
subplot(2,2,4);
imhist(filtImg);
title('Histogram of Modified Image');

Output: -

13

IMAGE PROCESSING

2014

Source Code: 4. Ideal Low Pass Filter.


%Ideal Low Pass Filter Application
%--------------------------------------N=28; % Order of the filter
Wn = 0.02; % The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0
H = fir1(N, Wn, 'low');
filtImg = imfilter(iptImg,H);
subplot(2,2,3);
imshow(filtImg);
title('Image After Applying Ideal LPF'); % LPF: Low Pass Filter
subplot(2,2,4);
imhist(filtImg);
title('Histogram of Modified Image');

Output: -

14

IMAGE PROCESSING

2014

Practical No: 3
Topic: - Image Enhancement using Statistical Filters.
Problem Statement: The Statistical Filter specifications are provided. This filter should be
applied to the input image and the resulting image should be displayed
1. Mean and Median Filters
2. Max-min and Min-max Filters

Used Functions Details: 1)

Function Name: mean2


Prototype: B = MEAN2(A)
Description: It computes the mean of the values in A.
Parameters:
o
A: Input matrix (image).
2) Function Name: imabsdiff
Prototype: Z = IMABSDIFF(X,Y)
Description: It computes absolute difference of two images. It subtracts
each element in array Y from the corresponding element in array X and
returns the absolute difference in the corresponding element of the output
array Z.
Parameters:
o
X: Input matrix (image1).
o
Y: Input Matrix (image2).

15

IMAGE PROCESSING

2014

Source Code: 1. Mean Filter.


clc; clear all; close all; figure;
iptImg = imread('cameraman.tif'); %Reads the image file to iptImg%
subplot(3,2,1), imshow(iptImg), title('Original Image');
[row col]= size(iptImg);
noise_image = imnoise(iptImg,'gaussian',0.02);
subplot(3,2,2),imshow(noise_image),title('Gaussian Noise Image');
noise_image= double(noise_image);
% Mean Filter
%-----------------------% Calculating Mean of Image Elements and using it as a filter
w = [1 1 1;1 1 1;1 1 1]/9;
for i = 2:1:row-1
for j=2:1:col-1
a1(i,j)= w(1)*noise_image(i-1,j-1) + w(2)*noise_image(i-1,j) +
w(3)*noise_image(i-1,j+1) + w(4)*noise_image(i,j-1) + w(5)*noise_image(i,j) +
w(6)*noise_image(i,j+1) + w(7)*noise_image(i+1,j-1) + w(8)*noise_image(i+1,j) +
w(9)*noise_image(i+1,j+1);
end
end
subplot(3,2,3), imshow(uint8(a1)), title('Mean Filter Image');

Output: -

16

IMAGE PROCESSING

2014

Source Code: 2. Median Filter.


clc, clear all;
close all;
figure;
% Median Filter
%-----------------------iptImg = imread('cameraman.tif'); %Reads the image file to iptImg%
%Add Noise
noise_image = imnoise(iptImg,'salt & pepper',0.02);
median_filter_out = medfilt2(noise_image,[3 3]);
subplot(2,2,1),imshow(iptImg), title('Original Image');
subplot(2,2,2),imshow(noise_image), title('Salt & pepper Noise Image');
subplot(2,2,3),imshow(median_filter_out), title('Median Filter Output');

Output: -

17

IMAGE PROCESSING

2014

Source Code: 3. Minimax Filter.


clc; clear all; close all; figure;
iptImg = imread('cameraman.tif'); %Reads the image file to iptImg%
subplot(3,2,1), imshow(iptImg), title('Original Image');
[r ,c]=size(iptImg);
noise_image = imnoise(iptImg,'salt & pepper',0.02);
subplot(2,2,2); imshow(noise_image); title('Salt and Pepper Noise Image');
for n =1:1:r
for m = 1:1:c
if noise_image(n,m)==0
noise_image(n,m)=255;
end
end
end
subplot(2,2,3); imshow(uint8(noise_image)); title('Max Filter Output');
for n =1:1:r
for m = 1:1:c
if noise_image(n,m)==255
noise_image(n,m)=0;
end
end
end
subplot(2,2,4); imshow(uint8(noise_image)); title('Min Filter Output');

Output: -

18

IMAGE PROCESSING

2014

Practical No: 4
Topic: - Wavelet Analysis.
Problem Statement: A one dimensional function is input. This can be extracted from scan line
information of an image. A wavelet basis for one dimensional function should be
encoded. The function is displayed at different resolution levels, j = 4, 8, 16, 32.
(Wavelet Toolbox)
Used Functions Details: 1)

Function Name: load


Prototype: LOAD FILENAME
Description: It retrieves all variables from a file given a full pathname or a
MATLABPATH relative partial pathname (see PARTIALPATH). If FILENAME has
no extension LOAD looks for FILENAME and FILENAME.mat and treats it as a
binary "MAT-file". If FILENAME has an extension other than .mat, it is treated
as ASCII.
Parameters:
o FILENAME: Name of the file to be loaded.
Function Name: plot
Prototype: PLOT(X)
Description: It plots the columns of Y versus their index.
Parameters:
o X: Vector to be plotted.
Function Name: wavedec
Prototype: [C,L] = WAVEDEC(X,N,'wname')
Description: It returns the wavelet decomposition of the signal X at
level N, using 'wname'.
Parameters:
o X: Signal.
o N: Order. It must be a strictly positive integer.
o wname: Specific wavelet name.

19

IMAGE PROCESSING

2014

Source Code: clc;


clear all;
close all;
% Load inbuilt 1D Sinusoidal wave
load sumsin;
% figure('property name', 'property value',.....);
% Creates a new figure object and assigns a name(title to it)
figure('Name','Input 1D Sinusoidal Wave');
plot(sumsin);
% bior: BiOrthogonal Wavelet Filter
% Function at Resolution level: 4
figure;
[C,L] = wavedec(sumsin,4,'bior1.1');
subplot(2,2,1);
plot(C);
title('Function at Resolution Level 4');
% Function at Resolution level: 8
[C,L] = wavedec(sumsin,8,'bior1.1');
subplot(2,2,2);
plot(C);
title('Function at Resolution Level 8');
% Function at Resolution level: 16
[C,L] = wavedec(sumsin,16,'bior1.1');
subplot(2,2,3);
plot(C);
title('Function at Resolution Level 16');
% Function at Resolution level: 32
[C,L] = wavedec(sumsin,32,'bior1.1');
subplot(2,2,4);
plot(C);
title('Function at Resolution Level 32');

20

IMAGE PROCESSING

2014

Output: -

21

IMAGE PROCESSING

2014

Practical No:
5
Topic: - Error Free Image Compression.
Problem Statement: An input image is provided. Any one of the following Error Free Image
Compression algorithm is provided. The algorithm is to be applied the input
image and percentage reduction along with the compressed image is to be
displayed. This image is now to be decompressed and the original image must
be displayed.
1. Variable length coding
2. Huffman coding
3. Lempel-Ziv-Welch (LZW) Coding

Used Functions Details: 1) Function Name: isa


Prototype: ISA(OBJ,'class_name')
Description: It returns 1 if OBJ is of the class, or inherits from the class,
'class_name' and 0 otherwise.
Parameters:
o OBJ: Input Object.
o Class: Class Name.

Some possibilities for 'class_name' are:


double: Double precision floating point numeric array
(this is the traditional MATLAB matrix or array)
logical: Logical array
char: Character array
cell: Cell array
struct: Structure array
22

IMAGE PROCESSING

2014

function_handle: Function Handle


numeric: Integer or floating-point array
single: Single precision floating-point numeric array
int8: 8-bit signed integer array
uint8: 8-bit unsigned integer array
int16: 16-bit signed integer array
uint16: 16-bit unsigned integer array
int32: 32-bit signed integer array
uint32: 32-bit unsigned integer array
<class_name>: Custom MATLAB object class or Java class
2) Function Name: svds
Prototype: S = SVDS(A,K)
Description: It computes the K largest singular values of A.
Parameters:
o A Input Matrix
o K Singular Value.

23

IMAGE PROCESSING

2014

3) Function Name: imwrite


Prototype: IMWRITE(A,FILENAME,FMT)
Description: writes the image A to FILENAME. FILENAME is a string that
specifies the name of the output file, and FMT is a string that specifies the
format of the file. A can be either a grayscale image (M-by-N) or a truecolor
image (M-by-N-by-3).
Parameters:
o A: Input image matrix
o Filename: Name of the output file.
o FMT: Format of the output image. E.g. JPEG, BMP, TIFF.

Source Code: clc; clear all; close all;


figure;
inputImg = imread('football.jpg');
subplot(1,2,1); imshow(inputImg); title('Input Image');
singularVals=10;
% Checking whether input image is of the class 'uint8'
if isa(inputImg(:,:,1),'uint8')
% Computing all x & y RGB-values in vectors Red, Green and Blue.
red = double(inputImg(:,:,1));
green = double(inputImg(:,:,2));
blue = double(inputImg(:,:,3));
% computing 10 largest singular values in vector red
[U S V] = svds(red, singularVals);
% Computing closest rank 10 approximation to red
imred = uint8(U*S*transpose(V));
% computing 10 largest singular values in vector green
[U S V] = svds(green, singularVals);
% Computing closest rank 10 approximation to green
imgreen = uint8(U*S*transpose(V));
% computing 10 largest singular values in vector blue
[U S V] = svds(blue, singularVals);
% Computing closest rank 10 approximation to blue
imblue = uint8(U*S*transpose(V));
% Generating Compressed 3D Image
compressedImg(:,:,1) = imred;
compressedImg(:,:,2) = imgreen;
compressedImg(:,:,3) = imblue;
subplot(1,2,2); imshow(compressedImg); title('Compressed Image');

end

% Saving both the image files


imwrite(inputImg, 'InputImg.jpg','JPG');
imwrite(compressedImg, 'CompressedImg.jpg', 'JPG');

24

IMAGE PROCESSING

2014

Output: -

25

IMAGE PROCESSING

2014

Practical No:
6
Topic: - Lossy Image Compression.
Problem Statement: An input image is provided. A Lossy Image Compression algorithm is
provided. The algorithm is to be applied the input image and percentage
reduction along with the compressed image is to be displayed. The nature of
information lost is to be explained. This image is now to be decompressed and
the original image must be displayed
Used Functions Details:

1)
Function Name: im2double
Prototype: I2 = IM2DOUBLE(I1)
Description: It takes an image as input, and returns an image of class
double. If the input image is of class double, the output image is identical to
it.
Parameters:
o
I1: Input Image.
2)
Function Name: blkproc
Prototype: B = BLKPROC(A,[M N],FUN,P1,P2,...)
Description: It processes the image A by applying the function FUN to each distinct
M-by-N block of A, padding A with zeros if necessary. FUN is a function that accepts an
M-by-N matrix, X, and returns a matrix, vector, or scalar Y: FUN(X).
Parameters:
o
A: Input image matrix
o
[M N]: Matrix block size for processing.
26

IMAGE PROCESSING

2014

FUN: A function for processing.


P1, P2: Parameters for FUN function.

o
o

Source Code: clc; clear all; close all;


figure;
iptImg = imread('rice.PNG');
iptImg = im2double(iptImg); % Converts image to double precision.
T = dctmtx(8); % Computes N*N discrete cosine transform matrix.
% Distinct blocks processing for image. It applies P*x*P2 to each distinct 8-by-8
block of A.
B = blkproc(iptImg,[8 8],'P1*x*P2',T,T');
% 8*8 Mask
mask = [1 1
1 1
1 1
1 0
0 0
0 0
0 0
0 0

1
1
0
0
0
0
0
0

1
0
0
0
0
0
0
0

0
0
0
0
0
0
0
0

0
0
0
0
0
0
0
0

0
0
0
0
0
0
0
0

0
0
0
0
0
0
0
0 ];

% to agree matrix dimension we are writing P1*x as P1.*x


B1 = blkproc(B,[8 8],'P1.*x',mask);
finalImg = blkproc(B1,[8 8], 'P1*x*P2', T', T);
subplot(1,2,1); imshow(iptImg); title('Input Image');
subplot(1,2,2); imshow(finalImg); title('Output Image');
% Saving Input and Output Image files %
imwrite(iptImg,'Input.jpg','JPEG');
imwrite(finalImg,'Output.jpg','JPEG');

27

IMAGE PROCESSING

2014

Output: -

Practical No: 7
Topic: - Morphological Algorithms.
Problem Statement: A texture image or a granular image is provided as input. A suitable
algorithm that computes pattern size or granule size in terms of number of pixel
it occupies is to be implemented. This information is to display as a histogram.
Used Functions Details: -

Function Name: imopen


Prototype: IM2 = IMOPEN(IM,SE)
Description: It performs morphological opening on the grayscale or binary
image IM with the structuring element SE.
Parameters:
o M: Input Image.
o SE: Structuring Element

Function Name: regionprops


Prototype: TATS = REGIONPROPS(L)
Description: It displays information about image pixels.
Parameters:
o L: Labeled Matrix

Function Name: pixval


Prototype: PIXVAL(val)
Description: It measures properties of image regions.
Parameters:
val: This can be ON or OFF to toggle interactive display

28

IMAGE PROCESSING

Function Name: mean


Prototype: MEAN(X)
Description: It calculates the mean value of the elements in X.
Parameters:
X: Input vector

Function Name: std


Prototype: STD(X)
Description: It calculates standard deviation for vector X
Parameters:
X: Input vector

2014

Function Name: median


Prototype: MEDIAN(X)
Description: It calculates the median value of the elements in X.
Parameters:
o X: Input vector

Source Code: clc; clear all; close all;


figure;
iptImg = imread('trees.tif');
subplot(2,3,1); imshow(iptImg); title('Original Image');
subplot(2,3,2); imshow(iptImg); colormap(Jet); % Sets the current figures map to
JET
title('Jet Colormap Image');
% Background Estimation
% imopen performs morphological opening on the grayscale or binary image
% strel is used to creat disk shaped structuring element of radius 10
bkgrndImg = imopen(iptImg,strel('disk',10));
subplot(2,3,3); imshow(bkgrndImg); colormap(Jet); title('Background Estimation');
% Background Removal
subImg = imsubtract(iptImg,bkgrndImg);
subplot(2,3,4); imshow(subImg); title('Flattened Backgroung Removal');
% Segment Grains from the background, obtains the binary Image
% graythresh computes Global Image Threshold
subplot(2,3,5);
binaryImg = im2bw(subImg,graythresh(subImg));
imshow(binaryImg);
title('Thrsholded Image');
% Label Connected Region
[L NUM] = bwlabel(binaryImg);
subplot(2,3,6);
imshow(L,[]);
colormap(jet);
pixval('on'); % Display information about image pixels.

29

IMAGE PROCESSING

2014

title('Connected Region');
% Feature Extraction
% Measures a set of properties for each labeled region in the label matrix L.
stats = regionprops(L);
A = [stats.Area];
figure;
hist(A);
xlabel('Area in Pixels');
ylabel('Popularity');
title('Size Distribution');
% Statistical Measurement
mean(A);
std(A);
median(A);

30

IMAGE PROCESSING

2014

Output: -

31

IMAGE PROCESSING

2014

Practical No: 8
Topic: - Edge Detection.
Problem Statement: A texture image or a granular image is provided as input. A suitable edge
detection algorithm is implemented which determines the number of patterns or
granule in the input image. If there are patterns/granules of different
characteristics (like color) then their number is determined and the information
is to be displayed as a histogram.
Used Functions Details:

1) Function Name: stretchlim


Prototype: LOW_HIGH = STRETCHLIM(I)
Description: It finds limits to contrast stretch an image.
Parameters:
o
I: Input Image.

2) Function Name: graythresh


Prototype: LEVEL = GRAYTHRESH(I)
Description: It computes global image threshold.
Parameters:
o
I: Input Image.

3) Function Name: label2rgb


Prototype: RGB = LABEL2RGB(L, MAP, ZEROCOLOR, ORDER)
Description: It converts labeld matrix to RGB image.
Parameters:
o L: Labeled Matrix.
o MAP: Color map to be used. a string containing the name of a colormap
function (such as 'jet' or 'gray'), or a function handle of a colormap
function (such as @jet or @gray). LABEL2RGB evaluates MAP so that
there is a different color for each region in L.
o ZEROCOLOR: It defines the RGB color of the elements labeled 0 in the
input label matrix L. ZEROCOLOR can either be an RGB triple, or one of
the following: 'y' (yellow), 'm', (magenta), 'c' (cyan), 'r'(red), 'g' (green),
'b' (blue), 'w' (white), or 'k' (black). If ZEROCOLOR is not specified, [1 1 1]
is used as the default.
o ORDER: It controls how colormap colors are assigned to regions in the
label matrix. Nonshuffle is default.
4) Function Name: regionprops
Prototype: TATS = REGIONPROPS(L,PROPERTIES)
Description: It measures properties of image regions.
Parameters:
o
L: Labeled Matrix.
o PROPERTIES: PROPERTIES can be a comma-separated list of strings, a cell
array containing strings, the string 'all', or the string 'basic'.
The set of valid measurement strings includes:
'Area'
'ConvexHull'
'EulerNumber'
'Centroid'
'ConvexImage' 'Extrema'
32

IMAGE PROCESSING

2014

'BoundingBox'
'ConvexArea'
'EquivDiameter'
'SubarrayIdx'
'Image'
'Solidity'
'MajorAxisLength' 'PixelList'
'Extent'
'MinorAxisLength' 'PixelIdxList'
'FilledImage'
'Orientation'
'FilledArea'
'Eccentricity'

Source Code: clc; clear all; close all;


figure;
iptImg = imread('rice.PNG');
subplot(3,2,1); imshow(iptImg); title('Original Input Image');
% Creating a morphological structring element
% strel->Create morphological structuring element.
backgroundImg = imopen(iptImg,strel('disk',15));
subplot(3,2,2); imshow(backgroundImg); title('Background Image');
% Subtracted Image
subImg = imsubtract(iptImg,backgroundImg);
subplot(3,2,3); imshow(subImg); title('Subtracted Image');
% Adjusting the image intensity values
% stretchlim->Find limits to contrast stretch an image.
satImg = imadjust(subImg,stretchlim(subImg),[0 1]);
subplot(3,2,4); imshow(subImg); title('Saturated Image');
% GRAYTHRESH -> Compute global image threshold
% IM2BW ->Convert to binary image by thresholding.
level = graythresh(satImg);
BW = im2bw(satImg,level);
subplot(3,2,5); imshow(BW); title('Threshold Binary Image');
% Label connected components in binary image.
[labeled,numObjects] = bwlabel(BW);
% Converting labelled matrix to RGB Image
% @ is used to specify a function handle of colormap function
rgbImg = label2rgb(labeled,@spring,'c','shuffle');
subplot(3,2,6); imshow(rgbImg); title('RGB Image');
% Measure properties of Image Region
figure;
graindata = regionprops(labeled,'basic');
% REGIONPROPS --> Measure properties of image regions.
allgrains = [graindata.Area];
hist(allgrains,numObjects);
xlabel('Area');
ylabel('Popularity');
title('Grain Distribution');

33

IMAGE PROCESSING

2014

Output: -

34

IMAGE PROCESSING

2014

Practical No: 9
Topic: - Image Segmentation.
Problem Statement: Write a program to input an image and perform image segmentation to
extract individual objects from that image.
Used Functions Details:

1) Function Name: edge


Prototype: O = EDGE(I,method)
Description: It finds edges in intensity image.
Parameters:
o
I: Input Image.
o
Method: Edge Detection method
2) Function Name: find
Prototype: I = FIND(X)
Description: It finds indices of nonzero elements. It returns the indices of the vector X
that are non-zero.
Parameters:
o X: Input Vector.

Source Code: clc; clear all; close all;


iptImg = imread('football.JPG');
subplot(3,2,1); imshow(iptImg); title('Original Image');
% Converting RGB Image to Gray scale
grayImg = rgb2gray(iptImg);
subplot(3,2,2); imshow(grayImg); title('Grayscale Image');
% Noise removal
filteredImg = medfilt2(grayImg, [3 3]);
subplot(3,2,3); imshow(filteredImg); title('Filtered Image');
% Edge Detection
edgedImg = edge(filteredImg,'canny');
subplot(3,2,4); imshow(edgedImg); title('Edge Detection');
[imgX, imgY] = size(edgedImg);
mask = [0 0 0 0 0;
0 1 1 1 0;
0 1 1 1 0;
0 1 1 1 0;
0 0 0 0 0];
% 2D Convolution
convImg = conv2(double(edgedImg), double(mask));
subplot(3,2,5); imshow(convImg); title('Smoothened Image');
% Calcualating connecting components by 8 connected Region
[L NUM] = bwlabel(convImg,8);
maxL = max(max(L));

35

IMAGE PROCESSING

2014

%Find Indices of zero elements


%[i,j] = find(L == 13);
[i,j] = find(L == 2);
% obtain iamge co-ordinates of Image Object at L=20
coords = [i j];
[sX sY] = size([i j]);
arr = zeros(imgX, imgY);
for i=1:sX
x = coords(i,1);
y = coords(i,2);
arr(x,y) = 255;
end
subplot(3,2,6); imshow(arr,[]); title('Extracted Image');

Output: -

36

IMAGE PROCESSING

2014

Practical No: 10
Topic: - Region Filling.
Problem Statement: Write a program to input an image and fill the empty region inside the
image using Region Filling procedure.
Used Functions Details:

1) Function Name: and


Prototype: C = AND(A,B)
Description: A & B is a matrix whose elements are 1's where both A and B
have non-zero elements, and 0's where either has a zero element. A & B must
have the same dimensions unless one is a scalar.
Parameters:
o
A & B: Matrix.
2) Function Name: pause
Prototype: PAUSE(n)
Description: PAUSE(n) pauses for n seconds before continuing, where n can
also be a fraction. The resolution of the clock is platform specific. Fractional
pauses of 0.01 seconds should be supported on most platforms.
Parameters:
o n: a delay to be introduced.

Source Code: 37

IMAGE PROCESSING

2014

clc; clear all; close all;


inputImg = [ 0
0
0
0
0
0
0
0
0
0
0

0
1
1
1
0
0
0
1
1
1
0

0
1
0
0
1
1
1
0
0
1
0

0
1
0
0
0
0
0
0
0
1
0

0
1
0
0
1
1
1
0
0
1
0

0
1
1
1
0
0
0
1
1
1
0

0;
0;
0;
0;
0;
0;
0;
0;
0;
0;
0; ];

subplot(1,4,1); imshow(inputImg); title('Input Image');


compImg = ~inputImg; % Complimenting input image
subplot(1,4,2); imshow(compImg); title('Complimented Input Image');
% Structuring element
structuringElement = [ 0 1 0;
1 1 1;
0 1 0; ];
filledImg = zeros(size(inputImg)); % Creating an N-by-N matrix of zeros.
filledImg(3,3) = 1; % Setting starting point
index = 0;
flagRegFound=0;
while flagRegFound ~= 1
index = index + 1;
subplot(1,4,3); imshow(filledImg); title('Filled Region');
% Using structuring element to perform dilation on Images
xnew = and(imdilate(filledImg, structuringElement), compImg);
% Checking if the previous and new image is same.
%If yes the region is filed
if sum(sum(xnew - filledImg)) == 0
flagRegFound = 1;
else
filledImg = xnew;
end
pause(0.25); % Introducing a pause of 1 seconds
end
% Displaying final imag i.e. filledImg + inputImg
outputImg = filledImg + inputImg;
subplot(1,4,4); imshow(outputImg); title('Final Output Image');

Output: -

38

IMAGE PROCESSING

2014

Pract
ical No: 11
Topic: - Morphological Operations.
Problem Statement: Write a program to input an image and perform following morphological
operations on it:
o
o
o

Erosion and Dilation


Opening and Closing
Boundary Extraction

Theory: Understanding Dilation and Erosion

Morphology is a broad set of image processing operations that


process images based on shapes. Morphological operations apply a structuring
element to an input image, creating an output image of the same size. In a
morphological operation, the value of each pixel in the output image is based on
a comparison of the corresponding pixel in the input image with its neighbors.
By choosing the size and shape of the neighborhood, you can construct a
morphological operation that is sensitive to specific shapes in the input image.
The most basic morphological operations are dilation and
erosion. Dilation adds pixels to the boundaries of objects in an image, while
erosion removes pixels on object boundaries. The number of pixels added or
removed from the objects in an image depends on the size and shape of the
structuring element used to process the image. In the morphological dilation
and erosion operations, the state of any given pixel in the output image is
determined by applying a rule to the corresponding pixel and its neighbors in
39

IMAGE PROCESSING

2014

the input image. The rule used to process the pixels defines the operation as
dilation or erosion. This table lists the rules for both dilation and erosion.
Used Functions Details:

1) Function Name: imagesc


Prototype: IMAGESC(img)
Description: IMAGESC(...) is the same as IMAGE(...) except the data is scaled
to use the full colormap..
Parameters:
o
img: Image to be scaled.
2) Function Name: strel
Prototype: SE = STREL('arbitrary',NHOOD)
Description: creates a flat structuring element with the specified
neighborhood. NHOOD is a matrix containing 1's and 0's; the location of
the 1's defines the neighborhood for the morphological operation.
Parameter:
o arbitrary: Type of the structuring element.
o NHOOD: Dimension of the element.
Examples:
o se1 = strel('square',11) % 11-by-11 square
o se2 = strel('line',10,45) % line, length 10, angle 45 degrees
o se3 = strel('disk',15)
% disk, radius 15
o se4 = strel('ball',15,5)
% ball, radius 15, height 5

o
o

3) Function Name: imdilate


Prototype: IM2 = IMDILATE(IM,SE)
Description: It dilates the grayscale, binary, or packed binary image IM,
returning the dilated image, IM2. SE is a structuring element object, or
array of structuring element objects, returned by the STREL function.
Parameters:
IM: Input Image
SE: Structuring lement.

o
o

4) Function Name: imerode


Prototype: IM2 = IMERODE(IM,SE)
Description: It erodes the grayscale, binary, or packed binary image IM,
returning the eroded image, IM2. SE is a structuring element object, or
array of structuring element objects, returned by the STREL function.
Parameters:
IM: Input Image
SE: Structuring lement.

5) Function Name: ismember


Prototype: ISMEMBER(A,S)
Description: For the array A, it returns an array of the same size as A
Containing 1 where the elements of A are in the set S and 0 otherwise. A
and S can be cell arrays of strings.
Parameters:
o A & S: Image Vectors.

40

IMAGE PROCESSING

2014

Source Code: clc; clear all; close all;


figure;
iptImg = imread('trees.tif');
subplot(2,3,1);
colormap(gray(256));
imagesc(iptImg)
title('Input Image');
% Structuring element construction %
se = strel('square',8);
% 8-by-8 square
%se = strel('line',10,45);
% line, length 10, angle 45 degrees
%se = strel('disk',5);
% disk, radius 15
%se = strel('ball',15,5);
% ball, radius 15, height 5
% Morphological Operations
% 1. Dialation
dilateImg = imdilate(iptImg,se);
subplot(2,3,2); imagesc(dilateImg); title('Image Dilation');
% 2. Erosion
erodeImg = imerode(iptImg,se);
subplot(2,3,3); imagesc(erodeImg); title('Image Erosion');
% 3. Opening
openImg = imdilate(erodeImg,se);
subplot(2,3,4); imagesc(openImg); title('Image Opening');
% 4. Closing
closeImg = imerode(dilateImg,se);
subplot(2,3,5); imagesc(closeImg); title('Image Closing');
% 5. Boundary Extraction
V = [80:168];
iptImg = ones(size(iptImg)) - ismember(iptImg,V);
bdExtImg = iptImg-double(imerode(iptImg,se));
subplot(2,3,6); imagesc(bdExtImg); title('Boundary Extraction');

Output: -

41

IMAGE PROCESSING

2014

42

IMAGE PROCESSING

2014

Practical No: 12
Topic: - Logical Operations.
Problem Statement: Performing various logical operations on an input image: AND, OR, XOR,
NOT.
Theory:

im2bw
Convert an image to a binary image, based on threshold SyntaxBW = im2bw(I,level)
BW = im2bw(X,map,level)
BW = im2bw(RGB,level)
Description
im2bw produces binary images from indexed, intensity, or RGB images. To do this, it
converts the input image to grayscale format (if it is not already an intensity image),
and then uses thresholding to convert this grayscale image to binary. The output binary
image BW has values of 0 (black) for all pixels in the input image with luminance less
than level and 1 (white) for all other pixels. (Note that you specify level in the range
[0,1], regardless of the class of the input image.) BW = im2bw(I,level) converts the
intensity image I to black and white. BW = im2bw(X,map,level) converts the indexed
image X with colormap map to black and white. BW = im2bw(RGB,level) converts the
RGB image RGB to black and white.
xor Exclusive or:
Syntax
C = xor(A,B)
Description
C = xor(A,B) performs an exclusive OR operation on the corresponding elements of
arrays A and B. The resulting element C(i,j,...) is logical true (1) if A(i,j,...) or B(i,j,...), but
not both, is nonzero.
Logical Operators:
Elementwise & | ~ Elementwise logical operations on arrays
Syntax
A&B
A|B
~A
Description
The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. They work
element by element on arrays, with 0 representing logical false, and anything nonzero
representing logical true. The logical operators return a logical array with elements set
to true (1) or false (0), as appropriate. The & operator does a logical AND, the | operator
does a logical OR, and ~A complements the elements of A. The function xor(A,B)
implements the exclusive OR operation.

43

IMAGE PROCESSING

2014

Source Code: clc; clear all; close all;


figure;
iptImg = imread('peppers.PNG');
% Converting image into Binary form
P = im2bw(iptImg);
% NOT Operation %
notImg = ~P;
subplot(1,2,1); imshow(iptImg); title('P');
subplot(1,2,2); imshow(notImg); title('NOT P');
imgNoisy = imnoise(iptImg,'poisson');
Q = im2bw(imgNoisy);
figure;
% AND Operation %
andImg = P & Q;
subplot(3,3,1); imshow(P); title('P');
subplot(3,3,2); imshow(Q);title('Q');
subplot(3,3,3); imshow(andImg); title('P AND Q');
% OR Operation %
orImg = P | Q;
subplot(3,3,4); imshow(P); title('P');
subplot(3,3,5); imshow(Q);title('Q');
subplot(3,3,6); imshow(orImg); title('P OR Q');
% XOR Operation %
xorImg = xor(P,Q);
subplot(3,3,7); imshow(P); title('P');
subplot(3,3,8); imshow(Q);title('Q');
subplot(3,3,9); imshow(xorImg); title('P XOR Q');

44

IMAGE PROCESSING

2014

Output: -

45

IMAGE PROCESSING

2014

Practical No: 13
Aim: An input image is provided. Apply Sampling and Quantization techniques on it and
display the resulting image.
Theory:
Imresize
Resize an image SyntaxB = imresize(A,m)
B = imresize(A,m,method)
B = imresize(A,[mrows ncols],method)
B = imresize(...,method,n)
B = imresize(...,method,h)
Description
B = imresize(A,m) returns an image B that is m times the size of A, using
nearest-neighbor interpolation. A can be an indexed image, grayscale image, RGB, or
binary image. If m is between 0 and 1.0, B is smaller than A. If m is greater than 1.0, B
is larger than A. B = imresize(A,m,method) returns an image that is m times the size of
A using the interpolation method specified by method. method is a string that can have
one of these values. The default value is enclosed in braces ({}).

Source Code:clc;
close all;
clear all;
I=imread('circuit.tif');
J=imresize(I,0.5);
figure(1);
imshow(I);
figure(2);
imshow(J);
quanta=100;
img=double(I)/255;
img=uint8(img*quanta);
figure(3);
imshow(img);

46

IMAGE PROCESSING

2014

Output:-

47

IMAGE PROCESSING

2014

PRACTICAL NO:14
Aim:-A texture image or a granular image is provided as input. A suitable
algorithm that computes pattern size or granule size in terms of number of
pixel it occupies is to be implemented. This information is to be display as a
histogram.
Theory:
Regionprops
Measure properties of image regions
Syntax
STATS = regionprops(L,properties)
Description
STATS = regionprops(L,properties) measures a set of properties for each labeled region
in the label matrix L. Positive integer elements of L correspond to different regions. For
example, the set of elements of L equal to 1 corresponds to region 1; the set of
elements of L equal to 2 corresponds to region 2; and so on. The return value STATS is a
structure array of length max(L(:)). The fields of the structure array denote different
measurements for each region, as specified by properties. properties can be a
comma-separated list of strings, a cell array containing strings, the single string 'all', or
the string 'basic'.
im2bw
Convert an image to a binary image, based on threshold SyntaxBW = im2bw(I,level)
BW = im2bw(X,map,level)
BW = im2bw(RGB,level)
Description
im2bw produces binary images from indexed, intensity, or RGB images. To do this, it
converts the input image to grayscale format (if it is not already an intensity image),
and then uses thresholding to convert this grayscale image to binary. The output binary
image BW has values of 0 (black) for all pixels in the input image with luminance less
than level and 1 (white) for all other pixels. (Note that you specify level in the range
[0,1], regardless of the class of the input image.) BW = im2bw(I,level) converts the
intensity image I to black and white. BW = im2bw(X,map,level) converts the indexed
image X with colormap map to black and white. BW = im2bw(RGB,level) converts the
RGB image RGB to black and white.
Mean
Average or mean value of arrays
Syntax
M = mean(A)
M = mean(A,dim)
Description
M = mean(A) returns the mean values of the elements along different dimensions of an
array. If A is a vector, mean(A) returns the mean value of A. If A is a matrix, mean(A)
treats the columns of A as vectors, returning a row vector of mean values. If A is a
multidimensional array, mean(A) treats the values along the first non-singleton
dimension as vectors, returning an array of mean values. M = mean(A,dim) returns the
mean values for elements along the dimension of A specified by scalar dim. For
matrices, mean(A,2) is a column vector containing the mean value of each row. The
default of dim is 1.
48

IMAGE PROCESSING

2014

Std
Standard deviation
Syntax
s = std(X)
s = std(X,flag)
s = std(X,flag,dim)
Description
s = std(X), where X is a vector, returns the standard deviation using (1) above. If X is a
random sample of data from a normal distribution, is the best unbiased estimate of its
variance. If X is a matrix, std(X) returns a row vector containing the standard deviation
of the elements of each column of X. If X is a multidimensional array, std(X) is the
standard deviation of th elements along the first nonsingleton dimension of X. s =
std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1) returns the standard
deviation using (2) above, producing the second moment of the sample about its mean.
s = std(X,flag,dim) computes the standard deviations along the dimension of X
specified by scalar dim.
Median
Median value of arrays
Syntax
M = median(A)
M = median(A,dim)
Description
M = median(A) returns the median values of the elements along different dimensions of
an array. If A is a vector, median(A) returns the median value of A. If A is a matrix,
median(A) treats the columns of A as vectors, returning a row vector of median values.
If A is a multidimensional array, median(A) treats the values along the first
nonsingleton dimension as vectors, returning an array of median values. M =
median(A,dim) returns the median values for elements along the dimension of A
specified by scalar dim.

Source Code:clc;
clear all;
close all;
iptImg = imread('rice.png');
subplot(2,3,1);
imshow(iptImg);
title('Original Image');
subplot(2,3,2)
imshow(iptImg);
colormap(Jet); % Sets the current figures map to JET
title('Jet Colormap Image');
% Background Estimation
49

IMAGE PROCESSING

2014

% imopen performs morphological opening on the grayscale or binary image


% strel is used to creat disk shaped structuring element of radius 10
bkgrndImg = imopen(iptImg,strel('disk',10));
subplot(2,3,3);
imshow(bkgrndImg);
colormap(Jet);
title('Background Estimation');
% Background Removal
subImg = imsubtract(iptImg,bkgrndImg);
subplot(2,3,4);
imshow(subImg);
title('Flattened Backgroung Removal');
% Segment Grains from the background, obtains the binary Image
% graythresh computes Global Image Threshold
subplot(2,3,5);
binaryImg = im2bw(subImg,graythresh(subImg));
imshow(binaryImg);
title('Thrsholded Image');
% Label Connected Region
[L NUM] = bwlabel(binaryImg);
subplot(2,3,6);
imshow(L,[]);
colormap(jet);
pixval('on'); % Display information about image pixels.
title('Connected Region');
% Feature Extraction
% Measures a set of properties for each labeled region in the label matrix L.
stats = regionprops(L);
A = [stats.Area];
figure;
hist(A);
xlabel('Area in Pixels');
ylabel('Popularity');
title('Size Distribution');
% Statistical Measurement
mean(A);
std(A);
median(A);

50

IMAGE PROCESSING

2014

Output:-

51

IMAGE PROCESSING

2014

PRACTICAL No:15
52

IMAGE PROCESSING

2014

Aim:- Write a Program to input an image and implement the global thresh
holding algorithms on it. Display the resulting image.
Theory:
bar, barh Bar graph (vertical and horizontal)
Syntax
bar(Y)
bar(x,Y)
bar(...,width)
bar(...,'style')
bar(...,'bar_color')
bar(axes_handle,...)
h = bar(...)
hpatches = bar('v6',...)
barh(...)
h = barh(...)
hpatches = barh('v6',...)
Description
A bar graph displays the values in a vector or matrix as horizontal or vertical bars.
bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars
produced by the elements in each row. The x-axis scale ranges from 1 to length(Y)
when Y is a vector, and 1 to size(Y,1), which is the number of rows, when Y is a matrix.
bar(x,Y) draws a bar for each element in Y at locations specified in x, where x is a
monotonically increasing vector defining the x-axis intervals for the vertical bars. If Y is
a matrix, bar groups the elements of each row in Y at corresponding locations in x.
bar(...,width) sets the relative bar width and controls the separation of bars within a
group. The default width is 0.8, so if you do not specify x, the bars within a group have
a slight separation. If width is 1, the bars within a group touch one another.
bar(...,'style') specifies the style of the bars. 'style' is 'grouped' or 'stacked'. 'group' is
the default mode of display. 'grouped' displays m groups of n vertical bars, where m is
the number of rows and n is the number of columns in Y. The group contains one bar
per column in Y. 'stacked' displays one bar for each row in Y. The bar height is the sum
of the elements in the row. Each bar is multicolored, with colors corresponding to
distinct elements and showing the relative contribution each row element makes to the
total sum. bar(...,'bar_color') displays all bars using the color specified by the
single-letter abbreviation 'r', 'g', 'b', 'c', 'm', 'y', 'k', or 'w'. bar(axes_handles,...) and
barh(axes_handles,...) plots into the axes with handle axes_handle instead of the
current axes (gca). h = bar(...) returns a vector of handles to barseries graphics objects.
bar creates one barseries graphics object per column in Y. barh(...) and h = barh(...)
create horizontal bars. Y determines the bar length. The vector x is a monotonic vector
defining
the
y-axis
intervals
for
horizontalbars.

53

IMAGE PROCESSING

2014

Source Code:clc;
close all;
clear all;
a=imread('circuit.tif');
[row col]=size(a);
h=zeros(1,256);
for n=1:1:row
for m=1:1:col
t=a(n,m);
h(t)=h(t)+1;
end
end
figure(1),imshow(a);
figure(2),bar(h)
[X,Y]=ginput(1);
for x=1:1:col
for y=1:1:col
if a(x,y)<X
a(x,y)=0;
else
a(x,y)=255;
end
end
end
figure(3),imshow(uint8(a));
Output:

54

IMAGE PROCESSING

2014

55

IMAGE PROCESSING

2014

56

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