Top Banner
Matlab Image Processing With Code (New updates) February 5, 2010 Print Article Citation , XML Email Authors 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 below code.
26
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Matlab Image hint

Matlab Image   Processing With Code (New updates)

February 5, 2010 Print Article Citation , XML

Email

Authors

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 below code.close allclear allclc

% 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

Page 2: Matlab Image hint

% Gaussian filter parametersigma=1.2;% Gaussian filterG=fspecial('gaussian',15,sigma);% Gaussian smoothed imageinpImage=conv2(inpImage,G,'same');

% gradient of image[gradIX,gradIY]=gradient(inpImage);absGradI=sqrt(gradIX.^2+gradIY.^2);

% higher dimensional embedding function phi whose zero level set is our% contour% radius of circle - initial embedding function% radius=min(floor(0.45*rows),floor(0.45*cols));[u,v] = meshgrid(1:cols, 1:rows);phi = ((u-cols/2)/(floor(0.45*cols))).^2+((v-rows/2)/(floor(0.45*rows))).^2-1;

% edge-stopping functiong = 1./(1+absGradI.^2);% gradient of edge-stopping function[gx,gy]=gradient(g);

% gradient descent step sizedt=.4;

% number of iterations after which we reinitialize the surfacenum_reinit=10;

phiOld=zeros(rows,cols);

% number of iterationsiter=0;

while(sum(sum(abs(phi-phiOld)))~=0) % gradient of phi [gradPhiX gradPhiY]=gradient(phi); % magnitude of gradient of phi absGradPhi=sqrt(gradPhiX.^2+gradPhiY.^2); % normalized gradient of phi - eliminating singularities normGradPhiX=gradPhiX./(absGradPhi+(absGradPhi==0)); normGradPhiY=gradPhiY./(absGradPhi+(absGradPhi==0));

[divXnormGradPhiX divYnormGradPhiX]=gradient(normGradPhiX); [divXnormGradPhiY divYnormGradPhiY]=gradient(normGradPhiY); % curvature is the divergence of normalized gradient of phi K = divXnormGradPhiX + divYnormGradPhiY; % dPhiBydT dPhiBydT =( g.*K.*absGradPhi + g.*absGradPhi + (gx.*gradPhiX+gy.*gradPhiY) ); phiOld=phi; % level set evolution equation phi = phi + ( dt * dPhiBydT ); iter=iter+1; if mod(iter,num_reinit)==0 % reinitialize the embedding function after num_reinit iterations phi=sign(phi); phi = double((phi > 0).*(bwdist(phi < 0)) - (phi < 0).*(bwdist(phi > 0))); end if mod(iter,10)==0 pause(0.05) iter imagesc(inpImage) colormap(gray) hold on contour(phi,[0 0],'r') % close all % surf(phi) % pause endend

Image Thresholding This demo shows how a image looks like after thresholding. The percentage of the thresholding means the threshold level between the maximum and minimum indesity of the initial image. Thresholding is a way to get rid of the effect of noise and to improve the signal-noise ratio. That is, it is a way to keep the significant imformation of the image while get rid of the unimportant part (under the condition that you choose a plausible thresholding level). In the Canny edge

Page 3: Matlab Image hint

detector part, you will see that, before thinning, we first do some thresholding. You are encouraged to do thinning without thresholding and to see what is the advantage of thresholding.

lena.gif 10% threshold20% threshold 30% threshold

Image Thresholding Matlab CodesThis program show the effect of thresholding. The output are four subfigures shown in the same figure:

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;% Threshold level parameter alfa:alfa=0.1;% less than 1/3

[x,map]=gifread('lena.gif');ix=ind2gray(x,map);I_max=max(max(ix));I_min=min(min(ix));level1=alfa*(I_max-I_min)+I_min;level2=2*level1;level3=3*level1;thix1=max(ix,level1.*ones(size(ix)));thix2=max(ix,level2.*ones(size(ix)));thix3=max(ix,level3.*ones(size(ix)));figure(1);colormap(gray);subplot(2,2,1);imagesc(ix);title('lena');subplot(2,2,2);imagesc(thix1);title('threshold one alfa');subplot(2,2,3);imagesc(thix2);title('threshold two alfa');subplot(2,2,4);imagesc(thix3);title('threshold three alfa');%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%

