edge_detect.m
上传用户:hjhzmdqc
上传日期:2020-07-06
资源大小:2k
文件大小:2k
- function e = edge_detect(a,sigma)
- [m,n] = size(a);
- a=double(a);
- e = false(m,n);
- GaussianDieOff = .0001;
- PercentOfPixelsNotEdges = .7; % Used for selecting thresholds
- ThresholdRatio = .4;
- pw = 1:30; % possible widths
- ssq = sigma^2;
- width = find(exp(-(pw.*pw)/(2*ssq))>GaussianDieOff,1,'last');
- if isempty(width)
- width = 1; % the user entered a really small sigma
- end
- t = (-width:width);
- gau = exp(-(t.*t)/(2*ssq))/(2*pi*ssq); % the gaussian 1D filter
- [x,y]=meshgrid(-width:width,-width:width);
- dgau2D=-x.*exp(-(x.*x+y.*y)/(2*ssq))/(pi*ssq);
- aSmooth=imfilter(a,gau,'conv','replicate'); % run the filter accross rows
- aSmooth=imfilter(aSmooth,gau','conv','replicate'); % and then accross columns
-
- %apply directional derivatives
- ax = imfilter(aSmooth, dgau2D, 'conv','replicate');
- ay = imfilter(aSmooth, dgau2D', 'conv','replicate');
- mag = sqrt((ax.*ax) + (ay.*ay));
- magmax = max(mag(:));
- if magmax>0
- mag = mag / magmax; % normalize
- end
-
- lowThresh = 0.7*mean(mag(:));
- highThresh = 2 * lowThresh;
- idxStrong = [];
- % idxWeak = find(mag > lowThresh);
- % e(idxWeak)=1;
- % idxStrong = [idxStrong; idxWeak(mag(idxWeak) > highThresh)];
- % rstrong = rem(idxStrong-1, m)+1;
- % cstrong = floor((idxStrong-1)/m)+1;
- % e = bwselect(e, cstrong, rstrong, 8);
- % mag=uint8(255*mag);
- % imshow(mag);
- % The next step is to do the non-maximum supression.
- % We will accrue indices which specify ON pixels in strong edgemap
- % The array e will become the weak edge map.
-
- for dir = 1:4
- idxLocalMax = cannyFindLocalMaxima(dir,ax,ay,mag);
- idxWeak = idxLocalMax(mag(idxLocalMax) > lowThresh);
- e(idxWeak)=1;
- idxStrong = [idxStrong; idxWeak(mag(idxWeak) > highThresh)];
- end
-
- if ~isempty(idxStrong) % result is all zeros if idxStrong is empty
- rstrong = rem(idxLocalMax-1, m)+1;
- cstrong = floor((idxLocalMax-1)/m)+1;
- e = bwselect(e, cstrong, rstrong, 8);
- % e = bwmorph(e, 'thin', 1); % Thin double (or triple) pixel wide contours
- end
- % imshow(e);
- %
-