You are on page 1of 41

ECE Kamaraj college of Engineering& Technology VNR

IMAGE PROCESSING INTRODUCTION


1. READING A IMAGE AND CARRYING OUT ALL BASIC CONVERSION
OPERATION
%// to clear a window in the command prompt
clc;
close all;
% // Reading a Image
a=imread('cameraman.tif');
imshow(a),pixval on;
title('Cameraman image');
figure;
% // Reading a image from folder
b=imread('D:\myimages\lena.bmp');
imshow(b);
title('Lena image');
figure;
%// adjust the display of the given image
subplot(1,2,1);
imshow(a);
title('Original cameraman image');
subplot(1,2,2);
h=imshow(a,[0 80]);
title('Adjust image of a cameraman');
%// resize the original image
a=ind2gray(a,gray(256));
a=a(1:256,1:256);
f1=imresize(a,0.2);
% Downsample to a 1/5th of the size
subplot(1,3,3);
imshow(f1);
title('resized image - downsample to a 1/5th of the size');
%// conversion of an image into RGB format
% To convert an image into RGB format by increasing the colour resolution
% apparently by dithering.
BW=dither(a);
figure,
subplot(121),imshow(a);
title('Original cameraman image');
subplot(122),imshow(BW);
title('Conversion of cameraman image into RGB format using dither function');
% // to find the size of the image
cc=size(a);
disp('the size of the cameraman image')
disp(cc);
disp('the number of gray levels present in the cameramanimage')
dd=size(unique(a));
Workshop on Image and Video Processing- A Practical Approach
1

ECE Kamaraj college of Engineering& Technology VNR


disp(dd);
%// listing all values along a particular dimension
c=a(100,200,:);
d=b(100,200,:);
disp(' pixel value for 100,200 in cameraman image');
disp(c);
disp(' pixel value for 100,200 in lena image');
disp(d);
%// information about your image
e=imfinfo('cameraman.tif');
f=imfinfo('D:\myimages\lena.bmp');
%// different data types and conversions
aa=23;
bb=uint8(aa);
disp('data conversion from double array to uint8');
disp(bb);
%// Grayscale images transformed into sequence of binary images- Bit plane
cd=double(a);
c0=mod(cd,2);
c1=mod(floor(cd/2),2);
c2=mod(floor(cd/4),2);
c3=mod(floor(cd/8),2);
c4=mod(floor(cd/16),2);
c5=mod(floor(cd/32),2);
c6=mod(floor(cd/64),2);
c7=mod(floor(cd/128),2);
figure(4);
title('Grayscale images transformed into sequence of binary images- Bit plane')
subplot(3,3,1);imshow(a);title('original cameraman image');
subplot(3,3,2);imshow(c0);title('mod of 2 of given image')
subplot(3,3,3);imshow(c1);title('mod of floor 2 of given image')
subplot(3,3,4);imshow(c2);title('mod of floor 4 of given image')
subplot(3,3,5);imshow(c3);title('mod of floor 8 of given image')
subplot(3,3,6);imshow(c4);title('mod of floor 16 of given image')
subplot(3,3,7);imshow(c5);title('mod of floor 32 of given image')
subplot(3,3,8);imshow(c6);title('mod of floor 64 of given image')
subplot(3,3,9);imshow(c7);title('mod of floor 128 of given image')

2. READING A IMAGE AND INCREASING THE CONTRAST LEVEL, FINDING


THE THRESHOLD VALUE
clc;
close all;
clear all;
%Read Image
%Read and display the grayscale image rice.png.
I = imread('rice.png');
Workshop on Image and Video Processing- A Practical Approach
2

ECE Kamaraj college of Engineering& Technology VNR


subplot(2,2,1);
imshow(I);
title('original Rice.tif image');
%Use Morphological Opening to Estimate the Background
background = imopen(I,strel('disk',15));
%Subtract the Background Image from the Original Image
I2 = I - background;
subplot(2,2,2);
imshow(I2);
title(' Subtract the Background Image from the Original Image');
%Increase the Image Contrast
I3 = imadjust(I2);
subplot(2,2,3);
imshow(I3);
title(' Increase the Image Contrast');
%Threshold the Image
level = graythresh(I3);
bw = im2bw(I3,level);
bw = bwareaopen(bw, 50);
subplot(2,2,4);
imshow(bw);
title(' Threshold the Image');
3. IMAGE QUANTIZATION
% Image quality strongly depends on the number of bits used for coding grey levels.
%This is called image quantization.
% With the following example these concepts should become clear.
clc;
clear all;
f=imread('cameraman.tif');
imshow(f); colormap(gray);title('original image of cameraman'); figure;
imshow(f); colormap(gray(32)); title('cameraman image for gray(32)');figure;
imshow(f);colormap(gray(4)); title('cameraman image for gray(4)'); figure;
imshow(f);colormap(jet(16)); title('cameraman image for jet(4)');% False color
4. DIFFERENCE IN USING IMSHOW AND IMVIEW USING LABEL2RGB
%//LABEL2RGB converts label matrix to RGB image.
%// difference in using imshow and imview
%// LABEL2RGB If ORDER is 'shuffle', then colormap colors are pseudo randomly
shuffled.
I = imread('rice.png');
subplot(1,3,1);
imshow(I)
title('original rice.tif image');
BW = im2bw(I, graythresh(I));
L = bwlabel(BW);
Workshop on Image and Video Processing- A Practical Approach
3

ECE Kamaraj college of Engineering& Technology VNR


RGB = label2rgb(L);
%//If ORDER is 'shuffle', then colormap colors are pseudorandomly shuffled.
RGB2 = label2rgb(L, 'spring', 'c', 'shuffle');
subplot(1,3,2);
imshow(RGB);
title('label matrix to RGB image');
subplot(1,3,3);
imshow(RGB2);
title('label matrix to RGB image - shuffle');
imview(RGB);
imview(RGB2);
imview(I);
5. CALLING A FUNCTION AND WRITING A PROGRAM FOR MEDIAN FILTER
USING NLFILTER
close all;
clc;
clear all;
%// NLFILTER Perform general sliding-neighborhood operations.
A = imread('cameraman.tif');
fun = inline('median(x(:))');
B = nlfilter(A,[3 3],fun);
imshow(B);
%//MYFUN is an M-file containing
%// function syntax
%// function [output_parameter_list] = function_name(input_parameter_list)
function scalar = myfun(x)
scalar = median(x(:));
6. PROGRAM FOR ADD, SUBTRACT, MULTIPLY, DIVIDE, ROTATE, CROP,
ADJUST, COMPLEMENT AND STRETCHING OF AN IMAGE.
clc;
clear all;
close all;
%// subtraction and addtion
b=imread('rice.png');
b1=b+128;
b1=uint8(double(b)+128);
b1=imadd(b,128);
b2=imsubtract(b,128);
figure;
subplot(4,4,1);
imshow(b);
title('Original rice.tif image');
subplot(4,4,2);
imshow(b1);
title('using uint8 and imadd');
Workshop on Image and Video Processing- A Practical Approach
4