Gaussian function   These demos show the basic effects of the (2D) Gaussian filter: smoothing the image and wiping off the noise. Generally speaking, for a noise-affected image, smoothing it by Gaussian function is the first thing to do before any other further processing, such as edge detection. The effectiveness of the gaussian function is different for different choices of the standard deviation sigma of the Gaussian filter. You can see this from the following demos.

Smoothing nonnoisy image

lena.gif filtered with sigma = 3 filtered with sigma = 1

Noise cancelling

Page 4: Matlab Image hint

noisy lena filtered with sigma = 3 filtered with sigma =1

(Noise is generated by matlab function 0.3*randn(512))

Gaussian filter study matlab codesThis program show the effect of Gaussian filter. The output are four subfigures shown in the same figure:

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.m file %%%%%%%%%%%%%%%clear;%

Parameters of the Gaussian filter:n1=10;sigma1=3;n2=10;sigma2=3;theta1=0;% The amplitude of the noise:noise=0.1;

[w,map]=gifread('lena.gif');

x=ind2gray(w,map);filter1=d2gauss(n1,sigma1,n2,sigma2,theta);x_rand=noise*randn(size(x));y=x+x_rand;f1=conv2(x,filter1,'same');rf1=conv2(y,filter1,'same');figure(1);subplot(2,2,1);imagesc(x);subplot(2,2,2);imagesc(y);subplot(2,2,3);imagesc(f1);subplot(2,2,4);imagesc(rf1);colormap(gray);%%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%%

%%%%%%% The functions used in the main.m file %%%%%%%% Function

"d2gauss.m":% This function returns a 2D Gaussian filter with size n1*n2; theta is % the angle that the filter rotated counter clockwise; and sigma1 and sigma2% are the standard deviation of the gaussian functions.function h = d2gauss(n1,std1,n2,std2,theta)r=[cos(theta) -sin(theta); sin(theta) cos(theta)];for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),std1)*gauss(u(2),std2); endendh = h / sqrt(sum(sum(h.*h)));

% Function "gauss.m":function y = gauss(x,std)y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi));%%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%%%%

Canny edge detector   There are some results of applying Canny edge detector to real image (The black and white image “lena.gif” we used here was obtained by translating from a color lena.tiff using matlab. So it might not be the standard BW “lena”.) The thresholding parameter alfa is fix as 0.1. The size of the filters is also fixed as 10*10.

Page 5: Matlab Image hint

These images are all gray images though they might seem a little strange in your browser. To see them more clearly, just click these images and you will find the difference especially from the “result images”, that is, the titled “after thinning” ones. The safe way to see the correct display of these images is to grab these images and show them by “xv” or “matlab”. While, you are encouraged to use the given matlab codes and get these images in matlab by yourself. Try to change the parameters to get more sense about how these parameters affect the edge detection.

The results of choosing the standard deviation sigma of the edge detectors as 3.

lena.gif vertical edges horizontal edgesnorm of the gradient after thresholding after thinning

The results of choosing the standard deviation sigma of the edge detectors as 1.

lena.gif vertical edges horizontal edgesnorm of the gradient after thresholding after thinning

Canny edge detector algorithm matlab codesThis part gives the algorithm of Canny edge detector. The outputs are six subfigures shown in the same figure:

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 algorithm parameters:% 1. Parameters of edge detecting filters:% X-axis direction filter: Nx1=10;Sigmax1=1;Nx2=10;Sigmax2=1;Theta1=pi/2;% Y-axis direction filter: Ny1=10;Sigmay1=1;Ny2=10;Sigmay2=1;Theta2=0;% 2. The thresholding parameter alfa: alfa=0.1;

% Get the initial image lena.gif[x,map]=gifread('lena.gif'); w=ind2gray(x,map);figure(1);colormap(gray);subplot(3,2,1);imagesc(w,200);title('Image: lena.gif');

Page 6: Matlab Image hint

% X-axis direction edge detectionsubplot(3,2,2);filterx=d2dgauss(Nx1,Sigmax1,Nx2,Sigmax2,Theta1);Ix= conv2(w,filterx,'same');imagesc(Ix);title('Ix');

