资源简介
使用MATLAB实现的Canny边缘算子检测
代码片段和文件信息
%本程序用于实验canny滤波算法
%作者:大指挥官
%程序状态:完结,但是效果不如MATLAB自带的Canny滤波器效果好。
pic=imread(‘e:\test-pic\test3.jpg‘);
pic=rgb2gray(pic);
%pic=imresize(pic0.5);
pic_s=pic;
px=size(pic1);
py=size(pic2);
% figure(1);
% imshow(pic);
% title(‘原图‘);
%%%%%%%%%%%%%%%%%%
%构建高斯滤波算子
%%%%%%%%%%%%%%%%%%
sigma=1;
Gx=floor(3*sigma+0.5);
x=-1*Gx:1*Gx;
y=x;
[xy]=meshgrid(xy);
z=1/(2*pi*sigma^2)*exp(-1*(x.^2+y.^2)/(2*sigma.^2));
%高斯算子归一化
z_sum=sum(sum(z));
z=z/z_sum;
% figure(2);
% mesh(z);
pic=uint8(conv2(double(pic)z));
pic=pic(Gx+1:px+GxGx+1:py+Gx);
pic=uint8(pic);
figure(3);
imshow(pic);
title(strcat(‘sigma=‘num2str(sigma)));
%%%%%%%%%%%%%%%%%%%%%%%
%计算两个方向上的一阶差分
%%%%%%%%%%%%%%%%%%%%%%%
A=-1/2*[-1 1;-1 1];
B=-1/2*[1 1;-1 -1];
pic_x=conv2(double(pic)A);
pic_x=pic_x(2:px+12:py+1);
pic_y=conv2(double(pic)B);
pic_y=pic_y(2:px+12:py+1);
% figure(4);
% imshow(pic_x[]);
% title(‘x方向差分‘);
% figure(5);
% imshow(pic_y[]);
% title(‘y方向差分‘);
%%%%%%%%%%%%%%%%%%%%%%%
%计算梯度的幅值与方向
%%%%%%%%%%%%%%%%%%%%%%%
gradamp=sqrt(double(pic_x.^2)+double(pic_y.^2));
gradori=atan(double(pic_y)./double(pic_x));
figure(6);
imshow(gradamp[]);
title(‘梯度幅值‘);
%%%%%%%%%%%%%%%%%%%%%%%
%非极大值抑制
%%%%%%%%%%%%%%%%%%%%%%%
%此处是以梯度图为模板,比较梯度图在梯度方向上的局部最大值,从而细化边缘
picre=zeros(size(gradamp));
picre(1:)=0;
picre(px:)=0;
picre(:1)=0;
picre(:py)=0;
%g1=0;g2=0;g3=0;g4=0;%这四个变量用于插值计算
t1=0;t2=0; %这两个变量保存插好的值
h1=0;h2=0; %插值计算时的两个端点的权重
for i=2:px-1
for j=2:py-1
if gradamp(ij)~=0
theta=gradori(ij);
if theta<0
theta=theta+pi;
end
% g1 g2
% c
% g3 g4
if (theta>=pi/2)&&(theta h1=tan(theta-pi/2);
h2=1-h1;
t1=h1*gradamp(i-1j-1)+h2*gradamp(i-1j);
t2=h1*gradamp(i+1j+1)+h2*gradamp(i+1j);
end
% g1
% g2 c g3
% g4
if (theta>=pi*3/4)&&(theta<=pi)
h1=tan(pi-theta);
h2=1-h1;
t1=h1*g
评论
共有 条评论