Sunteți pe pagina 1din 43

Experiment 1

AIM:

Write a MATLAB program to calculate compression ratio using


Huffman Coding for various input image.

Short Description of Huffman Theory:


In 1952 David A. Huffman published the paper A Method for the Construction of MinimumRedundancy Codes in which he defined a greedy algorithm that constructs an optimal prefix code called
a Huffman code.
The algorithm begins with a set C of pairs (c,f), called HuffmanLeaf, where c is a character of an
underlying alphabet (e.g., ASCII or data type byte) and f denotes the number of occurrences of c in a
given source file. The set C is a partial order over pairs. Thus, if (t,2),(d,3) C (i.e, (t,2), (d,3)
are elements of C), then we have that pair (t,2) (d,3). Huffmans algorithm uses the frequency f to
identify the two least-frequent objects in C and merges them. The result of the merger is a new object
(i.e., HuffmanNode) whose frequency is the sum of the frequency of the two objects being merged. In
total, the algorithm performs a sequence of |C| - 1 merging operations to create a Huffman tree.
Compression ratio can be found from equation:
Compression Ratio=

Original Image
Compressed Image

Symbol Weights:
n
pr ( r k ) = k for k =0,1,2, , L1
MN
Average Length of Code:
L1

Lavg= l ( r k ) pr (r k )
k=0

Entropy H Equation:
L1

H= pr (r k ) log 2 p r (r k )
k=0

Generalized MATLAB Code to Calculate Compression Ratio


Using Huffman Coding:

clc;
close all;
im=[5 100 200 3; 6 5 4 2; 100 2 3 46; 2 2 5 3];
m1=max(max(im));
s=1:m1;
[m,n]=size(im);
p=zeros(1,m1);
for k=1:m1
for i=1:m
for j=1:n
if (im(i,j)==k)
p(k)=p(k)+1;
end
end
end
p1(k)=p(k)/(m*n);
end
im1=im(:);
dict=huffmandict(s,p1);
hcode=huffmanenco(im1,dict);
dsig=huffmandeco(hcode,dict);
k=1;
for i=1:m
for j=1:n
res(i,j)=dsig(k);
k=k+1;
end
end
res=res';
figure; imagesc(im);title('Original Image');
figure; imagesc(res);title('Decoded Image');
num=m*n*8;
den=length(hcode);
CR=num/den
len=zeros(1,m1);
for i=1:m1
len(i)= length(dict{i,2});
end
lavg=sum(len.*p1);
for i=1:m1
if (p1(i)~=0)
H= sum(p1(i).*log10(p1(i))/0.3010);
end
end

H=-H
E=(H/lavg)*100

Compression

Ratio Output with Input Image & Some

Intermediate Information of Huffman Experiment:

Figure 1 Input Image

E=

8.6965

[Information]

H=

0.2500

[Entropy]

CR = 2.7826

Figure 2 Output Image

[Compression Ratio]

Conclusion of Experiment No. 1:


In Huffman Coding, less number of bits are assigned to higher probabilities and more number of
bits are assigned to lower probabilities. Compression ratio depends on inter-pixel redundancy. Entropy
depends on the amount of information/details. Entropy increases as information, object, details increases,
average length will also increase, which will increase efficiency of this coding.

Experiment 2

AIM:

Write a MATLAB program to compress image using Discrete Cosine


Transform and compute RMSE and PSNR for various input images.

Short Description of Discrete Cosine Transform Theory:


The discrete cosine transform (DCT) represents an image as a sum of sinusoids of varying
magnitudes and frequencies. The dct2 function computes the two-dimensional discrete cosine transform
(DCT) of an image. The DCT has the property that, for a typical image, most of the visually significant
information about the image is concentrated in just a few coefficients of the DCT. For this reason, the
DCT is often used in image compression applications. For example, the DCT is at the heart of the
international standard lossy image compression algorithm known as JPEG.
The two-dimensional DCT of an M-by-N matrix A is defined as follows.
M 1 N1

B pq= p q

A mn cos

m=0 n=0

p=

(2 m+1) p
(2n+1)q 0 p M 1
cos
,
2M
2N
0 q N1

1 / M , p=0
1/ N , q=0
, =
2 /M , 1 p M 1 q 2/ N , 1 q N1

The values Bpq are called the DCT coefficients of A


The 64 Basis Functions of an 8-by-8 Matrix:

DCT and Image Compression


In the JPEG image compression algorithm, the input image is divided into 8-by-8 or 16-by-16 blocks, and
the two-dimensional DCT is computed for each block. The DCT coefficients are then quantized, coded,
and transmitted. The JPEG receiver (or JPEG file reader) decodes the quantized DCT coefficients,
computes the inverse two-dimensional DCT of each block, and then puts the blocks back together into a