% Y-axis direction edge detectionsubplot(3,2,3)filtery=d2dgauss(Ny1,Sigmay1,Ny2,Sigmay2,Theta2);Iy=conv2(w,filtery,'same'); imagesc(Iy);title('Iy');

% Norm of the gradient (Combining the X and Y directional derivatives)subplot(3,2,4);NVI=sqrt(Ix.*Ix+Iy.*Iy);imagesc(NVI);title('Norm of Gradient');

% ThresholdingI_max=max(max(NVI));I_min=min(min(NVI));level=alfa*(I_max-I_min)+I_min;subplot(3,2,5);Ibw=max(NVI,level.*ones(size(NVI)));imagesc(Ibw);title('After Thresholding');

% Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.)subplot(3,2,6);[n,m]=size(Ibw);for i=2:n-1,for j=2:m-1, if Ibw(i,j) > level, X=[-1,0,+1;-1,0,+1;-1,0,+1]; Y=[-1,-1,-1;0,0,0;+1,+1,+1]; Z=[Ibw(i-1,j-1),Ibw(i-1,j),Ibw(i-1,j+1); Ibw(i,j-1),Ibw(i,j),Ibw(i,j+1); Ibw(i+1,j-1),Ibw(i+1,j),Ibw(i+1,j+1)]; XI=[Ix(i,j)/NVI(i,j), -Ix(i,j)/NVI(i,j)]; YI=[Iy(i,j)/NVI(i,j), -Iy(i,j)/NVI(i,j)]; ZI=interp2(X,Y,Z,XI,YI); if Ibw(i,j) >= ZI(1) & Ibw(i,j) >= ZI(2) I_temp(i,j)=I_max; else I_temp(i,j)=I_min; end else I_temp(i,j)=I_min; endendendimagesc(I_temp);title('After Thinning');colormap(gray);%%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%%

%%%%%%% The functions used in the main.m file %%%%%%%% Function "d2dgauss.m":% This function returns a 2D edge detector (first order derivative% of 2D Gaussian function) with size n1*n2; theta is the angle that% the detector rotated counter clockwise; and sigma1 and sigma2 are the% standard deviation of the gaussian functions.function h = d2dgauss(n1,sigma1,n2,sigma2,theta)r=[cos(theta) -sin(theta); sin(theta) cos(theta)];for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),sigma1)*dgauss(u(2),sigma2); endendh = h / sqrt(sum(sum(abs(h).*abs(h))));

% Function "gauss.m":function y = gauss(x,std)y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi));

% Function "dgauss.m"(first order derivative of gauss function):function y = dgauss(x,std)y = -x * gauss(x,std) / std^2;%%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%

——————————————————————————————————————————————-

MATLAN IMAGE PROCESSING : EDGE DETECTION FUNCTION  

Page 7: Matlab Image hint

Marr/Hildreth and Canny Edge Detection with m-code

Recall the wagon wheel test image used in the   resampling   example:

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

Page 8: Matlab Image hint

As most commonly implemented, Canny edge detection is based on extrema of the first derivative of the Gaussian operator applied to the image for various values of sigma, the standard deviation of the Gaussian. 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 top right is sigma=2, the bottom left is sigma=3 and the bottom right is sigma=4. The Canny method uses two thresholds to link edge points. The Matlab implementation can estimate both thesholds automatically. For this example, I found the Matlab estimated thresholds to be somewhat conservative. Therefore, for the mosaic, I reduced the thresholds to 75 percent of their automatically estimated values.

Page 9: Matlab Image hint

You should observe that zero-crossings in Marr/Hildreth edge detection always form connected, closed contours (or leave the edge of the image). This comes, however, at the expense of localization, especially for larger values of sigma. Arguably, Canny edge detection does a better job of localization. Alas, with Canny edge detection, the edge segments can become disconnected

For above example, m-code is below:

% Image Processing Toolbox Version 5.4(R2007a)

A = imread('/ai/woodham/public_html/cpsc505/images/wheel.tif');

% Marr/Hildreth edge detection% with threshold forced to zeroMH1 = edge(A,'log',0,1.0);MH2 = edge(A,'log',0,2.0);MH3 = edge(A,'log',0,3.0);MH4 = edge(A,'log',0,4.0);

% form mosaicEFGH = [ MH1 MH2; MH3 MH4];

