Image MATLAB implementation of canny detection (with code)

Source: Internet
Author: User

Original articles, welcome reprint. Reprint Please specify: Reproduced from Cheung's blog

Original link: http://blog.csdn.net/humanking7/article/details/46606791

The edge of image refers to the part where the brightness of the image is changed significantly, and the gray section of the region can be regarded as a step, which changes from one gray value to another in a very small buffer area to a gray scale with a large difference.

The basic features of canny edge detection are as follows:

(1) must meet two conditions: ① can effectively suppress the noise; ② must determine the position of the edge as precisely as possible.
(2) The optimal approximation operator is obtained based on the measurement of SNR and the product of positioning. This is the canny edge detection operator.
(3) similar to the Marr (LoG) edge detection method, also belongs to the first smoothing after the derivative number method.

Canny edge detection algorithm steps:

Step 1: Smooth processing of the original image with Gaussian filter;
Step 2: Calculate the amplitude and direction of the gradient with the finite difference of the first order bias;
Step 3: The gradient amplitude of the non-maximal value inhibition;
Step 4: Detect and connect the edges with a double-threshold algorithm.

Step 1: Smoothing the original image with a Gaussian filter



The reason for using smoothing filtering is essentially the derivative calculation in the edge detection operator. Derivative calculation is very sensitive to noise, if the filter is not used in advance, then after the derivative calculation, the noise will be amplified, so that the false edge detected more, not conducive to edge extraction.

Smoothing filtering and edge detection are a couple of conflicting concepts. On the one hand, smoothing filtering can effectively suppress the noise, and in this process, the edge of the image is blurred, which increases the uncertainty of the edge location. On the other hand, smoothing filtering can eliminate the noise which is sensitive to derivative operation in edge detection, and effectively suppress the generation of false edges. The practical engineering experience shows that Gaussian filter can provide a better compromise between anti-noise interference and precise positioning of edge detection.

Step 2: Calculate the amplitude and direction of the gradient with the finite difference of the first order bias

The edge of the image has a direction and amplitude of two properties, along the edge of the direction of the pixel changes gently, perpendicular to the edge of the direction of the pixel changes sharply, the edge of this change can be detected by differential operators, usually using first-order or second derivative to detect the edge.


As can be seen, the first derivative can be used to detect whether a point in the image is an edge point (that is, to determine whether a point is on the ramp). Similarly, the sign of the second derivative can be used to determine whether an edge pixel is on the bright side or the dark side.
The amplitude and direction of the gradient are calculated by using the finite difference of first order bias.

, a gradient of three-dimensional B is obtained after a gradient calculation. The x and y in Figure B represent the image pixel position, and the vertical axis values reflect the magnitude of the gradient amplitude. The equation (3-17) indicates that the edge direction is perpendicular to the gradient direction, and B is shown.

Step 3: Non-maximal suppression of the gradient amplitude

Step 4: Detect and connect edges with a dual-threshold algorithm

Code main function code

Main function code filemain.m

Clear ALL;CLEARCLC;% read-in image[filename, pathname]= Uigetfile ({' *.jpg '; ' *.bmp '; ' *.gif '},' Select Picture ');% No imagesiffilename = =0    return;EndIMGSRC = Imread ([pathname, filename]);[Y, X, Dim]=size(IMGSRC);% converted to grayscaleifDim>1IMGSRC = Rgb2gray (IMGSRC);EndSigma =1; gausfilter = Fspecial (' Gaussian ',[3,3], sigma); img= IMFilter (Imgsrc, Gausfilter,' Replicate '); zz = Double (IMG);%---------------------------------------------------------- % of its own edge detection function [M theta sector canny1 Canny2 bin]= Canny1step (IMG, A);[MSRC thetasrc sectorsrc c1src c2src binsrc]= Canny1step (IMGSRC, A);%matlab self-band Edge detectioned = Edge (IMG,' Canny ',0.5);[xx, yy]=Meshgrid(1: X,1: y); figure (1)%mesh (yy, XX, ZZ);Surf (yy, XX, ZZ); Xlabel (' y '); Ylabel (' x '); Zlabel (' grayscale '); Axis Tightfigure (2) Subplot (4,2,1); Imshow (IMGSRC);% OriginalSubplot (4,2,2); Imshow (IMG);after the% Gaussian filterSubplot (4,2,3); Imshow (Uint8 (m));% derivativeSubplot (4,2,4); Imshow (Uint8 (CANNY1));% non-maximal value suppressionSubplot (4,2,5); Imshow (Uint8 (Canny2));% double threshold valueSubplot (4,2,6); Imshow (ed);%matlab self-band Edge detectionSubplot (4,2,8); Imshow (BIN);% of my own binFigure3) Edzz =255*double (ed);    Mesh (YY,XX,EDZZ); Xlabel (' y '); Ylabel (' x '); Zlabel (' grayscale '); Axis Tight figure (4) mesh (yy,xx,m);% Draw partial derivativeXlabel (' y '); Ylabel (' x '); Zlabel (' derivative '); Axis Tight figure (5) mesh (Yy,xx,theta); Xlabel (' y '); Ylabel (' x '); Zlabel (' Theta '); Axis Tightfigure (6) mesh (yy,xx,sector); Xlabel (' y '); Ylabel (' x '); Zlabel (' Sector '); Axis Tightfigure (7) mesh (YY,XX,CANNY2); Xlabel (' y '); Ylabel (' x '); Zlabel (' Sector '); Axis Tight
Canny Edge detection function code