single image. For typical images, many of the DCT coefficients have values close to zero; these
coefficients can be discarded without seriously affecting the quality of the reconstructed image.
Root Mean Square Error
It is measure of estimator which suggests the accuracy of registration with respect to reference
image. It should be near to zero for best match.

1
2
RMSE=
(x (i , j ) y (i, j))

MN i =1 j=1
Peak Signal to Noise Ratio
It is a ratio of maximum possible power of signal to power of corrupting noise that affects the
fidelity of representation. Its range is wide so it is expressed as logarithmic scale. Maximum value of
PSNR indicates good match between the two images.
n

PSNR=10 log 10

(2 1)
MSE

Generalized MATLAB Code to compress image using Discrete


Cosine Transform:
clc;
clear all;
close all;
im=imread('cameraman.tif');
im = double(im)/255;
% im = rgb2gray(im);
figure; imshow(im); title('Original image');
img_dct=dct2(im);
img_pow=(img_dct).^2;
img_pow=img_pow(:);
[B,index]=sort(img_pow);
B=flipud(B);
index=flipud(index);
compressed_dct=zeros(size(im));
coeff = 20000;
for k=1:coeff
compressed_dct(index(k))=img_dct(index(k));
end
im_dct=idct2(compressed_dct);
figure; imshow(im_dct); title('DCT Compress Image');

%no zig-zag

% maybe change the value

psn=PSNR(im,im_dct);

Compressed Output Image with Input Image & Some

Intermediate Information of DCT Experiment:

Figure 3 Original Input Image

Figure 4 DCT Compressed Image

MATLAB Function for Finding PSNR and RMSE Values:


function psnr_Value = PSNR(A,B)
% PSNR (Peak Signal to noise ratio)
if (size(A) ~= size(B))
error('The size of the 2 matrix are unequal')
psnr_Value = NaN;
return;
elseif (A == B)
disp('Images are identical: PSNR has infinite value')
psnr_Value = Inf;
return;
else
maxValue = double(max(A(:)));

% Calculate MSE, mean square error.


mseImage = (double(A) - double(B)) .^ 2;
[rows columns] = size(A);
mse = sum(mseImage(:)) / (rows * columns);
% Calculate PSNR (Peak Signal to noise ratio)
psnr_Value = 10 * log10( 256^2 / mse)
RMSE = sqrt(mse)
% RMSE
end

PSNR and RMSE Values of Output Image & Input Image:

psnr_Value =

RMSE =

81.5724

0.0214

Conclusion of Experiment No. 2:


By performing this experiment we conclude that using DCT compression of the image is possible with
some error.

Experiment 3

AIM:

Write a MATLAB program to perform image compression using Run


Length Encoding method.

Short Description of Run Length Encoding Theory:


Run-length encoding is a data compression algorithm that is supported by most bitmap file
formats, such as TIFF, BMP, and PCX. RLE is suited for compressing any type of data regardless of its
information content, but the content of the data will affect the compression ratio achieved by RLE.
Although most RLE algorithms cannot achieve the high compression ratios of the more advanced
compression methods, RLE is both easy to implement and quick to execute, making it a good alternative
to either using a complex compression algorithm or leaving your image data uncompressed.
RLE works by reducing the physical size of a repeating string of characters. This repeating string,
called a run, is typically encoded into two bytes. The first byte represents the number of characters in the
run and is called the run count. In practice, an encoded run may contain 1 to 128 or 256 characters; the
run count usually contains as the number of characters minus one (a value in the range of 0 to 127 or
255). The second byte is the value of the character in the run, which is in the range of 0 to 255, and is
called the run value.
Uncompressed, a character run of 15 A characters would normally require 15 bytes to store:
AAAAAAAAAAAAAAA
The same string after RLE encoding would require only two bytes:
15A
The 15A code generated to represent the character string is called an RLE packet. Here, the first
byte, 15, is the run count and contains the number of repetitions. The second byte, A, is the run value and
contains the actual repeated value in the run.
A new packet is generated each time the run character changes, or each time the number of
characters in the run exceeds the maximum count. Assume that our 15-character string now contains four
different character runs:
AAAAAAbbbXXXXXt
Using run-length encoding this could be compressed into four 2-byte packets:
6A3b5X1t
Thus, after run-length encoding, the 15-byte string would require only eight bytes of data to
represent the string, as opposed to the original 15 bytes. In this case, run-length encoding yielded a
compression ratio of almost 2 to 1.

Long runs are rare in certain types of data. For example, ASCII plaintext seldom contains long
runs. In the previous example, the last run (containing the character t) was only a single character in
length; a 1-character run is still a run. Both a run count and a run value must be written for every 2character run. To encode a run in RLE requires a minimum of two characters worth of information;
therefore, a run of single characters actually takes more space. For the same reasons, data consisting
entirely of 2-character runs remains the same size after RLE encoding.
In our example, encoding the single character at the end as two bytes did not noticeably hurt our
compression ratio because there were so many long character runs in the rest of the data. But observe how
RLE encoding doubles the size of the following 14-character string:
Xtmprsqzntwlfb
After RLE encoding, this string becomes:
1X1t1m1p1r1s1q1z1n1t1w1l1f1b