ECE Kamaraj college of Engineering& Technology VNR


subplot(4,4,3);
imshow(b2);
title('imsubtract of given image');
%// y=x/2;
b3=immultiply(b,0.5);
b31=imdivide(b,2);
subplot(4,4,4);
imshow(b3);
title('immultiply of y=x/2 given image');
subplot(4,4,5);
imshow(b31);
title('imdivide of y=x/2 given image');
%// y=2x
b4=immultiply(b,2);
%// y = x/2 +128
b5 = imadd(immultiply(b,0.5),128);
b51=imadd(imdivide(b,2),128);
subplot(4,4,6);
imshow(b5);
title('imadd of immultiply y=2x given image');
subplot(4,4,7);
imshow(b51);
title('imadd of imdivide y=2x given image');
%// image complement
bc=imcomplement(b);
subplot(4,4,8);
imshow(bc);
title('complement of the given image');
% Add two images together and specify an output class.
J = imread('cameraman.tif');
K = imadd(b,J,'uint16');
subplot(4,4,9);
imshow(K,[]);
title('adding two images image');
% Add a constant to an image.
J1 = imadd(b,50);
subplot(4,4,10);
imshow(J1);
title('adding two images image');
% Estimate and subtract the background of an image:
background = imopen(b,strel('disk',15));
Ip = imsubtract(b,background);
subplot(4,4,11);
imshow(Ip,[]);
title('Estimate and subtract the background of an image');
% Subtract a constant value from an image:
Iq = imsubtract(b,50);
subplot(4,4,12);
Workshop on Image and Video Processing- A Practical Approach
5

ECE Kamaraj college of Engineering& Technology VNR


imshow(Iq);
title('Subtract a constant value from an image');
%// stretching an image
%//stretchlim computes [low hight] to be mapped into [bottom top]
I3 = imadjust(b, stretchlim(b), [0 1]);
subplot(4,4,13);
imshow(I3);
title('stretching an image');
%// rotation of an image
J6 = imrotate(b,35,'bilinear');
subplot(4,4,13);
imshow(J6);
title('rotation of an image');
%// adjusting an image
I31 = imadjust(b, stretchlim(b), [0 1]);
subplot(4,4,14);
imshow(I31);
title('adjusting an image');
%// Display the absolute difference between a filtered image and the original.
J5 = uint8(filter2(fspecial('gaussian'), b));
K = imabsdiff(b,J5);
subplot(4,4,15);
imshow(K,[]);
title('absolute difference between a filtered image and the original');
%// cropping an image
I21 = imcrop(J,[75 68 130 112]);
subplot(4,4,16);
imshow(I21);
title('cropping a cameraman image');

Workshop on Image and Video Processing- A Practical Approach


6

ECE Kamaraj college of Engineering& Technology VNR

IMAGE ENHANCEMENT :
1.CONVOLUTION OPERATION INVOLVING IMAGES:
clc;
clear all:
close all;
I = imread('cameraman.tif');
h = [1 0 1; 1 0 1; 1 0 1];
y=conv2(I,h);
figure,subplot(121),imshow(I,'notruesize'),title('original'):
subplot(122),imshow((unit8(y),notruesize),title(image after convolution);
2. MEDIAN FILTERING:
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.03);
K = medfilt2(J);
figure,subplot(311),imshow(I),title('original')
subplot(312),imshow(J),title('original mixed with salt and pepper noise'),
subplot(313),imshow(K),title('median filtered image')
3. IMAGE FILTERING:
clc; clear all; close all;
I = imread('cameraman.tif');
h1=[1 1 1; 1 1 1; 1 1 1]/9;
y1=imfilter(I,h1);
figure, subplot(121),imshow(I,'notruesize'),
title('original');
subplot(122), imshow(uint8(y1),'notruesize'),
title('Image after filtering');
4. CONTRAST ENHANCEMENT OF AN IMAGE:
I = imread('cameraman.tif');
J = histeq(I);
figure,subplot(121),imshow(I)
subplot(122),imshow(J)
5. PROGRAM USING IMADJUST
I = imread('cameraman.tif');
J = imadjust(I); figure, subplot(121),imshow(I)
Workshop on Image and Video Processing- A Practical Approach
7

ECE Kamaraj college of Engineering& Technology VNR


subplot(122),imshow(J)
6. IMAGE I/O
%display an image from a file
imshow('board.tif')
%diaplay an indexed image
[x, map]= imread('trees.tif');
imshow(x,map)
%display a greyscale image
I = imread('cameraman.tif');
imshow(I)
%display a greyscale image, adjust the display
%range
h = imshow(I,[0 80]);
7. CONVERSION OF A GRAYSCALE IMAGE INTO AN INDEXED IMAGE
I = imread('cameraman.tif');
[x, map] = gray2ind(I,8);
figure,subplot(121),imshow(I),
subplot(122),imshow(x,map);
8. CONVERSION OF AN RGB IMAGE TO GRAY IMAGE
I =imread('board.tif');
J =rgb2gray(I);
figure, subplot(121),imshow (I),subplot(122), imshow(J);

9. CONVERSION OF AN IMAGE INTO RGB FORMAT:


I = imread('cameraman.tif');
BW = dither(I);
figure,
subplot(211),imshow(I);
subplot(212),imshow(BW)

Workshop on Image and Video Processing- A Practical Approach


8

ECE Kamaraj college of Engineering& Technology VNR


