Professional Documents
Culture Documents
ECS 702
Digital Image Processing
Prerequisite :
Student has knowledge about the c and matlab. They should be able to write and
implement the programs in c language with turbo c compilers. The basic functional
aspect of Matlab should be known by the students.
Outcomes:
After knowing all the mentioned below programs either in C or in Matlab the
students will become to do research by applying different techniques of problem
identification and their solution with innovative methodologies.
Language
C or Matlab
C or Matlab
A. Program For Mean Filter
B. Program for Median Filter
C or Matlab
Matlab
Matlab
Matlab
Matlab
Matlab
Matlab
Matlab
Program 1.
Implement the program in Matlab for digital Negative.
clear all, close all
echo on
% 1. load a gray scale image
[xi,ind]=imread('images\p64.bmp');
[nh,nv]=size(xi); % size of the image
x=ind2gray(xi,ind); % pixel value in [0 255]
figure(1),
imshow(x),title('original image')
posi=get(1,'position'); % a 1 x 4 vector gives lower left corner and size of image
set(1,'position',[0 540 posi(3:4)])
% Image negatives: T(r) = L-1-r L=256
xneg=255-x;
figure(2),imshow(xneg),title('image negatives')
posi=get(2,'position'); % a 1 x 4 vector gives lower left corner and size of image
set(2,'position',[160 540 posi(3:4)])
pause
%
% Let us now consider some transformation function
%
r=[0:0.01:1];
s=[0.5*r(find(r<0.2)) 0.1+1.5*(r(find(0.2 <= r & r <= 0.7))-0.2)...
1+0.5*(r(find(r>0.7))-1)];
figure(7),subplot(131),plot(r,s,'-'),title('mid-range strech')
set(7,'position',[275 265 712 194])
%
x1=double(x)/255; % x1 range to 0 and 1
y=(0.5*x1).*[x1<0.2]+(0.1+1.5*(x1-0.2)).*[0.2 <= x1 & x1 <= 0.7] ...
+(1+0.5*(x1-1)).*[x1 > 0.7];
[xmid,indy]=cmunique(y);
figure(3),imshow(xmid,indy),title('mid-range stretched')
posi=get(3,'position'); % a 1 x 4 vector gives lower left corner and size of image
set(3,'position',[320 540 posi(3:4)])
pause
c = 255/log10(1+255);
% c is chosen to ensure only 256 gray levels after transform
r=[0:255]; s=c*log10(1+abs(r));
figure(7),subplot(132),plot(r,s,'-'),title('logarithm compression')
axis([0 256 0 256])
xlog=uint8(round(c*log10(1+double(x))));
figure(4),imshow(xlog),title('log-transformed')
posi=get(4,'position'); % a 1 x 4 vector gives lower left corner and size of image
set(4,'position',[480 540 posi(3:4)]),
Program 2a.
Mean Filter with 3 x 3 mask
clear all;
close all;
a=imread('car.jpg');
i=rgb2gray(a);
subplot(3,2,1);
imshow(i)
title('org image');
n=imnoise(i,'salt & pepper',0.05);%adding salt & pepper noise
subplot(3,2,2);
imshow(n);
title('with noise')
k=medfilt2(n);%applying mean filter
subplot(3,2,3);
imshow(k);
title('mean filter')
h = fspecial('average',5);%averager of 5x5 pixel dimension
h1= uint8(filter2(h,n));%applying 2D filter over the noise image 'n' with the averager 'h' and then
converting double to uint8
subplot(3,2,4);
imshow(h1);
title('avg');
m=wiener2(n);%applying wiener filter
subplot(3,2,5);
imshow(m);
title('wiener');
rms1=sqrt(sum(sum(n-i).^2))/length(n);%applying root mean square
PSNR1noise=20 * log10(255/rms1);%finding peak signal to noise ratio
rms2=sqrt(sum(sum(i-k).^2))/length(n);
PSNR2mean=20 * log10(255/rms2);
rms3=sqrt(sum(sum(i-m).^2))/length(n);
PSNR3weiner=20 * log10(255/rms3);
rms4=sqrt(sum(sum(i-h1).^2))/length(n);
PSNRavg=20 * log10(255/rms4);
Program 2b.
Median Filter with 3 x 3 mask
function [ img2 ] = MedianFilter( img )
[Width,Height]=size(img);
img2 = zeros(Width,Height);
for xcoord=1:1:Width
leftbound=xcoord-1;
rightbound=xcoord+1;
if leftbound<1
leftbound=1;
end
if rightbound>Width
rightbound=Width;
end
for ycoord=1:1:Height
topbound=ycoord-1;
bottombound=ycoord+1;
if topbound<1
topbound=1;
end
if bottombound>Height
bottombound=Height;
end
arrsize = (bottombound-topbound)*(rightbound-leftbound);
arr = zeros(arrsize);
xindex=leftbound;
yindex=bottombound;
index=1;
while index<arrsize
arr(index)=img2(xindex,yindex);
xindex=xindex+1;
if xindex >rightbound
xindex=1;
yindex=yindex+1;
end
if yindex>bottombound
break
end
end
sortedarr = SelectionSort(arr);
img2(xcoord,ycoord,1)=sortedarr(ceil((arrsize)/2));
end
end
end
length=size(numbers);
for i = length: -1: 1
max = i;
for j = i-1:-1:1
if numbers(max) < numbers(j)
max = j;
end
end
temp = numbers(max);
numbers(max) = numbers(i);
numbers(i) = temp;
end
end
Program 3.
Plot the regular histogram of M x N Image of 3 bits in Matlab. Also equalize and
plot the Flat histogram.
clear all, close all
load p64int.txt; % 64 x 64 image, L = 256
x0=p64int;
L=256;
[m,n]=size(x0);
len=m*n;
x=reshape(x0,len,1);
xpdf=hist(x,[0:L-1]); % pdf, 1 x L
tr=round(xpdf*triu(ones(L))*(L-1)/len); % cdf, range from 0 to L-1
y0=zeros(m,n);
for i=1:L,
if xpdf(i)>0,
y0=y0+[x0==i-1]*tr(i);
end
end
ypdf=hist(reshape(y0,len,1),[0:L-1]); % pdf of y, 1 x L
figure(1),subplot(211),stem([0:L-1],xpdf),title('histogram, original')
axis([0 256 0 500])
subplot(212),stem([0:L-1],ypdf),title('histogram, equalized'),axis([0 256 0 500])
% figure(2),subplot(121),image(x0),colormap('gray')
% subplot(122),image(y0),colormap('gray')
figure(2),subplot(121),imshow(uint8(x0)),title('before')
subplot(122),imshow(uint8(y0)),title('after')
figure(3)
stairs([0:L-1],tr),title('transformation'),axis([0 256 0 256])
% Algorithm:
% 1. compute the PDF, and then CDF (T(r))of x0
% 2. point-wise gray-level transform according to T(r)
if nargin<3, mode=0; end % default not plotting figures
if nargin<2, L=256; end % default L=256
bins=[0:L-1];
[m,n]=size(x0);
len=m*n;
x=reshape(x0,len,1);
xpdf=hist(x,bins); % pdf, 1 x L
tr=round(xpdf*triu(ones(L))*(L-1)/len); % cdf, range from 0 to L-1
y0=zeros(m,n);
for i=1:L,
if xpdf(i)>0,
y0=y0+[x0==i-1]*tr(i);
end
end
ypdf=hist(reshape(y0,len,1),[0:L-1]); % pdf of y, 1 x L
if mode==1,
figure(1),
subplot(211),stem([0:L-1],xpdf),title('histogram, original')
axis([0 256 0 500])
subplot(212),stem([0:L-1],ypdf),title('histogram, equalized'),
axis([0 256 0 500])
figure(2),
stairs([0:L-1],tr),title('transformation'),
axis([0 256 0 256])
figure(3),subplot(121),imagesc(uint8(x0)),title('before'),colormap('gray')
subplot(122),imagesc(uint8(y0)),title('after'),colormap('gray')
end
Program 4.
Write a program to implement the low pass filter in Matlab.
%Question No:5
%IDEAL LOW-PASS FILTER
function idealfilter(X,P)
f=imread(X);
[M,N,O]=size(f);
F=fft2(double(f));
u=0:(M-1);
v=0:(N-1);
idx=find(u>M/2);
u(idx)=u(idx)-M;
idy=find(v>N/2);
v(idy)=v(idy)-N;
[V,U]=meshgrid(v,u);
D=sqrt(U.^2+V.^2);
H=double(D<=P);
G=F;
for i = 1:O
G(:,:,i) = H.*F(:,:,i);
end
g=uint8(real(ifft2(double(G))));
imshow(f),figure,imshow(g);
end
Program 5.
Write a program to implement the high pass filter in Matlab.
function [g] = FFTPF1D(X, binsize, f, P)
M=length(X);
% get the fft position of cutoff frequence (reference
% frequency)
f = f / binsize;
xidx=1:1:M;
fftref = abs(fft(sin(xidx .* 2 .* pi ./f)));
bounder = find( (max(fftref) - fftref) < (max(fftref) ./ 1000 ));
% do the filter
fftx = fft(X)
if ( P )
fftx(bounder(1):1:bounder(2))=0
else
fftx(1:1:bounder(1)) = 0;
fftx(bounder(2):1:M) = 0;
end
g=real(ifft(fftx));
end
Program 6.
Write a program to implement the boundary extraction algorithm in Matlab.
% boundary demo.m
% (C) 2006 by Yu Hen Hu
% created: Dec. 19, 2006
% demonstrate morphological boundary extraction
%
clear all, close all
A0=imread('myshap4.bmp');
imshow(A0); % a heart shape hand drawing
title('original image');
pause
% A0 contains mostly 1s and the drawing contains 0s, uint8
A1=1-double(A0); % invert black and white
B=ones(3);
A2=imopen(imclose(A1,B),B); % fill 1 pixel hole and remove sticks
A3=imfill(A2,[100 100]); % fill the interior
A=double(A2) + double(A3);
imshow(A),title('after interior filling using imfill');
pause
Ab=A-double(erode(A,B));
imshow(Ab), title('extracted boundary');
clear A1 A2 A3; Ac=Ab;
vidx=[[1:20:280] 280];
Ac(vidx,:)=1; Ac(:,vidx)=1;
imshow(Ac)
Program 7.
Write a program to implement the grahms scan line algorithm in Matlab.
Input: a set of points S = {P = (P.x,P.y)}
Select the rightmost lowest point P0 in S.
Sort S angularly about P0 as a center.
For ties, discard the closer points.
Let P[N] be the sorted array of points.
Push P[0]=P0 and P[1] onto a stack W.
while i < N
{
Let PT1 = the top point on W
Let PT2 = the second top point on W
if (P[i] is strictly left of the line PT2 to PT1) {
Push P[i] onto W
i++ // increment i
}
else
Pop the top point PT1 off the stack
}
Output: W = the convex hull of S.
Program 8.
Write a program for edge detection algorithm in Matlab
% program for edge detection
clc; clear all; close all;
%read an image
[filename, pathname, filterindex] = uigetfile( ...
{ '*.jpg','JPEG (*.jpg)'; ...
'*.bmp','Windows Bitmap (*.bmp)'; ...
'*.fig','Figures (*.fig)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose image(s) to be processed', ...
'MultiSelect', 'off');
if filterindex==0, break;end
filename=cellstr(filename);
y= imread(horzcat(pathname,char(filename)));
% y=imread('car3.jpg');
mm=input('Input your threshold between 0 and 255 ');
% convert color image to gray scale
x= rgb2gray(y);
imshow(x);
[r,c]=size(x);
max=0;
min=0;
for j=2:r-1
for i=2:c-1
p=i-1;
q=i+1;
a=j-1;
b=j+1;
d1=abs(x(j,i)-x(j,p));
d2=x(j,i)-x(j,q);
e1=x(j,i)-x(a,i);
e2=x(j,i)-x(b,i);
f1=x(j,i)-x(a,p);
f2=x(j,i)-x(b,q);
g1=x(j,i)-x(a,q);
g2=x(j,i)-x(b,p);
if (d1 < 0)
d1=d1*(-1);
end
if (d2 < 0)
d2=d2*(-1);
end
if (e1 < 0)
e1=e1*(-1);
end
if (e2 < 0)
e2=e2*(-1);
end
if (f1 < 0)
f1=f1*(-1);
end
if (f2 < 0)
f2=f2*(-1);
end
if (g1 < 0)
g1=g1*(-1);
end
if (g2 < 0)
g2=g2*(-1);
end
if (d1 >= mm) && (d2 >= mm)
x(j,i)=255;
elseif (e1 >= mm) && (e2 >= mm)
x(j,i)=255;
elseif (f1 >= mm) && (f2 >= mm)
x(j,i)=255;
elseif (g1 >= mm) && (g2 >= mm)
x(j,i)=255;
else
x(j,i)=0;
end
end
end
figure
imshow(x);
BW = im2bw(x, 0.5);
figure
imshow(BW)
Program 9.
Write a Program for line detection algorithm in Matlab.
function DrawLines_2Ends(lineseg, varargin)
%Draw line segments, parameterized as (x1, x2, y1, y2), on graph
%
% DrawLines_2Ends(lineseg, varargin)
% A simple function for drawing line segments on graph. Made as an
% auxiliary tool for function '[...] = Hough_Grd(...)'.
%
% INPUT: (lineseg, properties)
% lineseg: Parameters (x1, x2, y1, y2) of line segments to draw.
%
Is a Ns-by-4 matrix with each row contains the parameters
%
(x1, x2, y1, y2) that define the two ends of a line
%
segment. The output 'lineseg' from the function
%
'[...] = Hough_Grd(...)' can be put here directly.
% properties: (Optional)
%
A string of line drawing properties. Will be transferred
%
to function 'plot' without modification for line drawing.
%
% OUTPUT: None
%
% BUG REPORT:
% Please send your bug reports, comments and suggestions to
% pengtao@glue.umd.edu . Thanks.
% Author: Tao Peng
%
Department of Mechanical Engineering
%
University of Maryland, College Park, Maryland 20742, USA
%
pengtao@glue.umd.edu
% Version: alpha
Revision: Dec. 02, 2005
hold on;
for k = 1 : size(lineseg, 1),
% The image origin defined in function '[...] = Hough_Grd(...)' is
% different from what is defined in Matlab, off by (0.5, 0.5).
if nargin > 1,
plot(lineseg(k,1:2)+0.5, lineseg(k,3:4)+0.5, varargin{1});
else
plot(lineseg(k,1:2)+0.5, lineseg(k,3:4)+0.5, 'LineWidth', 2);
end
end
hold off;