Variants on Run-Length Encoding:-

Basic run-length encoding flow:-

Generalized MATLAB Code to Compress Data Using Run


Length Encoding:
clc;clear all;close all;
x=[5 5 2 2 2 0 1 1 4 4 4 4]
x=[x 0];
l=length(x);
k=1;
temp1=[];temp2=[];temp3=[];
for i=1:l-1
temp=x(i)
if(temp==x(i+1))
k=k+1;
t=k;
else
t=k;

k=1;
temp=[temp t];
temp1=temp;
temp2=cat(1,temp2,temp1)
end
end
[r1 c1]=size(temp2);
for i=1:r1
for j=1:c1
temp3=[temp3 temp2(i,j)];
end
end
cr=length(x)/length(temp3)

Compressed Output Data with Input Data & Some

Information of Run Length Encoding Experiment:


x= [5

temp2 =

cr =

5
2
0
1
4

2
3
1
2
4

4]

1.3000

Input Data
Output Data

Compression Ratio

Generalized MATLAB Code to Compress Image Using Run


Length Encoding:
clc;clear all;close all;
im=imread('cameraman.tif');
image=im2bw(im(:));
[d,c]=rlencoding(image);
De_image=rldecoding(d,c);
Comression_ratio=length(image)/(2*length(d));
-----------------------------------------------Encoding Function-------------------------------------------------function [d,c]=rlencoding(x);
% This function performs Run Length Encoding to a strem of data x.
% [d,c]=rl_enc(x) returns the element values in d and their number of
if nargin~=1

error('A single 1-D stream must be used as an input')


end
ind=1;
d(ind)=x(1);
c(ind)=1;
for i=2 :length(x)
if x(i-1)==x(i)
c(ind)=c(ind)+1;
else ind=ind+1;
d(ind)=x(i);
c(ind)=1;
end
end
-----------------------------------------------Decoding Function-------------------------------------------------function x=rldecoding(d,c);
% This function performs Run Length Dencoding to the elements of the strem
% of data d according to their number of apperance given in c. There is no
% restriction on the format of the elements of d, while the elements of c
% must all be integers.
if nargin<2
error('not enough number of inputs')
end
x=[];
for i=1:length(d)
x=[x d(i)*ones(1,c(i))];
end

Compressed Ratio of Run Length Code Experiment:


Comression_ratio =

5.2112

Conclusion of Experiment No. 3:


By performing this experiment we can conclude that image compression of the input image is
possible using run length encoding, but the compression ratio depends on the type of image. If the
occurrence of the pixel is not sufficiently high than output image size can be higher than input image
which is not desirable.

Experiment 4

AIM: Write a MATLAB program to Perform Template Matching using Sum


of Squared Difference (SSD) and Normalized Correlation Coefficient (NCC).

Short Description on Template Matching using SSD & NCC:


Template Matching

Template matching is a technique in digital image processing for finding small parts of an image
which match a template image. It can be used in manufacturing as a part of quality control, a way to
navigate a mobile robot, or as a way to detect edges in images.
Target image: original image bigger one
Template image: which is to be matched smaller one
Correlation based Template matching

Many Correlation based methods are available


Sum of Squared Difference (SSD),
Normalized Cross Correlation (NCC),
Increment Sign Correlation (ISC),
M- Estimator Correlation Coefficient (MCC)
ISC and MCC will reduce the influence of noise and occlusion very accurately.
In correlation based template matching algorithm, one need to scan the target image and search for
the maximum correlation.

Sum of Squared Differences (SSD)

Let F= {F1,F2,.. Fn} is the original image and f = {f1,f2.fn} is the template image.
n

SSD= ( F jf j )2
j=1

Where n is the size of template image.


The value of SSD close to zero indicates the best match.
The computation of SSD is efficient but is very sensitive to changes in image brightness due to
occlusion and shading.

Normalized Cross Correlation Coefficient(NCC)


n