Canny Edge detection function filecanny1step.m

function [M, theta, Sector, CANNY1, canny2, bin] = Canny1step (src, lowth) The first step of the%canny function is to go to the X, y direction of the deflector, the template is as follows:%Gx%1-1%1-1%Gy% -1-1%1    1%------------------------------------% Input:% src: image, if not grayscale image converted to grayscale lowth: Low threshold% output:% m: two biased squared difference, reflecting edge strength% theta: reflects the direction of the edge% Sector: Divide the direction into3Areas, as follows%2 1 0%3 X 3%0 1 2% CANNY1: Non-maxima% Canny2: Dual threshold suppression% Bin: two value%--------------------------------------- [Ay AxDim] = Size (src),% converted to grayscaleifDim>1src = rgb2gray (src);Endsrc = double (src); m = Zeros (Ay,Ax); theta = Zeros (Ay,Ax); sector = zeros (Ay,Ax); canny1 = Zeros (Ay,Ax);% non-maximal value suppression Canny2 = zeros (Ay,Ax);% double threshold detection and connection bin = zeros (Ay,Ax); fory =1:(Ay-1) forx =1:(Ax-1) GX = src (y, x) + src (y+1, x)-src (y, x+1)-SRC (y+1, x+1); Gy =-src (y, x) + src (y+1, x)-src (y, x+1) + src (y+1, x+1); M (y,x) = (gx^2+gy^2)^0.5;%--------------------------------theta (y,x) = Atand (gx/gy); tem = Theta (y,x);%--------------------------------if(tem<67.5) && (tem>22.5) sector (Y,X) =0; ElseIf (tem<22.5) && (tem>-22.5) sector (Y,X) =3; ElseIf (tem<-22.5) && (tem>-67.5) sector (Y,X) =2;ElseSector (Y,X) =1;End        %--------------------------------End    End%-------------------------% non-maximal value suppression%------> x2 1 0%3 X 3%y0 1 2 fory =2:(Ay-1) forx =2:(Ax-1)if 0= = Sector (y,x)% upper right-left lowerif(M (y,x) >m (y1, x+1)) && (M (y,x) >m (y+1, X-1)) Canny1 (y,x) = m (y,x);ElseCanny1 (y,x) =0;EndElseIf1= = Sector (y,x)% vertical directionif(M (y,x) >m (y1, x)) && (M (y,x) >m (y+1, x)) canny1 (y,x) = m (y,x);ElseCanny1 (y,x) =0;EndElseIf2= = Sector (y,x)% left upper-right lowerif(M (y,x) >m (y1, X-1)) && (M (y,x) >m (y+1, x+1)) Canny1 (y,x) = m (y,x);ElseCanny1 (y,x) =0;EndElseIf3= = Sector (y,x)% transverse directionif(M (y,x) >m (y,x+1)) && (M (y,x) >m (y,x-1)) Canny1 (y,x) = m (y,x);ElseCanny1 (y,x) =0;End        End            End%End  forXEnd%End  forY%---------------------------------% double threshold detection ratio =2; fory =2:(Ay-1) forx =2:(Ax-1)ifCanny1 (y,x) <lowth% low threshold processing Canny2 (y,x) =0; Bin (y,x) =0;        Continue            ElseIf canny1 (y,x) >ratio*lowth% High threshold processing canny2 (y,x) = Canny1 (y,x); Bin (y,x) =1; ContinueElse% in between to see its8There is no higher threshold for the field, there is the edge tem =[canny1 (Y-1, X-1), Canny1 (y1, x), Canny1 (y1, x+1); Canny1 (y,x-1), Canny1 (y,x), Canny1 (y,x+1); Canny1 (y+1, X-1), Canny1 (y+1, x), Canny1 (y+1, x+1)]; Temmax = max (TEM);ifTemmax (1) > Ratio*lowth canny2 (y,x) = Temmax (1); Bin (y,x) =1; ContinueElseCanny2 (y,x) =0; Bin (y,x) =0; ContinueEnd        End    End%End  forXEnd%End  forYEnd%Endof function
Results Compare and contrast images

Analysis

The four images shown in Figure 2 show the entire edge detection process.

    • figure (a) shows the gradient value of the image, and its three-dimensional image is shown in Figure 3 on the left.
    • figure (b) shows the image after the maximum suppression, it can be seen that after the non-maximal value suppression, the elimination of non-edge pixels, only a few thin lines, that is, the candidate edge.
    • figure (c) for the two-threshold algorithm after the processing of the two-valued image (the selected low threshold of 22, the ratio of the high and low threshold is 2:1), the contrast chart (b) found that the process effectively suppressed the "false edge", but also connected to some of the broken edges.
    • figure (d) is the use of MATLAB with the edge function of the canny method, you can see that its effect is better than I realized the traditional canny program, MATLAB in the threshold selection principle and the gradient operator has its own corresponding improvement.

Figure 3 shows the three-dimensional effect of the gradient amplitude before and after the non-maximal value rejection, corresponding to the figure (a) and figure (b) in Figure 2.

Note: the image and code used in this article are derived from my bi-set thesis.

Image MATLAB implementation of canny detection (with code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.