Matlab Programs for Image Processing
1.The utility functions
The functions provided are :
- to load image called filename having the dimension xdim and ydim, and which is stored as datatype precision
rawread(filename, xdim, ydim, precision)
rawwrite(filename, matrix, precision)
- to save matrix in file called
filename with datatype precision . For internal storage purposes Matlab treats an image as a matrix. For example to load an image into a matrix try
image=rawread(ctscan.raw, 256, 256);
You can choose to treat rawread, rawwrite as blac boxes. The source code is given at the end of this document.
Rawread.m ;--------------------------------------%Reads a raw intesity image file, written with a given precision (by default uint! ). % img " R#$R%#&(fname,ncols,nrows,precision); % function raw"rawread(fname, cols, rows, prec) if nargin""', precision" uint! ; elseif nargin""(, precision"prec; else, error( $rong number of arguments) *yntax+ ,rawread(fname,cols,rows), ); return; end fid " fopen(fname, r ); raw " fread(fid,-cols,rows.,precision) ; fclose(fid);
;---------------------------;rawwrite
function count"rawwrite(fname, array, prec) if nargin""/, precision" uint! ; elseif nargin""', precision"prec;
else, error( $rong number of arguments) *yntax+ ,rawwrite(fname,array), ); return; end fid " fopen(fname, w ); count " fwrite(fid,array,precision) ; fclose(fid);
;-----------------------------------------------------------1) Exercise 1 Rea an is!lay an image Rea " is!.m ;---------------------------------------------filename# $ctscan.raw%; image#rawrea &filename' ()*' ()*); Imagesc&image);
50
100
150
200
250 50 100 150 200 250
Result+ ;-------------------------------The image a!!ear coloure an image+ Ty!e in the comman win ow+ axis(square); colormap(gray); The result now+ istorte . In or er to is!lay a gray un istorte
50
100
150
200
250 50 100 150 200 250
Exercise () Plot a line !rofile through an image line"!rofile.m
%Reads a raw image file and display a line profile through its middle % it uses the rawread function filename" ctscan.raw ; % the filename to be read image"rawread(filename, /01, /01); figure(2); 3magesc(image); % display axis( s4uare ); colormap( gray ); line"2/!; figure(/); plot( image(line,2+/01)); image(line,2+/01)
50
100
150
200
250 50 100 150 200 250
250
200
150
100
50
50
100
150
200
250
300
;------------------------------------------------------------exercise ,. Transform a gray image into a binary image To ma e any graylevel image into a a binary image !",# image$ at say a threshold of half the maximum brightness value try :
maximum"max(max(img))5/.6; binimg"(img7maximum); The max operator returns a vector
if applied to a matrix and a number if applied to a vector - so to get the maximum graylevel value in a matrix it has to be applied twice. The same is true for the median, std and min functions. - o"binary.m
filename" ctscan.raw ; % the name of the file to be read image"rawread(filename, /01, /01); figure(2); 3magesc(image); % display original image axis( s4uare ); colormap( gray ); % binari8e maximum"max(max(image)); binimg"(image7maximum5/.6); figure(/); 3magesc(binimg); % display the binary image axis( s4uare ); colormap( gray ); % save filenameout" ctscanbin.raw ;
rawwrite(filenameout, binimg); % it writes not as bit but with the same precision as the original image
50
100
150
200
250 50 100 150 200 250
Find the way to store the image as bits% in order to show the smaller si&e of the file'' ( -------------------.on/olutions + Matlab has facilities for both #) and *) convolutions as implemented in the functions conv and conv/. For example to get a simple edge detection mas convolved with img try :
result"conv/(img,--2 -2 -2;-2 ! -2;-2 -2 -2., same );
(------------------------------------------------------------------0.1ourier Transform 1ourier Transforms+ There are also facilities for #) and *) forward and inverse Fourier Transforms - try the commands fft, fft/, ifft and ifft/. The command fftshift centers the Fourier spectrum origin to the center of the image. +ote that the results of these are complex and to display them one needs to decide on a reasonable representation such as for example the modulus. ,s an example to display the centered Fourier transform for the image in img type :
fouimg"fft/(img); fouimg"fftshift(fouimg); imagesc(abs(fouimg));
Result with shifting
50
50
100
100
150
150
200
200
250 50 100 150 200 250
250 50 100 150 200 250
fouimg2"/9 log26 (2:abs(fouimg))
Result without shifting
50
100
150
200
250 50 100 150 200 250
The phase can be displayed by using imagesc(angle(fouimg))
50
100
150
200
250 50 100 150 200 250
The phase
and the real and imaginary parts using the real and imag operators.
50
50
100
100
150
150
200
200
250 50 100 150 200 250
250 50 100 150 200 250
-eal part
imaginary part
.rogram fft"image.m
filename" ctscan.raw ; % the filename to be read img"rawread(filename, /01, /01); figure(2); 3magesc(img); % display axis( s4uare ); colormap( gray ); fouimg"fft/(img); fouimg"fftshift(fouimg);
fouimg2"/9 log26 (2: abs(fouimg));% compresion of the dinamic range figure(/); 3magesc(abs(fouimg2)); axis( s4uare ); colormap( gray ); figure('); 3magesc((fouimg2)); axis( s4uare ); colormap( gray );
% display the modulus without compression range
% display the modulus with compression range
figure((); imagesc(angle(fouimg)) ; axis( s4uare ); colormap( gray );
% display the phase angle
/t is worth remembering that multiplication in the Fourier domain in the case of an e0uation of the form 1!u,v$2F!u,v$3!u,v$ would actually be implemented by elementwise multiplication of F and 3 using the .9 operator and not normal matrix multiplication. ( (------------------------------------------------------------------------------------------------Exercise ) The low pass filter: do4lowpass.m
filename" ctscan.raw ; % the filename to be read image"rawread(filename, /01, /01); 3magesc(image); % display axis( s4uare ); colormap( gray ); s8e"si8e(image); rows " s8e(2); cols " s8e(/); %cutoff is the cutoff fre4uency of the filter 6 - 6.0. % n is the order of the filter, the higher n is the sharper % the transition is. (n must be an integer 7" 2). cutoff"6.0; n"2.6; % ; and < matrices with ranges normalised to :5- 6.0 x " (ones(rows,2) 9 -2+cols. - (fix(cols5/):2))5cols; y " (-2+rows. 9 ones(2,cols) - (fix(rows5/):2))5rows;
radius " s4rt(x.=/ : y.=/); radius relative to centre.
% # matrix with every pixel "
filt"2 .5 (2.6 : (radius .5 cutoff).=(/9n)) ; f " fftshift(filt); % >he filter figure(/); surf(filt); im " normalise(image); % Rescale values 6-2 (and cast % to ?double if needed). @@>3m " fft/(im); % >aAe @@> of image him " real(ifft/(@@>3m.9f)); % #pply the filter, invert figure('); imagesc(him); axis( s4uare ); colormap( gray );
cutoff2".5
cutoff2".# the filter
50
100
150
200
250 50 100 150 200 250
50
100
150
200
250 50 100 150 200 250
Exercise * 3igh pass filter( do4highpass.m /t is obtained as:
filt" 2.6 - filtlow; where fillow is the lowpass filter described above
50
100
150
200
250 50 100 150 200 250
The result of the filtering Exercise 2 3igh4oost filtering
a high-boost Butterworth filter. f " (2-25boost)9highpassfilter : 25boost;
1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 0 50 100 150 200 250 300
difference between the highpass ( red) and highboost filter for boost"26;
Cighboost leaves a bit of low frec4uency information
50
50
100
100
150
150
200
200
250 50 100 150 200 250
250 50 100 150 200 250
6oost2*
6oost2#"
Exercise 5 3omomor!hic filtering+ o"homor!hic.m The homomorphic filtering%
im " normalise(im); cast % to ?double @@>log3m " fft/(log(im:.62)); offset % Rescale values 6-2 (and if needed). % >aAe @@> of log (with % to avoid log of 6).
him " exp(real(ifft/(@@>log3m.9h))); % #pply the high boost filter, invert % fft, and invert the log.
50
100
150
200
250 50 100 150 200 250
6ray le/el transformations Exercise 7+ 8inear .ontrast Enhancement: do4lcontrast.m Typically, high contrast images are visually more appealing.
0.45 0.4 0.35 0.3 0.25 0.2 0.15 0.1 0.05 0 0 50 100 150 200 250 300
Transfer functions for alfa"6.20
Red-7 alfa Blue-7 /9 alfa Dreen-7'9alfa
CT Scan 50 100 150 200 250 50 100 150 200 250 2* alfa 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250
alfa
50 100 150 200 250 3* alfa
50 100 150 200 250
Exercise 11+ 6ama .orrection : do4adgamma.m The drawbac of the linear contrast enhancemnt is that it leads to saturation. This may be avoided by employing a non-linear contrast ad7ustment scheme such as gamma correction
newim " newim.=(25g);
8here g 9 # increases contrast and g:# reduces contrast
1 0.9 0.8 0.7
1 0.9 0.8 0.7 0.6
0.6 0.5 0.5 0.4 0.4 0.3 0.3 0.2 0.1 0 50 100 150 200 250 300 0.2 0.1 0 0 50 100 150 200 250 300
g25
12".;
50
50
100
100
150
150
200
200
250 50 100 150 200 250
250 50 100 150 200 250
g25
12".;
%Ealues of g in the range 6-2 enhance contrast of bright % regions, values 7 2 enhance contrast in darA % regions.
Exercise 1(+ 9 :ust .ontrast : do4ad7constrast.m <ne drawbac of the gamma correction is that the gray values are mapped in an asymmetric fashion with respect to the middle level gray.This may be alleviated by employing a sigmoidal non-linearity .
newim " 2.5(2 : exp(gain9(cutoff-newim))); % #pply *igmoid function
1 0.9 0.8 0.7
1 0.9 0.8 0.7
0.6 0.6 0.5 0.5 0.4 0.4 0.3 0.2 0.1 0 0 50 100 150 200 250 300 0.3 0.2 0.1 0 50 100 150 200 250 300
cutoff"6.0;
cutoff"6./;
50
50
100
100
150
150
200
200
250 50 100 150 200 250
250 50 100 150 200 250
cutoff"6.0;
cutoff"6./;
(-----------------------------------------------------.rograms ta en from http:==robotics.eecs.ber eley.edu=>mayi=imgproc=index.html
/. Gaussian_m.m
6aussian 1ilter ;emos
These demos show the basic effects of !*)$ 1aussian filter: smoothing the image and wiping off the noise. 1enerally spea ing, for a noise-affected image, smoothing it by 1aussian function is the first thing to do before any other further processings, such as edge detection. The effectiveness of the 1aussian function is different for different choosing the standard deviation sigma of the 1aussian filter. You can see this from the following demos.
<moothing =onnoisy Image
lena.gif filtere with sigma # , filtere with sigma # 1
=oise .ancelling
noisy lena filtere with sigma # , filtere with sigma #1
!The noise is generated by M,T?,6 function ".5@randn!;#*$$
/t uses the function d2gauss.m
lena 50 100 150 200 250 50 100 150 200 250 smooth 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250 50 100 150 200 250 noise cancel noisy lena
The parametes of the function could be changed:
Farameters of the Daussian filter+ n2"26;sigma2"';n/"26;sigma/"';theta"6; % >he amplitude of the noise+ noise"6.2;
,. .anny E ge etector
.anny E ge ;etector ;emos
There are some results of applying Aanny edge detector to real image The thresholding parameter alfa is fix as ".#. The si&e of the filters is fixed as #"@#". These images are all gray images though they might show a little strange in your browser. To see clearer, 7ust clic these images and you will find the difference especially from the Bresult imagesB, that is, the titled Bafter thinningB ones. The safe way to see the correct
display of these images is to grab these images and show them by BxvB or BM,T?,6B. 8hile, you are encouraged to use the given M,T?,6 codes and get these images in M,T?,6 by yourself. Try to change the parameters to get more sense about how these parameters affect the edge detection.
The results of choosing the stan ar the e ge etectors as ,.
lena.gif /ertical e ges
e/iation sigma of
hori>ontal e ges
norm of the gra ient
after threshol ing
after thinning
The results of choosing the stan ar the e ge etectors as 1.
lena.gif /ertical e ges
e/iation sigma of
hori>ontal e ges
norm of the gra ient
after threshol ing
after thinning
/t uses the function d*dgauss.m /t wor s
Original Image 50 100 150 200 250 50 100 Iy 50 100 150 200 250 50 100 150 200 After Thresholding 50 100 150 200 250 50 100 150 200 250 250 50 100 150 200 250 50 150 200 250 50 100 150 200 250 50
Ix
100 150 200 Norm of Gradient
250
100 150 200 After Thinning
250
50 100 150 200 250 50 100 150 200 250
d*dgauss can be used as )erivative of a 1aussian ?in s of materials for image processing and Matlab #.http:==amath.colorado.edu=courses=CD*"=*"""Epr=?abs=8or sheets=Matlab4tutorial=mat labimpr.html /ntroduction to image processing in Matlab # by Kristian Sandberg, Department of Applied Mathematics, University of Colorado at Boulder
exercise 1, Fdge )etectors G morphology in Matlab% .rewit operators Aode: do4prewitt.m
FrwGim " edge(image, prewitt );
50
100
150
200
250 50 100 150 200 250
Fxercise #C Eobel operators Aode: do4sobel.m
sobGim " edge(image, sobel );
50
100
150
200
250 50 100 150 200 250
)ifference between the sobel and prewittH Aode: do4sobel4prewitt.m
50
100
150
200
250 50 100 150 200 250
Fxercise #I. -oberts <perators Aode: do4-oberts
50
100
150
200
250 50 100 150 200 250
3istogram based segmentation http:==arl.stanford.edu=pro7ects=helicopters=matlab.html
Fxercise #D. )o histogram Aode: do4histogram.m
imhist(im2);
50
100
150
200
250 50 100 150 200 250
5000
4000
3000
2000
1000
0 0 50 100 150 200 250
Fxercise #J. Fixed thresholding Aode: do4thresholding.m 68 2 /M*68!/,?FKF?$ converts the intensity image / to blac and white. 6ased on the histogram Thresh 2J". The output binary image 68 has values of " !blac $ for all pixels in the input image with luminance less than ?FKF? and # !white$ for all other pixels.
50
100
150
200
250 50 100 150 200 250
Thresh2#*"( L only the bones are ept.
50
100
150
200
250 50 100 150 200 250
Fxercise #M Morphology ;ilation+ code: do4dilation.m
&ifferent Aernels H'"ones('); H0"ones(0); HI"ones(I); HJ"ones(J);
50
100
150
200
250 50 100 150 200 250
thresh2#*"
50
100
150
200
250 50 100 150 200 250
dilated with N5
50
100
150
200
250 50 100 150 200 250
dilated with N; etc..
Fxercise *" Frosion
50
100
150
200
250 50 100 150 200 250
Froded with N5
50
100
150
200
250 50 100 150 200 250
eroded with N; Fxercise *": do4opening.m Morphology could be also applied with bwmorph function that will use a N5 ernel(
50
100
150
200
250 50 100 150 200 250
op"bwmorph(B$, open );
Fxercise *# Alosing Aode: do4closing.m
50
100
150
200
250 50 100 150 200 250
closing Fxercise *5 Thining )o4thining.m
50
100
150
200
250 50 100 150 200 250
Fx Fxercise *5 Thic ening )o4thic ening.m
50
100
150
200
250 50 100 150 200 250