MATLAB CODING FOR IMAGE RESTORATION:
PROGRAM-1
clc;
clear all;
close all;
%displaying original image
t=imread('cameraman.tif');
imshow(t);title('original image');
figure
%SALT & PEPPER NOISE(default-10%)
t_sp=imnoise(t,'salt & pepper');
imshow(t_sp);title('salt & pepper noise added image');
figure
%SALT & PEPPER NOISE(20% noise added)
t_sp_1=imnoise(t,'salt & pepper',0.2);
imshow(t_sp_1);title('with 20% salt & pepper noise added image');
figure
%GAUSSIAN NOISE
t_ga=imnoise(t,'gaussian');
imshow(t_ga);title('image with gaussian noise');
figure
%SPECKLE NOISE
t_spk=imnoise(t,'speckle');
imshow(t_spk);title('image with speckle noise');
figure;
%PERIODIC NOISE
s=size(t);
[x,y]=meshgrid(1:s(1),1:s(2));
p=sin(x/3+y/5)+1;
t_pn=(im2double(t)+p/2)/2;
imshow(t_pn);title('image with periodic noise');
figure
%CLEANING SALT & PEPPER NOISE
%1)using MEDIAN filtering
t_sp_m3=medfilt2(t_sp);
imshow(t_sp_m3);title('noise cleared image using median filter 3x3');
figure
t_sp2=imnoise(t,'salt & pepper',0.2);
imshow(t_sp2);title('with 20% salt & pepper noise added image');
figure
t_sp2_m3=medfilt2(t_sp2);
imshow(t_sp2_m3);title('noise cleared image using median filter 3x3 with 20% salt & pepper
noise');
figure
%5x5 medain filtering
t_sp2_m5=medfilt2(t_sp2,[5,5]);
imshow(t_sp2_m5);title('noise cleared image using median filter 5x5 with 20% salt & pepper
noise');
Workshop on Image and Video Processing- A Practical Approach
9

ECE Kamaraj college of Engineering& Technology VNR


figure;
%2)RANK-ORDER FILTERING
i=ordfilt2(t_sp,3,[0 1 0;1 1 1;0 1 0]);
imshow(i);title('noise cleared image using rank-order filter with 10% salt & pepper noise');
figure;
%Adaptive Filtering
t1=wiener2(t_ga);imshow(t1);title('noise cleared by 3x3 wiener filter');figure;
t2=wiener2(t_ga,[5,5]);imshow(t2);title('noise cleared by 5x5 wiener filter');figure;
t3=wiener2(t_ga,[7,7]);imshow(t3);title('noise cleared by 7x7 wiener filter');figure;
t4=wiener2(t_ga,[9,9]);imshow(t4);title('noise cleared by 9x9 wiener filter');figure;
t2=imnoise(t,'gaussian',0,0.005);
imshow(t2);title('image affected by 0.5% gaussian noise');figure;
t2w=wiener2(t2,[7,7]);
imshow(t2w);title('0.5% gaussian noise cleared by 7x7 wiener filter');
PROGRAM-2:
%Deblurring with the Wiener Filter
clc;
clear all;
close all;
I = imread('peppers.png');
% I = I(10+[1:256],222+[1:256],:);
figure;
imshow(I);
title('Original Image');
LEN = 31;
THETA = 11;
PSF = fspecial('motion',LEN,THETA);
Blurred = imfilter(I,PSF,'circular','conv');
figure;
imshow(Blurred);
title('Blurred Image');
wnr1 = deconvwnr(Blurred,PSF);
figure;
imshow(wnr1);
title('Restored, True PSF');
PROGRAM-3:
% Deblurring with a Regularized Filter
I = imread('tissue.png');
I = I(125+[1:256],1:256,:);
figure;
imshow(I);
title('Original Image');
PSF = fspecial('gaussian',11,5);
Blurred = imfilter(I,PSF,'conv');
Workshop on Image and Video Processing- A Practical Approach
10

ECE Kamaraj college of Engineering& Technology VNR


V = .02;
BlurredNoisy = imnoise(Blurred,'gaussian',0,V);
figure;
imshow(BlurredNoisy);
title('Blurred and Noisy Image');
NP = V*prod(size(I));
[reg1 LAGRA] = deconvreg(BlurredNoisy,PSF,NP);
Figure;
imshow(reg1);
title('Restored Image');
PROGRAM-4:
%Deblurring with the Lucy-Richardson Algorithm
clc;
clear all;
close all;
I=imread('board.tif');
I=I(50+[1:256],2+[1:256],:);
figure;
imshow(I);
title('Original Image');
PSF = fspecial('gaussian',5,5);
Blurred = imfilter(I,PSF,'symmetric','conv');
V = .002;
BlurredNoisy=imnoise(Blurred,'gaussian',0,V);
figure;
imshow(BlurredNoisy);
title('Blurred and Noisy Image');
luc1=deconvlucy(BlurredNoisy,PSF,5);
figure;
imshow(luc1);
title('Restored Image');
PROGRAM-5:
% Deblurring with the Blind Deconvolution Algorithm
clc;
clear all;
close all;
I = imread('cameraman.tif');
figure;
imshow(I);
title('Original Image');
PSF = fspecial('motion',13,45);
figure;
imshow(PSF,[],'notruesize');
title('Original PSF');
Blurred = imfilter(I,PSF,'circ','conv');
Workshop on Image and Video Processing- A Practical Approach
11

ECE Kamaraj college of Engineering& Technology VNR


figure;
imshow(Blurred);
title('Blurred Image');
INITPSF = ones(size(PSF));
[J P]= deconvblind(Blurred,INITPSF,30);
figure;
imshow(J);
title('Restored Image');
figure;
imshow(P,[],'notruesize');
title('Restored PSF');
WEIGHT = edge(I,'sobel',.28);
se1 = strel('disk',1);
se2 = strel('line',13,45);
WEIGHT = ~imdilate(WEIGHT,[se1 se2]);
WEIGHT = padarray(WEIGHT(2:end-1,2:end-1),[2 2]);
figure;
imshow(WEIGHT);
title('Weight Array');

Workshop on Image and Video Processing- A Practical Approach


12

ECE Kamaraj college of Engineering& Technology VNR

IMAGE SEGMENTATION MATLAB CODES


1. EDGE OPERATOR
clc;
clear all;
close all;
% I=imread('cameraman.tif');
I=imread('moon.tif');
px=[-1 0 1;-1 0 1;-1 0 1];
%Highlight vertical edges
qx=filter2(px,I);
figure,imshow(qx/255);
py=px';
%Highlight Horizontal edges
qy=filter2(py,I);
figure,imshow(qy/255);
%Highlight all the edges
edge_p=sqrt(qx.^2+qy.^2);
figure,imshow(edge_p/255);
%Roberts edge operator by direct command
edge_r=edge(I,'roberts');
figure,imshow(edge_r);
E3=size(find(edge_r));
E3
%Prewitt edge operator by direct command
edge_p1=edge(I,'prewitt');
figure,imshow(edge_p1);
E4=size(find(edge_p1));
E4
%Sobel edge operator by direct command
edge_s=edge(I,'sobel');
figure,imshow(edge_s);
E5=size(find(edge_s));
E5
%canny edge operator by direct command
edge_c=edge(I,'canny');
figure,imshow(edge_c);
E6=size(find(edge_c));
E6
2. ZEROCROSSING
clc;
clear all;
Workshop on Image and Video Processing- A Practical Approach
13

ECE Kamaraj college of Engineering& Technology VNR


close all;
ic=imread('circuit.tif');
figure,imshow(ic);
%laplacian filter
S=fspecial('laplacian',0);
ic_S=filter2(S,ic);
l=fspecial('laplacian',0);
icz=edge(ic,'zerocross',S);
figure,imshow(icz);
%Zero Crossing
log=fspecial('log',13,2);
edge(ic,'zerocross',log);
figure,imshow(icz);
3. SINGLE THRESHOLDING
clc;
clear all;
close all;
%b=imread('C:\Documents and Settings\user\Desktop\DIP\image\lena.bmp');
b=imread('Cameraman.tif');
%b=imread('mri.tif');
imshow(b);
figure,imshow(b>125);
4. MULTIPLE THRESHOLDING
clc;
clear all;
close all;
[x,map]=imread('eight.tif');
s=[x,map];
imshow(s);
figure,imshow(s>50 & s<125);
5. ADAPTIVE THRESHOLDING
clc;
clear all;
close all;
%c=imread('cameraman.tif');
x=ones(256,1)*[1:256];
c2=double(c).*(x/2+50)+(1-double(c)).*x/2;
c3=uint8(255*mat2gray(c2));
figure,imshow(c3);
t=graythresh(c3);ct=im2bw(c3,t);
p1=c3(:,1:64);
p2=c3(:,65:128);
p3=c3(:,129:192);
p4=c3(:,193:256);
Workshop on Image and Video Processing- A Practical Approach
14

ECE Kamaraj college of Engineering& Technology VNR


figure,imshow(p1);
figure,imshow(p2);
figure,imshow(p3);
figure,imshow(p4);
g1=im2bw(p1,graythresh(p1));
g2=im2bw(p2,graythresh(p2));
g3=im2bw(p3,graythresh(p3));
g4=im2bw(p4,graythresh(p4));
figure, imshow([g1 g2 g3 g4])
6. GLOBAL THRESHOLDING
clc;
clear all;
close all;
img=imread('Cameraman.tif');
T0=10;
T=25;
thresh=globalthreshold(img,T,T0);
figure,imshow(b>125);
function thresh=globalthreshold(img,T,T0)
s=size(img);
numelem=s(1)*s(2);
imgfl=double(img);
Tlast=-T0;
while abs(T-Tlast)>T0
tmp=imgfl>T;
zeros1=sum(tmp(:));
zeros2=numelem-zeros1;
G1=tmp.*imgfl;
G2=(~tmp).*imgfl;
mu1=sum(G1(:))/zeros1;
mu2=sum(G2(:))/zeros2;
Tlast=T;
T=1/2*(mu1+mu2)
end
thresh=T;
7. HOUGH TRANSFORM
clc;
clear all;
close all;
c=imread('cameraman.tif');
hc=hough(c);
figure,imshow(mat2gray(hc)*1.5);
%to find maximum value of transform
max(hc(:))
% to find r and values corresponding to the maximum
Workshop on Image and Video Processing- A Practical Approach
15

ECE Kamaraj college of Engineering& Technology VNR


[r,theta]=find(hc==91)
r=138
theta=181
c2=imadd(imdivide(c,4),192);
figure,imshow(c2);
houghline(c2,r,theta);
[r,theta]=find(hc>80)
houghline(c,r(1),theta(1));
8. DILATION
clc;
clear all;
close all;
c=imread('cameraman.tif');
sq=ones(3,3);
td=imdilate(c,sq);
figure,imshow(c);
figure,imshow(td);
9. EROSION
clc;
clear all;
close all;
c=imread('cameraman.tif');
sq=ones(3,3);
td=imerode(c,sq);
figure,imshow(c);
figure,imshow(td);
10. OPENING AND CLOSING
clc;
clear all;
close all;
c=imread('cameraman.tif');
%Opening
e=strel('square',20);
f=imopen(c,e);
figure,imshow(f);
%Closing
f1=imclose(c,e);
figure,imshow(f1);
11. HIT-OR-MISS TRANSFORM
clc;
clear all;
close all;
Input=[0 0 0 0 0 0
Workshop on Image and Video Processing- A Practical Approach
16

ECE Kamaraj college of Engineering& Technology VNR


001100
011110
011110
001100
0 0 1 0 0 0]
S1=ones(6,6)
S2=[1 1 1 1 ;1 0 0 0 ;1 1 1 1]
Input_S1=imerode(Input,S1);
Input_S1
Input_S2=imerode(~Input,S2);
Input_S2
Output=Input_S1& Input_S2;
Output

Workshop on Image and Video Processing- A Practical Approach


17

ECE Kamaraj college of Engineering& Technology VNR


IMAGE COMPRESSION
Block diagram for the JPEG compression program
Read the RGB image using the command
IMREAD
[ 600 800 3 uint 8 ]
Convert the RGB to gray level by RGB2YCBCR

Resize the Y, CB, CR according to the sampling format


4 : 2 : 0 if not pad zeros

CB
( : , : , 2)

Y
(:,:,1)

CR
(: , : , 3 )

Select 8 8 block for processing


For each block perform the following.
1. Take 2D DCT using DET2
2. Quantize by Y table [luminance label]
3. Round it off.
Of 64 elements

1. Call function jpgdcbits


to find the maximum length
for encoding the DC
coefficients

1. Call function
jpgacbits

2. dcbitsy

2. acbitsy
+
Total = dcbitsy + acbitsy

Find the signal to noise ratios.


Find the cut of bits to represent the single pixel &
effect of compression
Workshop on ImageExperience
and Video the
ProcessingA Practical Approach
18

ECE Kamaraj college of Engineering& Technology VNR

Function Jpgdcbits
1. Find the level / run length using the
formula Round (log 2 (abs(dc)) + 0.5) + 1)