Page 10: Matlab Image hint

%% show mosaic in Matlab Figure window%log = figure('Name','Marr/Hildreth: UL: s=1 UR: s=2 BL: s=3 BR: s=4');%iptsetpref('ImshowBorder','tight');%imshow(EFGH,'InitialMagnification',100);

% Canny edge detection[C1, Ct1] = edge(A,'canny',[],1.0);[C2, Ct2] = edge(A,'canny',[],2.0);[C3, Ct3] = edge(A,'canny',[],3.0);[C4, Ct4] = edge(A,'canny',[],4.0);

% Recompute lowering both automatically computed% thresholds by fraction kk = 0.75C1 = edge(A,'canny',k*Ct1,1.0);C2 = edge(A,'canny',k*Ct2,2.0);C3 = edge(A,'canny',k*Ct3,3.0);C4 = edge(A,'canny',k*Ct4,4.0);

% form mosaicABCD= [ C1 C2; C3 C4 ];

% show mosaic in Matlab Figure window%canny = figure('Name','Canny: UL: s=1 UR: s=2 BL: s=3 BR: s=4');%iptsetpref('ImshowBorder','tight');%imshow(ABCD,'InitialMagnification',100);

% write results to file% Note: Matlab no longer reads/writes GIF files, owing to licence% restrictions. Translation from TIF to GIF was done% manually (with xv) for inclusion in the web example pageimwrite(ABCD,'/ai/woodham/World/cpsc505/images/canny.tif','tif');imwrite(EFGH,'/ai/woodham/World/cpsc505/images/log.tif','tif');

Matlab image processing introductionThis is to help you get started with image processing in Matlab.

Contents

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. (If you run the whole script, the results will overwrite each other.) You can execute a few lines by copying them into the Matlab Command Window. Alternatively, you can view the script in the editor, and activate Cell Mode from the Cell menu. Then you can click in a cell (a section between two headings) to highlight it and click the “Evaluate cell” icon, or press CTRL-ENTER, to execute it.

First you must set your Matlab path to find the Sussex Matlab computer vision teaching libraries. At the time of writing, the command, which you give at the Matlab command prompt, is

Page 11: Matlab Image hint

addpath H:teachComputerVisionmatlab

If you are running this as a script on Informatics machines, you can uncomment the line above to execute it. You will also need to execute it at the start of each future session. You can do this by copying it to a startup.m file in the directory (folder) in which you start up Matlab, or you can just type it in or cut and paste it each time.

Read in an image

This uses the local function teachimage to read an image from disc, and convert it correctly to a gray-level array with values in the range 0-1.

We then use the Matlab function imshow to display it in a figure window.

Image = teachimage('edin_lib.bmp');imshow(Image);

Find out the size of the image

Print the number of rows and the number of columns. The size function operates on any matrix, not just ones holding image data.

[rmax, cmax] = size(Image)rmax =

314

cmax =

469

Simple image processing (conventional version)

Subtract each pixel from the one on its right, using loops and indexing as in ordinary languages.

Diffs = zeros(rmax, cmax-1); % Pre-allocate arrayfor row = 1:rmax; % Loop over rows for col = 1:cmax-1; % Loop over columns Diffs(row, col) = Image(row, col+1) - Image(row, col); endend

% display the resultimshow(Diffs, []); % Note the [] gives automatic grey-level scaling

Simple image processing (Matlab version)

Page 12: Matlab Image hint

Now the same operation, using Matlab matrix operations, which are very much faster and simpler to write. We then print out the largest absolute difference to check that the results are the same as before.

Im1 = Image(:, 1:cmax-1); % Miss off the rightmost columnIm2 = Image(:, 2:cmax); % Miss off the leftmost columnDiffs2 = Im2 - Im1; % Subtract pixel values

maximum_difference = max(max(abs(Diffs-Diffs2)))maximum_difference =

0

Canny edge detector algorithm matlab codesThis part gives the algorithm of Canny edge detector. The outputs are six subfigures shown in the same figure:

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 algorithm parameters:% 1. Parameters of edge detecting filters:% X-axis direction filter: Nx1=10;Sigmax1=1;Nx2=10;Sigmax2=1;Theta1=pi/2;% Y-axis direction filter: Ny1=10;Sigmay1=1;Ny2=10;Sigmay2=1;Theta2=0;% 2. The thresholding parameter alfa: alfa=0.1; % Get the initial image lena.gif[x,map]=gifread('lena.gif'); w=ind2gray(x,map);figure(1);colormap(gray);subplot(3,2,1);imagesc(w,200);title('Image: lena.gif');

