灰度化
// An highlighted block
img=imread('');%读取图像
img=rgb2gray(img);%灰度化
figure(1);imshow(img);title('灰度化原图');
求梯度以及方向
// An highlighted block
%2.计算图像梯度
[gx gy] = imgradientxy(img, 'sobel');%利用sobel滤波器获得x和y方向梯度
[img_grad_mag, img_grad_or] = imgradient(gx, gy);%获得梯度的幅值和方向
img_grad_or=img_grad_or/180*pi;
img_grad_or=round(img_grad_or./(pi/4)).*(pi/4);
%显示,并且关闭坐标显示
figure(2);imagesc(img_grad_mag);title('梯度幅度');axis off;
figure(3);imagesc(img_grad_or);title('梯度方向');axis off;
NMS
// An highlighted block
%3.NMS非极大值抑制,比较像素
Nms = zeros(rows,cols);%定义一个非极大值抑制图像
for i = 2:rows-1
for j= 2:cols-1
if (img_grad_or(i,j) == pi/2 && img_grad_mag(i,j) == max([img_grad_mag(i,j), img_grad_mag(i,j+1), img_grad_mag(i,j-1)]))
Nms(i,j) = img_grad_mag(i,j);%比较纵向
elseif (img_grad_or(i,j) == -pi/4 && img_grad_mag(i,j) == max([img_grad_mag(i,j), img_grad_mag(i+1,j-1), img_grad_mag(i-1,j+1)]))
Nms(i,j) = img_grad_mag(i,j);%比较-45度方向
elseif (img_grad_or(i,j) == 0 && img_grad_mag(i,j) == max([img_grad_mag(i,j), img_grad_mag(i+1,j), img_grad_mag(i-1,j)]))
Nms(i,j) = img_grad_mag(i,j);%比较横向
elseif (img_grad_or(i,j) == pi/4 && img_grad_mag(i,j) == max([img_grad_mag(i,j), img_grad_mag(i+1,j+1), img_grad_mag(i-1,j-1)]))
Nms(i,j) = img_grad_mag(i,j);%比较45度方向
end;
end;
end;
figure(4);imagesc(Nms);title('非极大值抑制图');axis off;
阈值拼接
// An highlighted block
%4.阈值化并链接
thresh_low=自己设置;thresh_high=自己设置;
%二值化,True变为数
img_thresh_low=[Nms>thresh_low+0];
img_thresh_high=[Nms>thresh_high+0];
for i = 2:rows-1
for j= 2:cols-1
if (img_thresh_high(i,j)==1)
if(img_grad_or(x,y) == 0)
img_thresh_high(i+1,j) = img_thresh_low(i+1,j);
elseif(img_grad_or(x,y) == pi)
img_thresh_high(i-1,j) = img_thresh_low(i-1,j);
elseif(img_grad_or(x,y) == pi/4)
img_thresh_high(i+1,j+1) = img_thresh_low(i+1,j+1);
elseif(img_grad_or(x,y) == pi/2)
img_thresh_high(i,j+1) = img_thresh_low(i,j+1);
elseif(img_grad_or(x,y) == 3*pi/4)
img_thresh_high(i-1,j+1) = img_thresh_low(i-1,j+1);
elseif(img_grad_or(x,y) == -3*pi/4)
img_thresh_high(i-1,j-1) = img_thresh_low(i-1,j-1);
elseif(img_grad_or(x,y) == -pi/2)
img_thresh_high(i,j-1) = img_thresh_low(i,j-1);
end;
end;
end;
end;
对比
// An highlighted block
BW1 = img_thresh_high;
BW2=edge(img,'canny');
figure(5);imshowpair(BW1, BW2, 'montage');title('canny算子比较');
这效果咋这么垃圾呢??????黑人问号??