2. Refer the table to find the length

Bits returned

Function Jpgacbits
0. Arrange the remaining 63 AC
coefficients in the Zig Zag pattern by
calling the function ZigZag

Function ZigZag
Convert 2D ac
coefficients into 1D array

Return
1. Find the level / run length using the
formula Round (log 2 (abs(dc)) + 0.5) + 1)

2. Refer the table to find the length

Bits returned

Workshop on Image and Video Processing- A Practical Approach


19

ECE Kamaraj college of Engineering& Technology VNR

PROGRAM FOR COMPRESSING RGB IMAGE USING JPEG


clc;
close all;
clear all;
R=imread('C:\Documents and Settings\All Users\Documents\My Pictures\Sample
Pictures\water1.bmp');
N=8;
[height,width,depth]=size(R);
if (mod(height,N)~=0)
height=floor(height/N)*N;
elseif (mod(width,N)~=0)
height=floor(width/N)*N;
end
R1=R(1:height,1:width,:);
clear R;
R=R1;clear R1;
samplingformat='4:2:0'; % Sampling format
I=rgb2ycbcr(R);
Image=I(:,:,1);
cb=R(:,:,2);%,[height/2,width/2],'bicubic');
cr=R(:,:,3);%;,[height/2,width/2],'bicubic');
Q=[16 11 10 16 24 40 51 61 % qtable for luminance
12 12 14 19 26 58 60 55
14 13 16 24 40 57 69 56
14 17 22 29 51 87 80 62
18 22 37 56 68 109 103 77
24 35 55 64 81 104 113 92
49 64 78 87 103 121 120 101
72 92 95 9 112 100 103 99];
QC=[17 18 24 47 66 99 99 99
18 21 26 66 99 99 99 99 % qtable for crominance
24 26 56 99 99 99 99 99
47 66 99 99 99 99 99 99
99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99];
Ylu=zeros(N,N);XQI=zeros(height,width);Ycb=zeros(N,N);Ycr=zeros(N,N);
XCBI=zeros(height,width);
XCRI=zeros(height,width);
%Reshapeimage=imresize(Image,[512,512]);
dcbitsy=0;
acbitsy=0;
for m=1:N:height
Workshop on Image and Video Processing- A Practical Approach
20