% X-axis direction edge detectionsubplot(3,2,2);filterx=d2dgauss(Nx1,Sigmax1,Nx2,Sigmax2,Theta1);Ix= conv2(w,filterx,'same');imagesc(Ix);title('Ix');

Page 13: Matlab Image hint

% Y-axis direction edge detectionsubplot(3,2,3)filtery=d2dgauss(Ny1,Sigmay1,Ny2,Sigmay2,Theta2);Iy=conv2(w,filtery,'same'); imagesc(Iy);title('Iy');

% Norm of the gradient (Combining the X and Y directional derivatives)subplot(3,2,4);NVI=sqrt(Ix.*Ix+Iy.*Iy);imagesc(NVI);title('Norm of Gradient');

% ThresholdingI_max=max(max(NVI));I_min=min(min(NVI));level=alfa*(I_max-I_min)+I_min;subplot(3,2,5);Ibw=max(NVI,level.*ones(size(NVI)));imagesc(Ibw);title('After Thresholding');

% Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.)subplot(3,2,6);[n,m]=size(Ibw);for i=2:n-1,for j=2:m-1,

if Ibw(i,j) > level,X=[-1,0,+1;-1,0,+1;-1,0,+1];Y=[-1,-1,-1;0,0,0;+1,+1,+1];Z=[Ibw(i-1,j-1),Ibw(i-1,j),Ibw(i-1,j+1); Ibw(i,j-1),Ibw(i,j),Ibw(i,j+1); Ibw(i+1,j-1),Ibw(i+1,j),Ibw(i+1,j+1)];XI=[Ix(i,j)/NVI(i,j), -Ix(i,j)/NVI(i,j)];YI=[Iy(i,j)/NVI(i,j), -Iy(i,j)/NVI(i,j)];ZI=interp2(X,Y,Z,XI,YI);

if Ibw(i,j) >= ZI(1) & Ibw(i,j) >= ZI(2)I_temp(i,j)=I_max;elseI_temp(i,j)=I_min;end

elseI_temp(i,j)=I_min;end

endendimagesc(I_temp);title('After Thinning');colormap(gray);%%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%%

%%%%%%% The functions used in the main.m file %%%%%%%% Function "d2dgauss.m":% This function returns a 2D edge detector (first order derivative

Page 14: Matlab Image hint

% of 2D Gaussian function) with size n1*n2; theta is the angle that% the detector rotated counter clockwise; and sigma1 and sigma2 are the% standard deviation of the gaussian functions.function h = d2dgauss(n1,sigma1,n2,sigma2,theta)r=[cos(theta) -sin(theta); sin(theta) cos(theta)];for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),sigma1)*dgauss(u(2),sigma2); endendh = h / sqrt(sum(sum(abs(h).*abs(h))));

% Function "gauss.m":function y = gauss(x,std)y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi));

% Function "dgauss.m"(first order derivative of gauss function):function y = dgauss(x,std)y = -x * gauss(x,std) / std^2;%%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%

Page 15: Matlab Image hint

edge - Find edges in grayscale image

Note

The syntax BW = edge(... ,K) has been removed. Use the BW = edge(... ,direction) syntax instead.

The syntax edge(I,'marr-hildreth',...) has been removed. Use the edge(I,'log',...) syntax instead.

Syntax

I=imread(‘xx.jpg’);imshow(I);BW = edge(I)BW1=edge(I,’sobel’);BW@=edge(I,’canny’);Figure,imshow(BW1);Figure,imshow(BW2);

BW = edge(I,'sobel')BW = edge(I,'sobel',thresh)BW = edge(I,'sobel',thresh,direction)[BW,thresh] = edge(I,'sobel',...)

BW = edge(I,'prewitt')BW = edge(I,'prewitt',thresh)BW = edge(I,'prewitt',thresh,direction)[BW,thresh] = edge(I,'prewitt',...)

Page 16: Matlab Image hint

