Matlab Image Processing

With Code (New updates) February 5, 2010 Print Article Citation , XML
y y y

Email

Authors
y

V Mayur

New Updated News:
- Scroll below: Learn Matlab function for active contours. - Updates at Below: Learn Matlab Image Processing ± Edge detection Function with example

- Visit two more links for Matlab Image Processing with examples:
http://knol.google.com/k/mayur-vora/learn-matlab-image-processing-with/232y3pcqwxodx/12# http://knol.google.com/k/learn-matlab-image-processing-with-example-part-2#

²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²² ²-

Active Contours in Matlab (Image Processing):
* Inbuilt Matlab functions have been made use of in implementing the code. close allclear allclc below

% read the input imageinpImage =imread('coin_1.jpg');% size of image[rows cols dims] = size(inpImage); if dims==3 inpImage=double(rgb2gray(inpImage));else inpImage=double(inpImage);end

[divXnormGradPhiY divYnormGradPhiY]=gradient(normGradPhiY). % higher dimensional embedding function phi whose zero level set is our% contour% radius of circle .15. phi = double((phi > 0). normGradPhiY=gradPhiY. phiOld=zeros(rows./(1+absGradI. 1:rows)./(absGradPhi+(absGradPhi==0)).^2-1. % gradient descent step sizedt=.[0 0]. % level set evolution equation phi = phi + ( dt * dPhiBydT ).[u. it is a way to keep the significant imformation of the image while get rid of the unimportant . phiOld=phi.v] = meshgrid(1:cols. end if mod(iter.absGradI=sqrt(gradIX. The percentage of the thresholding means the threshold level between the maximum and minimum indesity of the initial image.floor(0. Thresholding is a way to get rid of the effect of noise and to improve the signal-noise ratio.45*cols)).^2).45*cols))).^2+gradIY. % dPhiBydT dPhiBydT =( g.*absGradPhi + (gx.05) iter imagesc(inpImage) colormap(gray) hold on contour(phi.45*rows))).G. % gradient of image[gradIX.^2+((vrows/2)/(floor(0.'r') % close all % surf(phi) % pause endend Image Thresholding This demo shows how a image looks like after thresholding.2.num_reinit)==0 % reinitialize the embedding function after num_reinit iterations phi=sign(phi).*gradPhiY) ).phi = ((u-cols/2)/(floor(0. iter=iter+1.'same').^2).% gradient of edge-stopping function[gx.10)==0 pause(0. % magnitude of gradient of phi absGradPhi=sqrt(gradPhiX. % edge-stopping functiong = 1. [divXnormGradPhiX divYnormGradPhiX]=gradient(normGradPhiX). if mod(iter. % curvature is the divergence of normalized gradient of phi K = divXnormGradPhiX + divYnormGradPhiY.cols). % normalized gradient of phi eliminating singularities normGradPhiX=gradPhiX.gradIY]=gradient(inpImage).% Gaussian smoothed imageinpImage=conv2(inpImage.*K.gy]=gradient(g).45*rows).*absGradPhi + g.(phi < 0).^2).*(bwdist(phi < 0)) . % number of iterationsiter=0.initial embedding function% radius=min(floor(0.*(bwdist(phi > 0))).^2+gradPhiY.*gradPhiX+gy./(absGradPhi+(absGradPhi==0)).% Gaussian filterG=fspecial('gaussian'. while(sum(sum(abs(phi-phiOld)))~=0) % gradient of phi [gradPhiX gradPhiY]=gradient(phi).4. That is.sigma). % number of iterations after which we reinitialize the surfacenum_reinit=10.% Gaussian filter parametersigma=1.

thix1=max(ix.level3. You are encouraged to do thinning without thresholding and to see what is the advantage of thresholding.level1.imagesc(ix).2).ix=ind2gray(x.I_max=max(max(ix)).thix2=max(ix. The output are four subfigures shown in the same figure: y y y y Subfigure 1: The initial ³lena´ Subfigure 2: Threshold level is one alfa Subfigure 3: Threshold level is two alfa Subfigure 4: Threshold level is three alfa The MATLAB codes:%%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%%clear.level3=3*level1.figure(1).title('threshold one alfa').map]=gifread('lena.1.2. you will see that.thix3=max(ix.title('lena').level2=2*level1. In the Canny edge detector part. lena.% less than 1/3 [x.I_min=min(m in(ix)).imagesc(thix2).imagesc(thix1). we first do some thresholding.gif').colormap(gray). before thinning.% Threshold level parameter alfa:alfa=0.title('threshold two .subplot(2 .*ones(size(ix))).level2.subplot(2.2.3).1).2.map).level1=alfa*(I_maxI_min)+I_min.gif 10% threshold 20% threshold 30% threshold Image Thresholding Matlab Codes This program show the effect of thresholding.part (under the condition that you choose a plausible thresholding level).*ones(size(ix)) ).subplot(2.*ones(size(i x))).

4).2.subplot(2. The output are four subfigures shown in the same figure: .gif filtered with sigma = 3 filtered with sigma = 1 Noise cancelling noisy lena filtered with sigma = 3 filtered with sigma =1 (Noise is generated by matlab function 0. Smoothing nonnoisy image lena. such as edge detection. The effectiveness of the gaussian function is different for different choices of the standard deviation sigma of the Gaussian filter.title('threshold three alfa').m file %%%%%%%%%%%%%% Gaussian function These demos show the basic effects of the (2D) Gaussian filter: smoothing the image and wiping off the noise.imagesc(thix3). You can see this from the following demos. smoothing it by Gaussian function is the first thing to do before any other further processing. Generally speaking. for a noise-affected image.%%%%%%%%%%%%% End of the main.3*randn(512)) Gaussian filter study matlab codes This program show the effect of Gaussian filter.alfa').

% Function "gauss.tiff using matlab. x=ind2gray(w.n2.imagesc(f1).theta1=0.std)y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)).gif´ we used here was obtained by translating from a color lena.*h))).4).sigma1. The safe way to see the correct display of these images is to grab these images and show them by ³xv´ or ³matlab´.imagesc(x). .function h = d2gauss(n1.std2.theta).) The thresholding parameter alfa is fix as 0.theta)r=[cos(theta) sin(theta).colormap(gra y).f1=conv2(x. sin(theta) cos(theta)]. you are encouraged to use the given matlab codes and get these images in matlab by yourself.m file %%%%%%%% Function "d2gauss.1. and sigma1 and sigma2% are the standard deviation of the gaussian functions.imagesc (y).2.% The amplitude of the noise:noise=0.2.fil ter1.m file %%%%%%%%%%%%%%% %%%%%%% The functions used in the main.std1)*gauss(u(2).sigma2=3.x_rand=noi se*randn(size(x)).figure(1). To see them more clearly. These images are all gray images though they might seem a little strange in your browser.%%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%%%% y y y y y Canny edge detector There are some results of applying Canny edge detector to real image (The black and white image ³lena.filter1=d2gauss(n1.m":function y = gauss(x.y=x+x_rand. The size of the filters is also fixed as 10*10.m":% This function returns a 2D Gaussian filter with size n1*n2. the titled ³after thinning´ ones.filter1.n2.imagesc(rf1).'same').map).subplot(2.2). While.map]=gifread('lena. just click these images and you will find the difference especially from the ³result images´.3).'same'). that is.y y y y y Subfigure 1: The initial noise free ³lena´ Subfigure 2: The noisy ³lena´ Subfigure 3: Filtered the initial ³lena´ Subfigure 4: Filtered the noisy ³lena´ The matlab codes:%%%%%%%%%%%%% The main. So it might not be the standard BW ³lena´.rf1=conv2(y.1.std2).sigma1=3.2.sigma2.j) = gauss(u(1). h(i.subplot(2.1).2. [w. endendh = h / sqrt(sum(sum(h.subplot(2. theta is % the angle that the filter rotated counter clockwise.for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'.gif').std1.% Parameters of the Gaussian filter:n1=10. Try to change the parameters to get more sense about how these parameters affect the edge detection.m file %%%%%%%%%%%%%%%clear.%%%%%%%%%%%%%% End of the main.n2=10.subplot(2.

lena.gif vertical edges horizontal edges norm of the gradient after thresholding after thinning .gif vertical edges horizontal edges norm of the gradient after thresholding after thinning The results of choosing the standard deviation sigma of the edge detectors as 1.The results of choosing the standard deviation sigma of the edge detectors as 3. lena.

Sigmax2=1.+1.subplot(3.2).Sigmay2=1.0.m file %%%%%%%%%%%%%%%clear.Nx2=10. % Y-axis direction edge detectionsubplot(3.subplot(3.title('Ix').3)filtery=d2dgauss(Ny1.)subplot(3.*ones(size(NVI))).titl e('Image: lena.2.NVI=sqrt(Ix. % Get the initial image lena.gif[x.2.Theta2).Sigmax1.2. imagesc(Iy).imagesc(Ix).Nx2.+1].0.[n.gif').Ny2.% The algorithm parameters:% 1.% 2. w=ind2gray(x.5).for i=2:n-1.colormap(gray).2.level=alfa*(I_maxI_min)+I_min.map).Sigmay1.4). % ThresholdingI_max=max(max(NVI)).j) > level.% Yaxis direction filter: Ny1=10.figure(1).imagesc(w.map]=gifread('lena.Ibw=max(NVI.Sigmay2.I_min=min(min(NVI)). title('After Thresholding').-1.Iy=co nv2(w.gif').Sigmax1=1. % X-axis direction edge detectionsubplot(3.Sigmax2.*Ix+Iy.title('Norm of Gradient').level.6).Canny edge detector algorithm matlab codes This part gives the algorithm of Canny edge detector.-1.*Iy).Ny2=10.+1.1). % Norm of the gradient (Combining the X and Y directional derivatives)subplot(3. The thresholding parameter alfa: alfa=0.Theta1=pi/2.imagesc(Ibw).Ix= conv2(w.Theta2=0. Y=[-1.filterx=d2dgauss(Nx1. if Ibw(i.m]=size(Ibw).filterx.'same').2.2.-1.title('Iy'). The outputs are six subfigures shown in the same figure: y y y y y y Subfigure 1: The initial ³lena´ Subfigure 2: Edge detection along X-axis direction Subfigure 3: Edge detection along Y-axis direction Subfigure 4: The Norm of the image gradient Subfigure 5: The Norm of the gradient after thresholding Subfigure 6: The edges detected by thinning The matlab codes:%%%%%%%%%%%%% The main.- .Sigmay1=1.filtery.'same'). % Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum. Parameters of edge detecting filters:% X-axis direction filter: Nx1=10.1.200). X=[-1.for j=2:m-1.Theta1).0.imagesc(NVI).

j)/NVI(i.j+1)].sigma2.j)=I_min. Ibw(i.sigma1.Ibw(i.0.1.%%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%% ²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²² ²²²²²²²- MATLAN IMAGE PROCESSING : EDGE DETECTION FUNCTION Marr/Hildreth and Canny Edge Detection with m-code Recall the wagon wheel test image used in the resampling example: . ZI=interp2(X. endendh = h / sqrt(sum(sum(abs(h).m":% This function returns a 2D edge detector (first order derivative% of 2D Gaussian function) with size n1*n2. endendendimagesc(I_temp). h(i.Ibw(i-1. and sigma1 and sigma2 are the% standard deviation of the gaussian functions.for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i(n2+1)/2]'. theta is the angle that% the detector rotated counter clockwise.std)y = -x * gauss(x.XI.j)/NVI(i.j).j+1).YI).Ibw(i+1. XI=[Ix(i. % Function "dgauss.std)y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)).m"(first order derivative of gauss function):function y = dgauss(x.j+1).j) = gauss(u(1). end else I_temp(i.Y.j1).j)].n2. sin(theta) cos(theta)].m file %%%%%%%%%%%%%%% %%%%%%% The functions used in the main.j) >= ZI(2) I_temp(i.j)/NVI(i.j)/NVI(i.j).0.j-1).+1.j).std) / std^2.title('After Thinning'). else I_temp(i.function h = d2dgauss(n1.m":function y = gauss(x.%%%%%%%%%%%%%% End of the main.sigma2).Z. % Function "gauss.theta)r=[cos(theta) -sin(theta). Z=[Ibw(i-1.j).j). Ibw(i+1.j)].0.Ibw(i-1.sigma1)*dgauss(u(2). if Ibw(i.j)=I_min.Ibw(i.Ibw(i+1. Iy(i.+1].j-1).colormap(gray).*abs(h)))).+1. YI=[Iy(i.j) >= ZI(1) & Ibw(i. -Ix(i.m file %%%%%%%% Function "d2dgauss.j)=I_max.

What follows is a mosaic of zero-crossings for four choices of sigma computed using the Matlab image processing toolbox. the standard deviation of the Gaussian. the threshold is forced to be zero so that all zero-crossings are reported. Here.Marr/Hildreth edge detection is based on the zero-crossings of the Laplacian of the Gaussian operator applied to the image for various values of sigma. The top left is sigma=1. the bottom left is sigma=3 and the bottom right is sigma=4. as is required by the Marr/Hildreth theory of edge detection.) . the top right is sigma=2. (Matlab Laplacian of Gaussian edge detection normally selects a threshold so that only zero-crossings of sufficient strength are shown.

the bottom left is sigma=3 and the bottom right is sigma=4. For this example. for the mosaic. The Matlab implementation can estimate both thesholds automatically. Therefore. Canny edge detection is based on extrema of the first derivative of the Gaussian operator applied to the image for various values of sigma. I found the Matlab estimated thresholds to be somewhat conservative. the top right is sigma=2. . I reduced the thresholds to 75 percent of their automatically estimated values.As most commonly implemented. What follows is a mosaic of edge points for four choices of sigma computed using the Matlab image processing toolbox. The top left is sigma=1. the standard deviation of the Gaussian. The Canny method uses two thresholds to link edge points.

'log'.3.0.0.MH4 = edge(A.MH2 = edge(A.'log'.4.2.'log'. with Canny edge detection. This comes. m-code is below: % Image Processing Toolbox Version 5.MH3 = edge(A. however. Alas.0).'log'. especially for larger values of sigma.You should observe that zero-crossings in Marr/Hildreth edge detection always form connected.tif').0. at the expense of localization. MH3 MH4].4(R2007a) A = imread('/ai/woodham/public_html/cpsc505/images/wheel. the edge segments can become disconnected For above example. % Marr/Hildreth edge detection% with threshold forced to zeroMH1 = edge(A.0). .0). closed contours (or leave the edge of the image). % form mosaicEFGH = [ MH1 MH2. Canny edge detection does a better job of localization.0). Arguably.1.0.

[].'canny'.) You can execute a few lines by copying them into the Matlab Command Window.1. Ct4] = edge(A.[]. and activate Cell Mode from the Cell menu.'tif').'canny'. At the time of writing.3.k*Ct2.'canny'.C3 = edge(A.'InitialMagnification' .100).%imshow(ABCD.0). % write results to file% Note: Matlab no longer reads/writes GIF files.'InitialMagnification' . Matlab image processing introduction This is to help you get started with image processing in Matlab.'canny'. Translation from TIF to GIF was done% manually (with xv) for inclusion in the web example pageimwrite(ABCD.0). Ct3] = edge(A.100).imwrite( EFGH.tif'.3. % Canny edge detection[C1. is .'Marr/Hildreth: UL: s=1 UR: s=2 BL: s=3 BR: s=4'). Alternatively. to execute it.'/ai/woodham/World/cpsc505/images/canny.[].k*Ct4.k*Ct3. % show mosaic in Matlab Figure window%canny = figure('Name'.'tight').0).0).'canny'. the results will overwrite each other.%imshow(EFGH.[C4. (If you run the whole script. Ct1] = edge(A. the command.'canny'.0).0).4.[]. % Recompute lowering both automatically computed% thresholds by fraction kk = 0. C3 C4 ]. Ct2] = edge(A.'/ai/woodham/World/cpsc505/images/log.k*Ct1.0).0).[C2.1. owing to licence% restrictions. Contents y y y y y y Setup Read in an image Find out the size of the image Simple image processing (conventional version) Simple image processing (Matlab version) Experimenting yourself Setup You can execute the code in this file a section at a time to see the effects. or press CTRL-ENTER. % form mosaicABCD= [ C1 C2. Then you can click in a cell (a section between two headings) to highlight it and click the ³Evaluate cell´ icon.[C3.C4 = edge(A.4. you can view the script in the editor.'tif').%iptsetpref('ImshowBorder'.75C1 = edge(A.%iptsetpref('ImshowBorder'. First you must set your Matlab path to find the Sussex Matlab computer vision teaching libraries.'canny'.C2 = edge(A.2.%% show mosaic in Matlab Figure window%log = figure('Name'.'canny'. which you give at the Matlab command prompt.'Canny: UL: s=1 UR: s=2 BL: s=3 BR: s=4').tif'.'tight').2.