ECE Kamaraj college of Engineering& Technology VNR


for n=1:N:width
t=(Image(m:m+N-1,n:n+N-1));%-128;
Ylu=dct2(t);
temp=round(Ylu./Q);
if n==1
DC=temp(1,1);
dcbitsy=dcbitsy+jpgdcbits(DC,'Y');
else
DC=temp(1,1)-DC; % differential encoding
dcbitsy=dcbitsy+jpgdcbits(DC,'Y');% Dc bits for luminance
DC=temp(1,1);
end
acbits=jpgacbits(temp,'Y');
acbitsy=acbitsy+acbits;% AC bits for luminance component.
XQI(m:m+N-1,n:n+N-1)=(idct2(temp.* Q));%+128;
end
end
ycomp=uint8(XQI);
dcbitscb=0;
dcbitscr=0;acbitscb=0;acbitscr=0;Acbitscb=0;Acbitscr=0;
for m=1:N:height
for n=1:N:width
t1=cb(m:m+N-1,n:n+N-1);%-128;
t2=cb(m:m+N-1,n:n+N-1);%-128;
Ycb=dct2(t1);Ycr=dct2(t2);
temp1=floor(Ycb./QC);
temp2=floor(Ycr./QC);
if n==1;
DC1=temp1(1,1);
DC2=temp2(1,1);
dcbitscb=dcbitscb+jpgdcbits(DC1,'C');
dcbitscr=dcbitscr+jpgdcbits(DC2,'C');
else
DC1=temp1(1,1)-DC1;
DC2=temp2(1,1)-DC2;
dcbitscb=dcbitscb+jpgdcbits(DC1,'C'); % Dc-chrominance blue
dcbitscr=dcbitscr+jpgdcbits(DC2,'C'); % Dc-chrominance red
DC1=temp1(1,1);DC2=temp2(1,1);
end
acbitscb=jpgacbits(temp1,'C');
acbitscr=jpgacbits(temp2,'C');
Acbitscb=Acbitscb+acbitscb;%Acbits chrominance-blue
Acbitscr=Acbitscr+acbitscr;%Ac bits chrominance-red
XCBI(m:m+N-1,n:n+N-1)=idct2(temp1.*QC);%+128;
XCRI(m:m+N-1,n:n+N-1)=idct2(temp2.*QC);%+128;
end
end
Totalbits=dcbitsy+acbitsy+dcbitscb+dcbitscr+Acbitscb+Acbitscr;
Workshop on Image and Video Processing- A Practical Approach
21

ECE Kamaraj college of Engineering& Technology VNR


Rd=uint8(XQI);
mse=std2(Image-Rd);
snr=20*log10(std2(Image)/mse);
imshow(Rd);
FUNCTION TO FIND NUMBER OF BITS FOR AC COEFFICIENTS JPGACBITS
function Bits=jpgacbits(x,c);
RLC=cell(1,15);
RLCy=cell(1,15);
RLCy{1}=int16([4 3 4 6 8 10 12 14 18 25 26]);
RLCy{2}=int16([5 8 10 13 16 22 23 24 25 26]);
RLCy{3}=int16([6 10 13 20 21 22 23 24 25 26]);
RLCy{4}=int16([7 11 14 20 21 22 23 24 25 26]);
RLCy{5}=int16([7 12 19 20 21 22 23 24 25 26]);
RLCy{6}=int16([8 12 19 20 21 22 23 24 25 26]);
RLCy{7}=int16([8 13 19 20 21 22 23 24 25 26]);
RLCy{8}=int16([9 13 19 20 21 22 23 24 25 26]);
RLCy{9}=int16([9 17 19 20 21 22 23 24 25 26]);
RLCy{10}=int16([10 18 19 20 21 22 23 24 25 26]);
RLCy{11}=int16([10 18 19 20 21 22 23 24 25 26]);
RLCy{12}=int16([10 18 19 20 21 22 23 24 25 26]);
RLCy{13}=int16([11 18 19 20 21 22 23 24 25 26]);
RLCy{14}=int16([12 18 19 20 21 22 23 24 25 26]);
RLCy{15}=int16([13 18 19 20 21 22 23 24 25 26]);
RLCy{16}=int16([12 18 19 20 21 22 23 24 25 26]);
RLCc=cell(1,15);
RLCc{1}=int16([2 3 5 7 9 12 15 23 24 25 26]);
RLCc{2}=int16([5 8 11 14 20 22 23 24 25 26]);
RLCc{3}=int16([6 9 13 15 21 22 23 24 25 26]);
RLCc{4}=int16([6 9 12 15 21 22 23 24 25 26]);
RLCc{5}=int16([6 10 14 20 21 22 23 24 25 26]);
RLCc{6}=int16([7 11 17 20 21 22 23 24 25 26]);
RLCc{7}=int16([8 12 19 20 21 22 23 24 25 26]);
RLCc{8}=int16([7 12 19 20 21 22 23 24 25 26]);
RLCc{9}=int16([8 14 19 20 21 22 23 24 25 26]);
RLCc{10}=int16([9 14 19 20 21 22 23 24 25 26]);
RLCc{11}=int16([9 14 19 20 21 22 23 24 25 26]);
RLCc{12}=int16([9 14 19 20 21 22 23 24 25 26]);
RLCc{13}=int16([9 18 19 20 21 22 23 24 25 26]);
RLCc{14}=int16([11 18 19 20 21 22 23 24 25 26]);
RLCc{15}=int16([13 18 19 20 21 22 23 24 25 26]);
RLCc{16}=int16([11 17 18 19 20 21 22 23 24 25 26]);
switch c
case 'Y'
RLC=RLCy;
Workshop on Image and Video Processing- A Practical Approach
22

ECE Kamaraj college of Engineering& Technology VNR


case 'C'
RLC=RLCc;
end
X1=zig(x);
k=2;count=0;Bits=double(0);
%L=length(zig);
while k<=64
if X1(k)==0
count=count+1;

if k==64
Bits=Bits+double(RLC{1}(1));
break;
end
else
if count==0
RL=count;
level=round(log2(abs(X1(k)))+0.5);
Bits=Bits+double(RLC{RL+1}(level+1));
elseif count>=1 && count<=15
RL=count;
level=round(log2(abs(X1(k)))+0.5);
Bits=Bits+double(RLC{RL+1}(level));
count=0;
else
Bits=Bits+double(RLC{1}(1));
count=count-16;
end
end
k=k+1;
end

FUNCTION TO FIND NUMBER OF BITS FOR DC COEFFICIENTS


function Bits=jpgdcbits(dc,c);
codey=int16([3 4 5 5 7 8 10 12 14 16 18 20]);
codec=int16([2 3 5 6 7 9 11 13 15 18 19 20]);
switch c
case 'Y'
codelength=codey;