BW = edge(I,'roberts')BW = edge(I,'roberts',thresh)[BW,thresh] = edge(I,'roberts',...)

BW = edge(I,'log')BW = edge(I,'log',thresh)BW = edge(I,'log',thresh,sigma)[BW,threshold] = edge(I,'log',...)

BW = edge(I,'zerocross',thresh,h)[BW,thresh] = edge(I,'zerocross',...)

BW = edge(I,'canny')BW = edge(I,'canny',thresh)BW = edge(I,'canny',thresh,sigma)[BW,threshold] = edge(I,'canny',...)

Description

BW = edge(I) takes a grayscale or a binary image I as its input, and returns a binary image BW of the same size as I, with 1's where the function finds edges in I and 0's elsewhere.

By default, edge uses the Sobel method to detect edges but the following provides a complete list of all the edge-finding methods supported by this function:

The Sobel method finds edges using the Sobel approximation to the derivative. It returns edges at those points where the gradient of I is maximum.

The Prewitt method finds edges using the Prewitt approximation to the derivative. It returns edges at those points where the gradient of I is maximum.

The Roberts method finds edges using the Roberts approximation to the derivative. It returns edges at those points where the gradient of I is maximum.

The Laplacian of Gaussian method finds edges by looking for zero crossings after filtering I with a Laplacian of Gaussian filter.

The zero-cross method finds edges by looking for zero crossings after filtering I with a filter you specify.

The Canny method finds edges by looking for local maxima of the gradient of I. The gradient is calculated using the derivative of a Gaussian filter. The method uses two thresholds, to detect strong and weak edges, and includes the weak edges in the output only if they are connected to strong edges. This method is therefore less likely than the others to be fooled by noise, and more likely to detect true weak edges.

The parameters you can supply differ depending on the method you specify. If you do not specify a method, edge uses the Sobel method.

Sobel Method

BW = edge(I,'sobel') specifies the Sobel method.

Page 17: Matlab Image hint

BW = edge(I,'sobel',thresh) specifies the sensitivity threshold for the Sobel method. edge ignores all edges that are not stronger than thresh. If you do not specify thresh, or if thresh is empty ([]), edge chooses the value automatically.

BW = edge(I,'sobel',thresh,direction) specifies the direction of detection for the Sobel method. direction is a string specifying whether to look for 'horizontal' or 'vertical' edges or 'both' (the default).

BW = edge(I,'sobel',...,options) provides an optional string input. String 'nothinning' speeds up the operation of the algorithm by skipping the additional edge thinning stage. By default, or when 'thinning' string is specified, the algorithm applies edge thinning.

[BW,thresh] = edge(I,'sobel',...) returns the threshold value.

[BW,thresh,gv,gh] = edge(I,'sobel',...) returns vertical and horizontal edge responses to Sobel gradient operators. You can also use the following expressions to obtain gradient responses:

