canny算子实现——matlab

灰度化

// 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算子比较');

这效果咋这么垃圾呢??????黑人问号??

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值