case 'C'
codelength=codec;
end
if dc==0
Workshop on Image and Video Processing- A Practical Approach
23

ECE Kamaraj college of Engineering& Technology VNR


Bits=double(codelength(1));
else
Bits=double(codelength(round(log2(abs(dc))+0.5)+1));
end

FUNCTION FOR ZIG-ZAG SCANNING


function y=zig(x)
y(1)=x(1,1);y(2)=x(1,2);y(3)=x(2,1);y(4)=x(3,1);y(5)=x(2,2);
y(6)=x(1,3);y(7)=x(1,4);y(8)=x(2,3);
y(9)=x(3,2);y(10)=x(4,1);y(11)=x(5,1);y(12)=x(4,2);y(13)=x(3,3);
y(14)=x(2,4);y(15)=x(1,5);y(16)=x(1,6);
y(17)=x(2,5);y(18)=x(3,4);y(19)=x(4,3);y(20)=x(5,2);y(21)=x(6,1);
y(22)=x(7,1);y(23)=x(6,2);y(24)=x(5,3);
y(25)=x(4,4);y(26)=x(1,1);y(27)=x(2,6);y(28)=x(1,7);y(29)=x(1,8);
y(30)=x(2,7);y(31)=x(3,6);y(32)=x(4,5);
y(33)=x(5,4);y(34)=x(6,3);y(35)=x(7,2);y(36)=x(8,1);y(37)=x(8,2);
y(38)=x(7,3);y(39)=x(6,4);y(40)=x(5,5);
y(41)=x(4,6);y(42)=x(3,7);y(43)=x(2,8);y(44)=x(3,8);y(45)=x(4,7);
y(46)=x(5,7);y(47)=x(6,5);y(48)=x(7,4);
y(49)=x(8,3);y(50)=x(8,4);y(51)=x(7,5);y(52)=x(6,6);y(53)=x(5,7);
y(54)=x(4,8);y(55)=x(5,7);y(56)=x(6,7);
y(57)=x(7,6);y(58)=x(8,5);y(59)=x(8,6);y(60)=x(7,7);y(61)=x(6,8);
y(62)=x(7,8);y(63)=x(8,7);y(64)=x(8,8);

Program 1
%This program illustrates false contouring
clc
clear all
close all
a=imread('tigerpub.jpg');
imshow(a),title('original image')
%using 128 gray levels
figure,imshow(grayslice(a,128),gray(128)),
title('Image with 128 gray level')
%using 64 gray levels
figure,imshow(grayslice(a,64),gray(64)),
title('Image with 64 gray level')
%using 32 gray levels
figure,imshow(grayslice(a,32),gray(32)),
title('Image with 32 gray level')
%using 16 gray levels
figure,imshow(grayslice(a,16),gray(16)),
title('Image with 16 gray level')
%using 8 gray levels
figure,imshow(grayslice(a,8),gray(8)),
title('Image with 8 gray level')

Workshop on Image and Video Processing- A Practical Approach


24

ECE Kamaraj college of Engineering& Technology VNR


original image

Image with 128 gray level

Image with 32 gray level

Image with 8 gray level

Program 2
% Generating Walsh Basis function
clear all;
close all;
clc;
n=input('Enter the basis matrix dimension: ');
m=n;
for u=0:n-1
for v=0:n-1
for x=0:n-1
for y=0:n-1
powervalue=1;
sn=log2(n);
for i=0:sn-1
a=dec2bin(x,sn);
b=bin2dec(a(sn-i));
c=dec2bin(y,sn);
d=bin2dec(c(sn-i));
e=dec2bin(u,sn);
f=bin2dec(e(i+1));
e=dec2bin(v,sn);
a=bin2dec(e(i+1));
powervalue=powervalue*(-1)^(b*f+d*a);
end
basis{u+1,v+1}(x+1,y+1)=powervalue;
end
end

Workshop on Image and Video Processing- A Practical Approach


25

ECE Kamaraj college of Engineering& Technology VNR


end
end
mag=basis;
figure(1)
k=1;
for i=1:m
for j=1:n
subplot(m,n,k)
imshow(mag{i,j},256)
k=k+1;
end
end

Program 3
%Averaging filter
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\rose.jpg');
% Addition of noise to the input image
b=imnoise(a,'salt & pepper');
c=imnoise(a,'gaussian');
d=imnoise(a,'speckle');
% Defining 3x3 and 5x5 kernel
h1=1/9*ones(3,3);
h2=1/25*ones(5,5);
% Attempt to recover the image
b1=conv2(b,h1,'same');
b2=conv2(b,h2,'same');
c1=conv2(c,h1,'same');
c2=conv2(c,h2,'same');
d1=conv2(d,h1,'same');
d2=conv2(d,h2,'same');
%Displaying the result
figure,subplot(2,2,1),imshow(a),title('Original Image'),
subplot(2,2,2),imshow(b),title('Salt & Pepper noise'),
subplot(2,2,3),imshow(uint8(b1)),title('3 x 3 Averaging filter'),
subplot(2,2,4),imshow(uint8(b2)),title('5 x 5 Averaging filter')
%...........................
figure,subplot(2,2,1),imshow(a),title('Original Image'),
subplot(2,2,2),imshow(c),title('Gaussian noise'),
subplot(2,2,3),imshow(uint8(c1)),title('3 x 3 Averaging filter'),
subplot(2,2,4),imshow(uint8(c2)),title('5 x 5 Averaging filter'),
%..................

Workshop on Image and Video Processing- A Practical Approach


26

ECE Kamaraj college of Engineering& Technology VNR


figure,subplot(2,2,1),imshow(a),title('Original Image'),
subplot(2,2,2),imshow(d),title('Speckle noise'),
subplot(2,2,3),imshow(uint8(d1)),title('3 x 3 Averaging filter'),
subplot(2,2,4),imshow(uint8(d2)),title('5 x 5 Averaging filter'),

Original Image

Salt & Pepper noise

3 x 3 Averaging filter

5 x 5 Averaging filter

Program 4
%This code is used to Butterworth highpass filter
close all;
clear all;
clc;
im=imread('d:\work\hibiscus.tif');
fc=40;
n=1;
[co,ro] = size(im);
cx = round(co/2); % find the center of the image
cy = round (ro/2);
imf=fftshift(fft2(im));
H=zeros(co,ro);
for i = 1 : co
for j =1 : ro
d = (i-cx).^2 + (j-cy).^ 2;
if d ~= 0
H(i,j) = 1/(1+((fc*fc/d).^(2*n)));
end;
end;
end;
outf = imf .* H;
out = abs(ifft2(outf));
imshow(im),title('Original Image'),figure,imshow(uint8(out)),title('Highpass Filterd Image')
figure,imshow(H),title('2D View of H'),figure,surf(H),

Workshop on Image and Video Processing- A Practical Approach


27

ECE Kamaraj college of Engineering& Technology VNR


title('3D View of H')
Original Image

Highpass Filterd Image