if ~(isa(I,'double') || isa(I,'single')); I = im2single(I); endgh = imfilter(I,fspecial('sobel') /8,'replicate');gv = imfilter(I,fspecial('sobel')'/8,'replicate');

Prewitt Method

BW = edge(I,'prewitt') specifies the Prewitt method.

BW = edge(I,'prewitt',thresh) specifies the sensitivity threshold for the Prewitt method. edge ignores all edges that are not stronger than thresh. If you do not specify thresh, or if thresh is empty ([]), edge chooses the value automatically.

BW = edge(I,'prewitt',thresh,direction) specifies the direction of detection for the Prewitt method. direction is a string specifying whether to look for 'horizontal' or 'vertical' edges or 'both' (the default).

[BW,thresh] = edge(I,'prewitt',...) returns the threshold value.

Roberts Method

BW = edge(I,'roberts') specifies the Roberts method.

BW = edge(I,'roberts',thresh) specifies the sensitivity threshold for the Roberts method. edge ignores all edges that are not stronger than thresh. If you do not specify thresh, or if thresh is empty ([]), edge chooses the value automatically.

BW = edge(I,'roberts',...,options) where options can be the text string 'thinning' or 'nothinning'. When you specify 'thinning', or don't specify a value, the algorithm applies

Page 18: Matlab Image hint

edge thinning. Specifying the 'nothinning' option can speed up the operation of the algorithm by skipping the additional edge thinning stage.

[BW,thresh] = edge(I,'roberts',...) returns the threshold value.

[BW,thresh,g45,g135] = edge(I,'roberts',...) returns 45 degree and 135 degree edge responses to Roberts gradient operators. You can also use these expressions to obtain gradient responses:

if ~(isa(I,'double') || isa(I,'single')); I = im2single(I);

endg45 = imfilter(I,[1 0; 0 -1]/2,'replicate');g135 = imfilter(I,[0 1;-1 0]/2,'replicate');

Laplacian of Gaussian Method

BW = edge(I,'log') specifies the Laplacian of Gaussian method.

BW = edge(I,'log',thresh) specifies the sensitivity threshold for the Laplacian of Gaussian method. edge ignores all edges that are not stronger than thresh. If you do not specify thresh, or if thresh is empty ([]), edge chooses the value automatically. If you specify a threshold of 0, the output image has closed contours, because it includes all the zero crossings in the input image.

BW = edge(I,'log',thresh,sigma) specifies the Laplacian of Gaussian method, using sigma as the standard deviation of the LoG filter. The default sigma is 2; the size of the filter is n-by-n, where n = ceil(sigma*3)*2+1.

[BW,thresh] = edge(I,'log',...) returns the threshold value.

Zero-Cross Method

BW = edge(I,'zerocross',thresh,h) specifies the zero-cross method, using the filter h. thresh is the sensitivity threshold; if the argument is empty ([]), edge chooses the sensitivity threshold automatically. If you specify a threshold of 0, the output image has closed contours, because it includes all the zero crossings in the input image.

[BW,thresh] = edge(I,'zerocross',...) returns the threshold value.

Canny Method

BW = edge(I,'canny') specifies the Canny method.

BW = edge(I,'canny',thresh) specifies sensitivity thresholds for the Canny method. thresh is a two-element vector in which the first element is the low threshold, and the second element is the high threshold. If you specify a scalar for thresh, this scalar value is used for the high

Page 19: Matlab Image hint

threshold and 0.4*thresh is used for the low threshold. If you do not specify thresh, or if thresh is empty ([]), edge chooses low and high values automatically. The value for thresh is relative to the highest value of the gradient magnitude of the image.

BW = edge(I,'canny',thresh,sigma) specifies the Canny method, using sigma as the standard deviation of the Gaussian filter. The default sigma is sqrt(2); the size of the filter is chosen automatically, based on sigma.

[BW,thresh] = edge(I,'canny',...) returns the threshold values as a two-element vector.

Class Support

I is a nonsparse numeric array. BW is of class logical.

Tips

For the gradient-magnitude methods (Sobel, Prewitt, Roberts), thresh is used to threshold the calculated gradient magnitude. For the zero-crossing methods, including Lap, thresh is used as a threshold for the zero-crossings; in other words, a large jump across zero is an edge, while a small jump isn't.

The Canny method applies two thresholds to the gradient: a high threshold for low edge sensitivity and a low threshold for high edge sensitivity. edge starts with the low sensitivity result and then grows it to include connected edge pixels from the high sensitivity result. This helps fill in gaps in the detected edges.

In all cases, the default threshold is chosen heuristically in a way that depends on the input data. The best way to vary the threshold is to run edge once, capturing the calculated threshold as the second output argument. Then, starting from the value calculated by edge, adjust the threshold higher (fewer edge pixels) or lower (more edge pixels).

The function edge changed in Version 7.2 (R2011a). Previous versions of the Image Processing Toolbox used a different algorithm for computing the Canny method. If you need the same results produced by the previous implementation, use the following syntax:

BW = edge(I,'canny_old',...)

Examples

Find the edges of an image using the Prewitt and Canny methods.

I = imread('circuit.tif');BW1 = edge(I,'prewitt');BW2 = edge(I,'canny');imshow(BW1);

Page 20: Matlab Image hint

Prewitt Method

figure, imshow(BW2)

Canny Method

RADON TRANSFORM

Page 21: Matlab Image hint

I=zeros(100,100);

I(40:60,40:60)=1;

Imshow(I);

[R,xp]=radon(I,0); [R,xp]=radon(I,45);

Figure,plot(xp,R);