% Pre-allocate arrayfor row = 1:rmax. []). Read in an image This uses the local function teachimage to read an image from disc. You will also need to execute it at the start of each future session. The size function operates on any matrix. Diffs = zeros(rmax.addpath H:teachComputerVisionmatlab If you are running this as a script on Informatics machines.imshow(Image). Image = teachimage('edin_lib. col). [rmax. cmax-1). or you can just type it in or cut and paste it each time. % Loop over rows for col = 1:cmax-1. You can do this by copying it to a startup. you can uncomment the line above to execute it. Find out the size of the image Print the number of rows and the number of columns.m file in the directory (folder) in which you start up Matlab. cmax] = size(Image) rmax = 314 cmax = 469 Simple image processing (conventional version) Subtract each pixel from the one on its right. col+1) . We then use the Matlab function imshow to display it in a figure window. using loops and indexing as in ordinary languages. endend % display the resultimshow(Diffs. col) = Image(row.bmp'). and convert it correctly to a gray-level array with values in the range 0-1. not just ones holding image data. % Loop over columns Diffs(row. level scaling % Note the [] gives automatic grey- Simple image processing (Matlab version) .Image(row.

Nx2.2.Sigmay1=1. % The algorithm parameters: % 1. % Miss off the rightmost columnIm2 = Image(:. We then print out the largest absolute difference to check that the results are the same as before.Im1.gif [x.map). imagesc(w.Sigmay2=1. Ix= conv2(w. The outputs are six subfigures shown in the same figure: y y y y y y Subfigure 1: The initial "lena" Subfigure 2: Edge detection along X-axis direction Subfigure 3: Edge detection along Y-axis direction Subfigure 4: The Norm of the image gradient Subfigure 5: The Norm of the gradient after thresholding Subfigure 6: The edges detected by thinning The matlab codes: %%%%%%%%%%%%% The main.m file %%%%%%%%%%%%%%% clear. . The thresholding parameter alfa: alfa=0.colormap(gray).Ny2=10. % 2. w=ind2gray(x.200). % Get the initial image lena.map]=gifread('lena.gif'). 2:cmax).Sigmax1. title('Ix').1). 1:cmax-1). % X-axis direction edge detection subplot(3.'same').Sigmax2. % Y-axis direction filter: Ny1=10. Im1 = Image(:. imagesc(Ix).Theta2=0.gif'). subplot(3.Nx2=10. using Matlab matrix operations.Sigmax2=1. % Subtract pixel values maximum_difference = max(max(abs(Diffs-Diffs2))) maximum_difference = 0 Canny edge detector algorithm matlab codes This part gives the algorithm of Canny edge detector. Parameters of edge detecting filters: % X-axis direction filter: Nx1=10.filterx.Theta1). filterx=d2dgauss(Nx1. % Miss off the leftmost columnDiffs2 = Im2 .Now the same operation.1.2.2).Theta1=pi/2.Sigmax1=1. figure(1). title('Image: lena. which are very much faster and simpler to write.

j).Ibw(i+1. if Ibw(i.2. imagesc(Iy).% Y-axis direction edge detection subplot(3.j)/NVI(i. NVI=sqrt(Ix.*Ix+Iy. level=alfa*(I_max-I_min)+I_min.+1]. title('Norm of Gradient').0.level.j)=I_min.j)/NVI(i. I_min=min(min(NVI)). imagesc(Ibw).Ibw(i-1. title('After Thinning'). for j=2:m-1. colormap(gray).+1.Ny2.filtery.-1.+1]. %%%%%%%%%%%%%% End of the main.Ibw(i-1.j)].j)].Y. theta is the angle that . else I_temp(i. X=[-1. % Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.0.-1. if Ibw(i.'same'). for i=2:n-1.m file %%%%%%% % Function "d2dgauss.+1.j+1).j) >= ZI(2) I_temp(i.m]=size(Ibw).*Iy).j-1).) subplot(3.0.j+1)]. end end end imagesc(I_temp).+1.XI. Ibw=max(NVI. [n. end else I_temp(i.YI).j). -Ix(i. title('After Thresholding').6).-1.j+1).j-1). -Iy(i.Sigmay1.j).m file %%%%%%%%%%%%%%% %%%%%%% The functions used in the main.4).j)=I_min. YI=[Iy(i.Ibw(i.2.2.Ibw(i.j) >= ZI(1) & Ibw(i. Z=[Ibw(i-1.j)=I_max.j-1).Z.-1.2. XI=[Ix(i.0.j)/NVI(i.j) > level. ZI=interp2(X. Iy=conv2(w. title('Iy'). Ibw(i.0.*ones(size(NVI))).Theta2).j). Ibw(i+1. imagesc(NVI). Y=[-1.Sigmay2. % Norm of the gradient (Combining the X and Y directional derivatives) subplot(3.j). % Thresholding I_max=max(max(NVI)).m": % This function returns a 2D edge detector (first order derivative % of 2D Gaussian function) with size n1*n2.j)/NVI(i.0.3) filtery=d2dgauss(Ny1. subplot(3.Ibw(i+1.+1.5).

sigma1)*dgauss(u(2).j) = gauss(u(1). function h = d2dgauss(n1.sigma2).sigma1.std) y = -x * gauss(x.theta) r=[cos(theta) -sin(theta). and sigma1 and sigma2 are the % standard deviation of the gaussian functions.sigma2. for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'. % Function "gauss. % Function "dgauss. end end h = h / sqrt(sum(sum(abs(h). sin(theta) cos(theta)].m": function y = gauss(x.n2.m"(first order derivative of gauss function): function y = dgauss(x. h(i.std) y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)).*abs(h)))). %%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%% .std) / std^2.% the detector rotated counter clockwise.