f i f )
(F i F)(
NCC=

i=1

2
(Fi F)
i=1

i=1

(f i f )2

Let F= {F1,F2,.. Fn} is the original image and f = {f1,f2.fn} is the template image.
The SSD and NCC both estimate the degree of linear dependence between the corresponding pixel
brightness values being compared.
The range of NCC is -1 to +1.
The value closer to 1 indicates the better match.

Generalized MATLAB Code for Template Matching using


Sum of Squared Difference (SSD) Method:
clc; close all; clear all;
image=imread('cameraman.tif');
image=imresize(image,[100 100]);
image=double(image);
figure;imshow(uint8(image));
image_cropped=imcrop(image,[37 13 20 17]);
image_cropped=double(image_cropped);
figure,imshow(uint8(image_cropped));
[r_im,c_im]=size(image);
[r_c_im,c_c_im]=size(image_cropped);
sum=[];
for i=1:r_im-r_c_im+1
for j=1:c_im-c_c_im+1
temp=0;
for i1=1:r_c_im
for j1=1:c_c_im
temp = temp +(image(i+i1-1,j+j1-1)-image_cropped(i1,j1))^2;
end
end
sum(i,j)= temp;
end
end
min_val=min(min(sum));
[y,x]=find(sum==(min_val));
figure;imshow(uint8(image));hold on;

rectangle('Position',[x,y,c_c_im,r_c_im],'LineWidth',2,'LineStyle','--','EdgeColor','r');

Template Detected Output Image with Input Image &

template Image used in this SSD Experiment:

Figure 5 Template detected Output Image

Figure 7 Template Image

Figure 6 Original Input image

Generalized MATLAB Code for Template Matching using


Normalized Cross Correlation Coefficient(NCC) Method:
clc; close all; clear all; format long;
%%---------------------------------------------------- Image read-----------------------------------------------image=imread('cameraman.tif');
image=imresize(image,[100 100]);
figure;imshow(uint8(image));
%%----------------------------------------------- Template generation-----------------------------------------t_image=imcrop(image,[37 13 20 17]);
t_image=double(t_image);
figure;imshow(uint8(t_image));
%%--------------------------------------------------- add noise---------------------------------------------------n_image=imnoise(image,'salt & pepper');
%n_image=imnoise(image,'poisson');
%n_image=imnoise(image,'gaussian');
n_image=double(n_image);
figure;imshow(uint8(n_image));
[r_n c_n]=size(n_image);
[r_t c_t]=size(t_image);
mean_vect=[];mean_1=0;
%% -------------------------------------------------figure mean--------------------------------------------------for i=1:r_n-r_t+1

for j=1:c_n-c_t+1
mean_1=0;
for i1=1:r_t
for j1=1:c_t
mean_1=mean_1+(n_image(i+i1-1,j+j1-1));
end
end
mean_vect(i,j)= mean_1/(r_t*c_t);
end
end
%% ------------------------------------------------denominator_left-term--------------------------------------for i=1:r_n-r_t+1
for j=1:c_n-c_t+1
diff_sqr_l=0;
for i1=1:r_t
for j1=1:c_t
diff_sqr_l =diff_sqr_l+(n_image(i+i1-1,j+j1-1)-mean_vect(i,j));
end
end
diff_sqr_sqrt_l(i,j)=sqrt(diff_sqr_l);
end
end
%%--------------------------------------------------template mean-----------------------------------------------temp_mean=0;
for i1=1:r_t
for j1=1:c_t
temp_mean = temp_mean +t_image(i1,j1);
end
end
temp_mean=temp_mean/(r_t*c_t);
%%-----------------------------template-matrix for numerator multiplication-------------------------------for i1=1:r_t
for j1=1:c_t
temp_mat(i1,j1) = t_image(i1,j1)-temp_mean;
end
end
%% -------------------------------------------denominator_right-term------------------------------------------diff_sqr_r=0;
for i=1:r_t
for j=1:c_t
diff_sqr_r =diff_sqr_r+ (t_image(i,j)-temp_mean);
end
end
diff_sqr_sqrt_r = sqrt(diff_sqr_r);
%% -------------------------------------------NCC formula implementation-----------------------------------for i=1:r_n-r_t+1

for j=1:c_n-c_t+1
temp=0;
for i1=1:r_t
for j1=1:c_t
numer_l(i1,j1)=(n_image(i+i1-1,j+j1-1)-mean_vect(i,j));
denom_l(i1,j1)=numer_l(i1,j1)^2;
end
end
temp1=numer_l.*temp_mat;
numer_l_s = sum(sum(temp1));
denom_l_s = sqrt(sum(sum(denom_l)));
denom_r=diff_sqr_sqrt_r;
NCC_s (i,j)=numer_l_s /(denom_l_s + denom_r);
end
end
%%--------------------------- Location finding and making ractangular boundary-------------------------max_val=max(max(NCC_s));
[y,x]=find(NCC_s ==(max_val));
figure;imshow(uint8(n_image));hold on;
rectangle('Position',[x,y,c_t,r_t],'LineWidth',2,'LineStyle','--','EdgeColor','r');

Template Detected Output Image with Noisy Input Image &

template Image used in this NCC Experiment:

Figure 9 Template Image

Figure 8 Input Image

Figure 10 Template Detected


Output Image with Impulse
Noise

Figure 11 Template Detected


Output Image with Poisson
Noise

Figure 12 Template Detected


Output Image with Gaussian
Noise

Conclusion of Experiment No. 4:


By performing this experiment we conclude that the result with SSD method is good but the result
achieved with NCC method is better in presence of noise. In SSD method, the best match yields to 0
value where as in NCC, the value is 1.

Experiment 5

AIM:

Write a MATLAB program to Perform Template Matching using


Increment Sign Correlation (ISC).

Short Description on Template Matching using ISC:


Increment Sign Correlation Coefficient (ISC)
Increment sign correlation (Increment Sign Correlation; ISC) is for the gray image matching, is
the statistic that was focused on the sign of the increase or decrease in brightness. This statistic is one
that captures statistically the increase or decrease tendency of the luminance value of the pixel of
interest and the neighboring pixels, the degree of noise and lighting variations that do not cause the
sign inversion, you can match the robust to such shielding of the object.
Checking sign of increasing and decreasing in brightness by scanning both the images from left to
right and top to bottom.
Increment sign correlation is calculated based on the degree of matching of binary code.
For the Target image, the binary codes is defined as
1b
f
{b b +( i F )(1bi )}
n
1
ISC=
n i=1
F
i

f
i

ISC represents the percentage of the match of each bit each other in the two-bit column.
For the Template image, the binary codes is defined as

biF = 1, if Fi +1 Fi
0, otherwise
The increment sign correlation coefficient (ISC) is defined as follows.

bif = 1, if f i+1 f i
0, otherwise

Generalized MATLAB Code for Template Matching using


Increment Sign Correlation Coefficient (ISC):
clc;
close all;
clear all;
format long;
%% ---------------------------------------------Image read-------------------------------------------------------image=imread('cameraman.tif');
image=imresize(image,[100 100]);
figure;imshow(uint8(image));
n_image = rgb2gray(imread('fill.jpg'));
figure;imshow((n_image));
%% -----------------------------------------Template generation------------------------------------------------t_image=imcrop(image,[33 12 22 20]);
t_image=double(t_image);
figure;imshow(uint8(t_image));
%% ----------------------------------------------addin noise------------------------------------------------------n_image=imnoise(n_image,'gaussian');
n_image=imnoise(n_image,'Poisson');
n_image=imnoise(n_image,'salt & pepper');
n_image=double(n_image);
[r_n c_n]=size(n_image);
[r_t c_t]=size(t_image);
mean_vect=[];mean_1=0;
%% -----------------------------------------------template_isc---------------------------------------------------template_isc=zeros(r_t,c_t);
for i1=1:r_t-1
for j1=1:c_t-1
if(t_image(i1,j1)>t_image(i1,j1+1))
template_isc(i1,j1)=1;
else
template_isc(i1,j1)=0;
end
end
end
%% --------------------------------------------------figure_isc----------------------------------------------------

isc_temp=0;isc=[];figure_isc=zeros(r_n,c_n);
for i=1:r_n-1
for j=1:c_n-1
if(n_image(i,j)>n_image(i,j+1))
figure_isc(i,j)=1;
else
figure_isc(i,j)=0;
end
end
end
%%
-------------------------------------------ISC-formula-------------------------------------------------for i=1:r_n-r_t+1
for j=1:c_n-c_t+1
isc_temp=0;
for i1=1:r_t
for j1=1:c_t
isc_temp = isc_temp+((template_isc(i1,j1)*figure_isc(i1+i-1,j1+j-1))+((1-figure_isc(i1+i1,j1+j-1))*(1-template_isc(i1,j1))));
end
end
isc(i,j)=isc_temp/(r_t*c_t);
end
end
%% ------------------------------Location finding and making ractangular boundary----------------------max_val=max(max(isc));
[y,x]=find(isc ==(max_val));
figure;imshow(uint8(n_image));hold on;
rectangle('Position',[x,y,c_t,r_t],'LineWidth',2,'LineStyle','--','EdgeColor','r');

Template detected Output Images with Noise with Input

Image and Template Image:

Figure 13 Template Detected


Output Image with Impulse
Noise

Figure 14 Template Detected


Output Image with Poisson
Noise

Figure 15 Template Detected


Output Image with Gaussian
Noise

Figure 18 Template
Image
Figure 16 Original Input Image

Figure 17 Image with Black


spot

Conclusion of Experiment No. 5:


By performing this practical we conclude that using ISC method, we can detect the shape/object
even from a clustered background easily with effectively. It also perform well in presence of noisy
environment.

Experiment 6

AIM:

Write a MATLAB Program to detect and Count the teeth of a gear in


given input image.

Short Description:
Following are the steps which is being implemented in this practical.

Read input image

Convert to black and white

Apply morphological operation to remove noise

Find boundary of object

Find the center location

Find Euclidean distance

Find peak from Euclidean plot

Count number of peaks

Display the result

Generalized MATLAB Code to Detect & Count teeth of Gear:


clc; clear all; close all;
%% --------------------------------------------Read in the image------------------------------------------------gearImage = imread('gear.jpg');
figure,imshow(gearImage);
%% ---------------------------------Convert to grayscale and threshold--------------------------------------gearGray = rgb2gray(gearImage);
gearBW = gearGray > 105;
figure,imshow(gearBW);
%% -----------------------------Remove the small spots Clean up the image.-------------------------------gearBW = bwareaopen(gearBW, 20);
figure,imshow(gearBW);
%% ---------------------------------------------Fill in the holes -------------------------------------------------gearBW = imfill(gearBW, 'holes');
figure,imshow(gearBW);
%% ---------------------------------Find the circle that encloses the gear------------------------------------rp = regionprops(double(gearBW), 'all');
xy = rp.ConvexHull;
line(xy(:,1),xy(:,2),'Color','yellow','LineWidth',2)
%% ---------------------------------Shrink the circle to expose the gears-------------------------------------[r,c] = size(gearBW);
mask = poly2mask(xy(:,1), xy(:,2), r, c);
maskEroded = imerode(mask, ones(16));
rp = regionprops(double(maskEroded), 'all');
xy = rp.ConvexHull;
line(xy(:,1),xy(:,2),'Color','red','LineWidth',2)
%% ----------------------------------------------Subtract the hub------------------------------------------------teeth = gearBW;
teeth(maskEroded) = 0;
figure,imshow(teeth);
%% -----------------------------------------Label and count the teeth------------------------------------------[teethLabel, numTeeth] = bwlabel(teeth);
figure,imshow(label2rgb(teethLabel, @jet));
numTeeth

Detected Teeth Output Image with Input Image and some

intermediate Images:

Figure 19 Original Input Image

Figure 20 Binary Image

Figure 21 Filtered clean Image

Figure 22 Show circles that


closes gear

Figure 23 Teeth Detected


Image

Figure 24 Output with Counted


teeth

numTeeth = 40

Conclusion of Experiment No. 6:


By performing this practical we conclude that using Matlab, we get precise number of teeth from
any input image.

Experiment 7

AIM: Write a MATLAB program to detect character from an input image.

Short Description on Character Detection:


Following are the steps which is being implemented in this practical.

Read input image

Convert to black and white

Apply morphological operation to remove noise

Find boundary of object

Low Pass Filtering

Region Filling

Label Each Regions

Bounding Box

Display the result

Generalized MATLAB Code for Detection of Character:

%% --------------------------------------CREATE TEMPLATES----------------------------------------------%% -------------------------------------------------Letter---------------------------------------------------------A=imread('letters_numbers\A.bmp');B=imread('letters_numbers\B.bmp');


C=imread('letters_numbers\C.bmp');D=imread('letters_numbers\D.bmp');
E=imread('letters_numbers\E.bmp');F=imread('letters_numbers\F.bmp');
G=imread('letters_numbers\G.bmp');H=imread('letters_numbers\H.bmp');
I=imread('letters_numbers\I.bmp');J=imread('letters_numbers\J.bmp');
K=imread('letters_numbers\K.bmp');L=imread('letters_numbers\L.bmp');
M=imread('letters_numbers\M.bmp');N=imread('letters_numbers\N.bmp');
O=imread('letters_numbers\O.bmp');P=imread('letters_numbers\P.bmp');
Q=imread('letters_numbers\Q.bmp');R=imread('letters_numbers\R.bmp');
S=imread('letters_numbers\S.bmp');T=imread('letters_numbers\T.bmp');
U=imread('letters_numbers\U.bmp');V=imread('letters_numbers\V.bmp');
W=imread('letters_numbers\W.bmp');X=imread('letters_numbers\X.bmp');
Y=imread('letters_numbers\Y.bmp');Z=imread('letters_numbers\Z.bmp');
%% -----------------------------------------------Number--------------------------------------------------------one=imread('letters_numbers\1.bmp'); two=imread('letters_numbers\2.bmp');
three=imread('letters_numbers\3.bmp');four=imread('letters_numbers\4.bmp');
five=imread('letters_numbers\5.bmp'); six=imread('letters_numbers\6.bmp');
seven=imread('letters_numbers\7.bmp');eight=imread('letters_numbers\8.bmp');
nine=imread('letters_numbers\9.bmp'); zero=imread('letters_numbers\0.bmp');
%*-*-*-*-*-*-*-*-*-*-*letter=[A B C D E F G H I J K L M...
N O P Q R S T U V W X Y Z];
number=[one two three four five...
six seven eight nine zero];
character=[letter number];
templates=mat2cell(character,42,[24 24 24 24 24 24 24 ...
24 24 24 24 24 24 24 ...
24 24 24 24 24 24 24 ...
24 24 24 24 24 24 24 ...
24 24 24 24 24 24 24 24]);
save ('templates','templates')

function [fl re]=lines(im_texto)


im_texto=clip(im_texto);
num_filas=size(im_texto,1);
for s=1:num_filas
if sum(im_texto(s,:))==0
nm=im_texto(1:s-1, :); % First line matrix
rm=im_texto(s:end, :);% Remain line matrix
fl = clip(nm);
re=clip(rm);

break
else
fl=im_texto;%Only one line.
re=[ ];
end
end

function img_out=clip(img_in)
[f c]=find(img_in);
img_out=img_in(min(f):max(f),min(c):max(c));%Crops image

function letter=read_letter(imagn,num_letras)
global templates
comp=[ ];
for n=1:num_letras
sem=corr2(templates{1,n},imagn);
comp=[comp sem];
end
vd=find(comp==max(comp));
%*-*-*-*-*-*-*-*-*-*-*-*-*if vd==1
letter='A';
elseif vd==2
letter='B';
elseif vd==3
letter='C';
elseif vd==4
letter='D';
elseif vd==5
letter='E';
elseif vd==6
letter='F';
elseif vd==7
letter='G';
elseif vd==8
letter='H';
elseif vd==9
letter='I';
elseif vd==10
letter='J';
elseif vd==11
letter='K';
elseif vd==12
letter='L';

elseif vd==13
letter='M';
elseif vd==14
letter='N';
elseif vd==15
letter='O';
elseif vd==16
letter='P';
elseif vd==17
letter='Q';
elseif vd==18
letter='R';
elseif vd==19
letter='S';
elseif vd==20
letter='T';
elseif vd==21
letter='U';
elseif vd==22
letter='V';
elseif vd==23
letter='W';
elseif vd==24
letter='X';
elseif vd==25
letter='Y';
elseif vd==26
letter='Z';
%*-*-*-*-*
elseif vd==27
letter='1';
elseif vd==28
letter='2';
elseif vd==29
letter='3';
elseif vd==30
letter='4';
elseif vd==31
letter='5';
elseif vd==32
letter='6';
elseif vd==33
letter='7';
elseif vd==34
letter='8';
elseif vd==35

letter='9';
else
letter='0';
end

clc, close all, clear all


% Clear all
imagen=imread('TEST_1.jpg');
% Read image
imshow(imagen);
% Show image
title('INPUT IMAGE WITH NOISE')
if size(imagen,3)==3 %RGB image
% Convert to gray scale
imagen=rgb2gray(imagen);
end
threshold = graythresh(imagen);
% Convert to BW
imagen =~im2bw(imagen,threshold);
imagen = bwareaopen(imagen,30);
% Remove all object containing fewer than 30 pixels
word=[ ];
%Storage matrix word from image
re=imagen;
fid = fopen('text.txt', 'wt');
%Opens text.txt as file for write
load templates
% Load templates
global templates
num_letras=size(templates,2);
% Compute the number of letters in template file
while 1
[fl re]=lines(re);
%Fcn 'lines' separate lines in text
imgn=fl;
[L Ne] = bwlabel(imgn);
for n=1:Ne
[r,c] = find(L==n);
n1=imgn(min(r):max(r),min(c):max(c));
% Extract letter
img_r=imresize(n1,[42 24]);
% Resize letter (same size of template)
letter=read_letter(img_r,num_letras);
word=[word letter];
% Letter concatenation
end
%fprintf(fid,'%s\n',lower(word));%Write 'word' in text file (lower)
fprintf(fid,'%s\n',word);%Write 'word' in text file (upper)
word=[ ];
% Clear 'word' variable
if isempty(re) %See variable 're' in Fcn 'lines' %*When the sentences finish, breaks the loop
break
end
end
fclose(fid);
winopen('text.txt')
%Open 'text.txt' file

Output Image & Input Images:

Figure 25 Input Image test 1

Figure 26 Input Image test 2

Figure 28 Output Image test 1 Figure 29 Output Image test 2

Figure 27 Input Image test 3

Figure 30 Output Image test 3

Conclusion of Experiment No. 7:


By performing this practical we can detect the character from an image by just following the steps
including some morphological operators. This algorithm fails when characters are too closed and it
depends on the size and shape of structuring element.

Experiment 8

AIM:

Write a MATLAB program to compute area of circular object given in


the input image.

Short Description on Object detection:


Following are the steps which is being implemented in this practical.

Read input image

Convert to black and white

Apply morphological operation to remove noise

Find boundary of object

Low Pass Filtering

Find Region Property

Label Each Regions

Average Area of all Object

Display the result

Generalized MATLAB Code to Compute Area of Circular


Objects given in Image :
clc; close all; clear all;
I=imread('tablet.png');
thresh=graythresh(I);
BW=im2bw(I,thresh);
K = medfilt2(BW);
imshow(K);
SE = strel('disk',4);
SE1 = strel('disk',9);
BW1 = imerode(BW,SE);
bw1=imdilate(BW1,SE1);
figure,imshow(BW1),title('Character Detected'); % Dilation (LPF)
hold on;
bwAreaOpenBW = bwareaopen(BW1,200);
figure, imshow(bwAreaOpenBW);
figure, imshow(I);
hold on;
[L, count] =bwlabel(bwAreaOpenBW);
stats = regionprops(L,'all');
stats(count); % Labeling
allArea = [stats.Area];
Area1=0;
for i=1:count
Area1=Area1 + allArea(1,i);
end
Area=round(Area1/count)
allMajorAxisLength = [stats. MajorAxisLength];
dia1=0;
for i=1:count
dia1=dia1 + allMajorAxisLength(1,i);
end
dia=round(dia1/count)
for i=1:count
rectangle('Position',stats(i,1).BoundingBox,'LineWidth',2,'LineStyle','-','EdgeColor','r');
end

Input Image & Output Image with some intermediate Images

Figure 31 Binary of Input Image


Character Detected

Figure 32 Area Opened Image

Figure 33 Noise Removed Image

Figure 34 Object Detected output Image

Diameter: 76.43
Radius: 38.22
Area: 4587

Conclusion of Experiment No. 8:


By using regionprops property we can easily find the area of the desired portion of the image also
incorporating morphological operators.

erimentExperiment 9

AIM:

Write a MATLAB program to Stitch two images and generate


panoramic image from the given two images.

Short Description on Stitching two images:

Read input image

Convert to Same Size

Take a Small Part of Image 2 for Comparison

Compare with Image 1

First Row wise compare

Second Column Wise

Stitch Both image at That Point

Display the result

Following are the steps which is being implemented in this practical.

Generalized MATLAB Code to Stitch Two Images and


Generate Panoramic Image:
clc; close all;
In_Im_1=imread('s11.png');
In_Im_2=imread('s22.png');
Im_1=In_Im_1(:,:,1);
[m,n]=size(Im_1);
Im_2=In_Im_2(:,:,1);
Im_2=imresize(Im_2,[m,n]);
figure,imshow(In_Im_1);
figure,imshow(In_Im_2);
figure,imshow(Im_1);

figure,imshow(Im_2);
Im_2_part=Im_2(1:50,1:50);
for q=n-50:-1:n/2
SAD=0;
for i=1:50
for j=1:50
SAD=SAD+abs(double(Im_1(i,q+j))-double(Im_2_part(i,j)));
end
end
SAD2(q)=SAD;
end
e=min(SAD2(n/2:n-50));
q=1:n-50;
figure,stem(q,SAD2);
z=find(SAD2==e);
for i=1:m
for j=1:z
timg(i,j)=(In_Im_1(i,j));
end
end
for i=1:m
for j=1:n
timg(i,z+j)=(In_Im_2(i,j));
end
end
figure,imshow(uint8(timg));

Input Image & Output Image with some intermediate

Image:

x 10

10

0
0

50

100

150

200

250

300

Conclusion of Experiment No. 9:


By scanning the two images horizontally by using SAD method we can successfully do the
mosaicing over the input images.

Experiment 10

AIM: Write a MATLAB program to detect touching objects and determine its
feature vector from an input image.

Short Description on Touching Objects Detection:

Generalized MATLAB Code to Detect Touching Objects from


an Input Image :
clc; close all;
I=imread('afmsurf.bmp');
figure,imshow(I),title('Original Image');
se = strel('disk',12);
J = imtophat(I,se);
figure,imshow(J),title('Tophat');
K = imadjust(J);
S = imsubtract(imadd(I,imtophat(I,se)), imbothat(I,se));
figure,imshow(S),title('Subtracted(Top-Bottom)')
J = imcomplement(S);
figure,imshow(J),title('Complement')
BW = imextendedmin(J,21);
figure,imshow(BW),title('Extended Min Image')
Z=imimposemin(J,BW);
figure,imshow(Z),title('Imposed Image');
W=watershed(Z);
figure,imshow(W),title('Watershed Image');
T = bwlabel(W);
RGB = label2rgb(T);
figure,imshow(RGB),title('RGB');
[C, count] =bwlabel(W);
stats = regionprops(C,'all');
stats(23); % Labeling

Input Image & Output Image with Intermediate Images:

Figure 35 Original Input Image

Figure 36 Mask Image

Figure 38 Complement Image Figure 39 Minimum Area Image

Figure 41 Final Image

Figure 37 Subtracted Image

Figure 40 Combined Image

Figure 42 Image with Region Counted

No. of Regions are : 72

Conclusion of Experiment No. 10:


By performing this practical we able to find out the number of touching objects from an given
input image and also we can extract the different features from it using regionprops property.

S-ar putea să vă placă și