资源简介
canny算法,实现边缘检测。本程序主要分为4步,第一步是输入图像,第二步和第三步实现canny算法,第三步实现输出
代码片段和文件信息
function e=canny_edge(Isigma)
%functione=edge(I‘canny‘threshsigma);
%该函数实现Canny算子提取边缘点
%输入图像为I,标准差sigma,输出为边缘图像e
I=255*double(I);%将图像转化为double型
[mn]=size(I);
Rr=2:m-1;cc=2:n-1;
e=repmat(logical(uint8(0))mn);
%产生同样大小的边缘图像e,初始化为1 ,即初始化边缘
GaussianDieOff=0.0001;%设定高斯函数消失门限
PercentOfPixelsNotEdges=0.7;%用于计算边缘门限
ThresholdRatio=0.2;%设置两个门限的比例
%首先设计高斯滤波器和它的微分
pw=1:30;
%设定滤波器宽度
ssq=sigma*sigma;
%计算方差
width = find(exp(-(pw.*pw)/(2*ssq))>GaussianDieOff1‘last‘);
if isempty(width)
width = 1; %当使用者键入很小的sigma时
end
%计算滤波算子宽度
t = (-width:width);
gau = exp(-(t.*t)/(2*ssq))/(2*pi*ssq); % 一维高斯滤波器
[xy]=meshgrid(-width:width-width:width);
dgau2D=-x.*exp(-(x.*x+y.*y)/(2*ssq))/(pi*ssq);%高斯滤波器的一阶导数
%平滑图像
aSmooth=imfilter(Igau‘conv‘‘replicate‘); % 按行滤波
aSmooth=imfilter(aSmoothgau‘‘conv‘‘replicate‘); % 再按列滤波
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;
%对滤波幅度进行归一化
end
%下面根据滤波幅度的概率密度计算滤波门限
[countsx]=imhist(mag64);
%计算滤波结果的幅度的直方图
highThresh=min(find(cumsum(counts)>PercentOfPixelsNotEdges*m*n))/64;
%通过设定非边缘点的比例来确定高门限
lowThresh=ThresholdRatio*highThresh;
%设置低门限为高门限乘以比例因子
thresh=[lowThreshhighThresh];
%下面进行非极大抑制
%大于高门限的点归于强边缘图像
%小于低门限的点归于弱边缘图像
idxStrong=[];
for dir=1:4
idxLocalMax=cannyFindLocalMaxima(diraxaymag);
idxWeak=idxLocalMax(mag(idxLocalMax)>lowThresh);
e(idxWeak)=1;
idxStrong=[idxStrong;idxWeak(mag(idxWeak)>highThresh)];
end
rstrong=rem(idxStrong-1m)+1;%rem是求余数
cstrong=floor((idxStrong-1)/m)+1;%向-∞取整
e=bwselect(ecstrongrstrong8);
%通过形态学算子将两幅图像的边缘进行连接
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Local Function : cannyFindLocalMaxima
%
function idxLocalMax = cannyFindLocalMaxima(directionixiymag)
%
% This sub-function helps with the non-maximum suppression in the Canny
% edge detector. The input parameters are:
%
% direction - the index of which direction the gradient is pointing
% read from the diagram below. direction is 1 2 3 or 4.
% ix - input image filtered by derivative of gaussian along x
% iy - input image filtered by derivative of gaussian along y
% mag - the gradient magnitude image
%
% there are 4 cases:
%
% The X marks the pixel in question and each
% 3 2 of the quadrants for the gradient vector
% O----0----0 fall into two cases divided by the 45
% 4 | | 1 degree line. In one case the gradient
% | | vector is more horizontal and in the other
% O X O it is more vertical. There are eight
% | | divisions but for the non-maximum suppression
% (1)| |(4) we are only worried about 4 of them since we
% O----O----O use symmetric po
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 431818 2010-08-21 13:04 canny\3.jpg
文件 4681 2011-03-19 12:47 canny\canny_edge.m
目录 0 2011-03-24 14:01 canny
----------- --------- ---------- ----- ----
436499 3
评论
共有 条评论