Program 5
%unsharp masking
clc
clear all
close all
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\babyelephant.jpg');
h=fspecial('unsharp');
b=imfilter(a,h);
imshow(a),title('original image')
figure,imshow(b), title('Unsharp mask')
original image

Unsharp mask

Program 6
Workshop on Image and Video Processing- A Practical Approach
28

ECE Kamaraj college of Engineering& Technology VNR


%This code performs logarthmic transformation
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\crow.jpg');
L=255;
c=L/log10(1+L);
d=c*log10(1+double(a));
imshow(a),title('original image')
figure,imshow(uint8(d)),title('Log transformation image')
original image

Log transformation image

Program 7
% Motion Blur
close all;
clear all;
clc;
a = imread(horse.jpg');
a=rgb2gray(a);
H = fspecial('motion',10,25);
MotionBlur_a = imfilter(a,H,'replicate');
imshow(a),title('Original Image');
figure,imshow(MotionBlur_a),title('Motion Blurred Image');
Original Image

Motion Blurred Image

Workshop on Image and Video Processing- A Practical Approach


29

ECE Kamaraj college of Engineering& Technology VNR


Program 8
%This program is a wiener filter
close all;
clear all;
clc;
x = imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\flower2.jpg');
x=double(rgb2gray(x));
sigma = 50;
gamma = 1;
alpha = 1;% It indicates Wiener filter
[M N]=size(x);
h = ones(5,5)/25;
Freqa = fft2(x);
Freqh = fft2(h,M,N);
y = real(ifft2(Freqh.*Freqa))+25*randn(M,N);
Freqy = fft2(y);
Powy = abs(Freqy).^2/(M*N);
sFreqh = Freqh.*(abs(Freqh)>0)+1/gamma*(abs(Freqh)==0);
iFreqh = 1./sFreqh;
iFreqh = iFreqh.*(abs(Freqh)*gamma>1)...
+gamma*abs(sFreqh).*iFreqh.*(abs(sFreqh)*gamma<=1);
Powy = Powy.*(Powy>sigma^2)+sigma^2*(Powy<=sigma^2);
Freqg = iFreqh.*(Powy-sigma^2)./(Powy-(1-alpha)*sigma^2);
ResFreqa = Freqg.*Freqy;
Resa = real(ifft2(ResFreqa));
imshow(uint8(x)),title('Original Image')
figure,imshow(uint8(y)),title('Degraded Image')
figure,imshow(uint8(Resa)),title('Restored Image')

Original Image

Degraded Image

Restored Image

Workshop on Image and Video Processing- A Practical Approach


30

ECE Kamaraj college of Engineering& Technology VNR

Program 9
% This program computes the edges in the image
clear all;
close all;
clc;
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\dove1.jpg');
% a = rgb2gray(a);
b=edge(a,'roberts');
c=edge(a,'sobel');
d=edge(a,'prewitt');
e=edge(a,'log');
f=edge(a,'canny');
imshow(a),title('Original Image')
figure,imshow(b),title('Roberts')
figure,imshow(c),title('Sobel')
figure,imshow(d),title('Prewitt')
figure,imshow(e),title('Log')
figure,imshow(f),title('Canny')
Original Image

Prewitt

Roberts

Log

Sobel

Canny

Program 10
% Boundary detector
close all;
clear all;
clc;
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\morph2.bmp');
b=[0 1 0;1 1 1;0 1 0];
a1=imdilate(a,b);
a2=imerode(a,b);
a3=a-a2;
a4=a1-a;

Workshop on Image and Video Processing- A Practical Approach


31

ECE Kamaraj college of Engineering& Technology VNR


a5=a1-a2;
imshow(a),title('Original image')
figure,imshow(a1),title('Dilated image')
figure,imshow(a2),title('Eroded image')
figure,imshow(a3),title('First property ')
figure,imshow(a4),title('Second property')
figure,imshow(a5),title('Third Property')
Original image

Dilated image

Eroded image
Third
Property
Second
property
First property

Program 11
% Colour filtering
clc;
close all;
clear all;
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\sunflower2.jpg');
yiq=rgb2ntsc(a);
%Extract the Y component alone
b1=yiq(:,:,1);
h=[-1 -1 -1;-1 8 -1;-1 -1 -1];
%Perform high pass filtering only on Y component
c1=conv2(b1,h,'same');
yiq(:,:,1)=c1;
% Convert YIQ to RGB format
a1=ntsc2rgb(yiq);
figure,imshow(a),title('original image')
figure,imshow(a1),title('High pass filtered image')

Workshop on Image and Video Processing- A Practical Approach


32

ECE Kamaraj college of Engineering& Technology VNR


original image
High pass filtered image

Program 12
% Color image segmentation
clc
clear all
close all
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\Tomato2.jpg');
%Conversion of RGB to YCbCr
b=rgb2ycbcr(a);
%Threshold is applied only to Cb component
mask=b(:,:,2)>120;
imshow(a),title('original image')
figure,imshow(mask),title('Segmented image')
original image

Segmented image

Program 13
% Separating RGB components

Workshop on Image and Video Processing- A Practical Approach


33

ECE Kamaraj college of Engineering& Technology VNR


clc;
close all;
clear all;
RGB=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\mixedfruit.bmp');
R=RGB;
G=RGB;
B=RGB;
R(:,:,2)=0;
R(:,:,3)=0;
G(:,:,1)=0;
G(:,:,3)=0;
B(:,:,1)=0;
B(:,:,2)=0;
subplot(2,2,1),imshow(RGB),title('original image')
subplot(2,2,2),imshow(R),title('Red Component')
subplot(2,2,3),imshow(G),title('Green Component')
subplot(2,2,4),imshow(B),title('Blue Component')

original image

Red Component

Green Component

Blue Component

Program 14
% Finding Red. Green and Blue missing components
clc
clear all
close all
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\fl1.bmp');

Workshop on Image and Video Processing- A Practical Approach


34

ECE Kamaraj college of Engineering& Technology VNR


a1=a;
b1=a;
c1=a;
a1(:,:,1)=0;
b1(:,:,2)=0;
c1(:,:,3)=0;
imshow(a),title('original image')
figure,imshow(a1),title('Red Missing!')
figure,imshow(b1),title('Green Missing!')
figure,imshow(c1),title('Blue Missing!')

original image

Red Missing!

Green Missing!

Blue Missing!

Program 15
% Wavelet Decomposition
clc
clear all
close all
a=imread('E:\Program Files\MATLAB\R2010b\toolbox\images\imdemos\images\zoneplate.png');
figure,imshow(a);
%First level decomposition
[p q r s]=dwt2(single(a),'db1');
b=[uint8(p), q; r,s];
%Second level decomposition
[p1 q1 r1 s1]=dwt2(p,'db1');
b1=[p1,q1; r1, s1];
b2=[uint8(b1), q; r s];
figure, imshow(b2)

Workshop on Image and Video Processing- A Practical Approach


35

ECE Kamaraj college of Engineering& Technology VNR

_________________________________________________________
VIDEO PROCESSING- BASIC MATLAB CODES
1.To read a video file
clc;
close all;
vidread=aviread('rhinos.avi');
implay(vidread)
2.To Convert Video To Frames
clc;
clear clc;
clear all;
close all;
3. To read a video file
vidread =mmreader('rhinos.avi');
vidFrames = read(vidread);
vidfrmlocation='F:\vidFrames.jpg';
4. To read particular frame
figure,imshow(vidFrames(:,:,:,50));
numFrames = get(vidread,'numberOfFrames');
for NumFrm =1:5
Frames(:,:,:,NumFrm )= read(vidread,5 ); figure,imshow(Frames(:,:,:,NumFrm ));
end
5.Background Subtraction or Foreground Extraction with noise removal
clc;
close all;
I=imread ('E:\ \');
figure,imshow(I);
I1=imread ('E:\ \');
figure,imshow(I1);
I2=imread ('E:\ \');
forgnd=I-I1;figure,imshow(forgnd);
figure,imshow(im2bw(forgnd));
for i=1:240
for j=1:320
if forgnd(i,j)>(8)
b(i,j)=255;
else
b(i,j)=0;
end
Workshop on Image and Video Processing- A Practical Approach
36

ECE Kamaraj college of Engineering& Technology VNR


end
end
figure,imshow(b);
s= strel('disk',1);
noiseremov=imerode(b,s);
figure,imshow(noiseremov);
filtimg=medfilt2(noiseremov);
figure,imshow(filtimg);
6.To Read Frames in loop
clc;
close all;
img=cell(1,10);
for N=1:6
dir=strcat('E:\ \');
img{:,N}=imread(dir);
figure,imshow(img{:,N});
end
7. To Convert Frames to Video File(Avifile)
clc;
close all;
avi=avifile('F:\result5.avi');
for k=1: 9
I=imread(strcat('E:\ \');
f = im2frame(I);
avi=addframe(avi,f);
end
avi=close(avi);
8.To find Centroid for Single Frame
clc;
close all;
% img=cell(1,10);
B1=imread ('E:\ \');figure,imshow(B1);
BW = imread ('E:\ \');
figure,imshow(B1);
CC = bwconncomp(BW, 4);
S = regionprops(CC);
% figure,imshow(S);
C = regionprops(CC, 'centroid');
[L, num] = bwlabel(BW, 4);
L1=labelmatrix(CC);
centroids = cat(1, S.Centroid);
imshow(BW)
hold on
plot(centroids(:,1), centroids(:,2), 'b*')
hold on
Workshop on Image and Video Processing- A Practical Approach
37

ECE Kamaraj college of Engineering& Technology VNR


9.To Create Bounding Box for Single Frame
clc;
close all;
img=cell(1,10);
BW = imread ('E:\ \');
CC = bwconncomp(BW, 4);
S = regionprops(CC);
% figure,imshow(S);
C = regionprops(CC, 'centroid');
[L, num] = bwlabel(BW, 4);
L1=labelmatrix(CC);
centroids = cat(1, S.Centroid);
imshow(BW)
hold on
plot(centroids(:,1), centroids(:,2), 'b*')
hold on
for z=1:num
BB= regionprops(L, 'boundingbox');
end
BB = regionprops(CC, 'boundingbox');
BB = regionprops(CC, 'boundingbox');
rectangle('position', [9.5000 74.5000 23 58], 'Edgecolor','red');
rectangle('position', [30.5000 68.5000 24 59], 'Edgecolor','red');
hold on
10. Read information about the original.avi file and save it in a local variable.
file_name = rhinos.avi;
file_info = aviinfo(file_name);
11. View the video compression and the number of frames for this file.
file_info.VideoCompression
file_info.NumFrames
12. We can also load individual frames from a video file by specifying the frame numbers
as a second parameter.
Load frames 5, 10, 15, and 20.
frame_nums = [5 10 15 20];
my_movie2 = aviread(file_name, frame_nums);
13. Inspect the first frame of the my_movie structure.
my_movie(1)
Workshop on Image and Video Processing- A Practical Approach
38

ECE Kamaraj college of Engineering& Technology VNR


14. View the first frame as an image using the imshow function.
imshow(my_movie(1).cdata)
15. Preallocate a 4D array that will hold the image data for all frames.
image_data = uint8(zeros(file_info.Height, file_info.Width, 3, ...
file_info.NumFrames));

16. Play the video five times with a frame rate of 30 fps.
movie(my_movie, 5, 30)
17. Play only frames 110.
frames = [5 1:10];
movie(my_movie, frames, 30)
18. Convert frame 10 to an image for further processing.
old_img = frame2im(my_movie(10));
19. Blur the image using an averaging filter and display the result.
fn = fspecial(average,7);
new_img = imfilter(old_img, fn);
figure , subplot(1,2,1), imshow(old_img), title(Original Frame);
subplot(1,2,2), imshow(new_img), title(Filtered Frame);
20. Using another frame, create a negative and display the result
old_img2 = frame2im(my_movie(15));
image_neg = imadjust(old_img2, [0 1], [1 0]);
figure
subplot(1,2,1), imshow(old_img2), title(Original Frame);
subplot(1,2,2), imshow(image_neg), title(Filtered Frame);
21.Now that we have processed our image, we can convert it back to frame using the im2frame
function.Convert the images back to frames and save the new frames in the video structure.
my_movie2 = my_movie;
new_frame10 = im2frame(new_img);
new_frame15 = im2frame(image_neg);
my_movie2(10) = new_frame10;
my_movie2(15) = new_frame15;

22. Create a negative of all the frames and reconstruct the frames into a video.
movie_neg = my_movie;
for k = 1:file_info.NumFrames
cur_img = frame2im(movie_neg(k));
new_img = imadjust(cur_img, [0 1], [1 0]);
Workshop on Image and Video Processing- A Practical Approach
39

ECE Kamaraj college of Engineering& Technology VNR


movie_neg(k) = im2frame(new_img);
end
implay(movie_neg)
23. Create an array of negative images from the original movie.
my_imgs = uint8(zeros(file_info.Height, file_info.Width,3, ...
file_info.NumFrames));
for i = 1:file_info.NumFrames
img_temp = frame2im(my_movie(i));
my_imgs(:,:,:,i) = imadjust(img_temp, [0 1], [1 0]);
end
24. Create the AVI file.
movie2avi(new_movie, file_name, compression, None);
25.Reading and Playing Video Files in Different Formats
Use the sequence below to read and play the first 100 frames of an MPEG movie.
obj = mmreader(shopping_center.mpg);
video = read(obj, [1 100]);
frameRate = get(obj,FrameRate)
implay(video, frameRate)

Workshop on Image and Video Processing- A Practical Approach


40

ECE Kamaraj college of Engineering& Technology VNR

Workshop on Image and Video Processing- A Practical Approach


41

You might also like