改进canny算法matlab代码效果图
时间: 2023-09-17 21:12:18 浏览: 90
很抱歉,作为AI语言模型,我无法提供图片。但是,我可以为您提供改进Canny算法的Matlab代码。
改进Canny算法的Matlab代码:
```matlab
function edgeImg = myCanny(im, sigma, thLow, thHigh)
%MYCANNY Implementation of Canny edge detection algorithm
% edgeImg = MYCANNY(im, sigma, thLow, thHigh) returns binary edge map
% of input image 'im' using Canny edge detection algorithm. 'sigma' is
% the standard deviation of Gaussian filter used for smoothing. 'thLow'
% and 'thHigh' are thresholds for hysteresis thresholding.
% Convert image to double
im = im2double(im);
% Smoothing using Gaussian filter
G = fspecial('gaussian', [5 5], sigma);
imFilt = imfilter(im, G, 'same');
% Computing gradients using Sobel filter
Sx = [-1 0 1; -2 0 2; -1 0 1];
Sy = [-1 -2 -1; 0 0 0; 1 2 1];
Gx = imfilter(imFilt, Sx, 'same');
Gy = imfilter(imFilt, Sy, 'same');
Gmag = sqrt(Gx.^2 + Gy.^2);
Gtheta = atan2(Gy, Gx) * 180/pi;
% Non-maximum suppression
[n, m] = size(im);
edgeImg = zeros(n, m);
for i = 2:n-1
for j = 2:m-1
if (Gtheta(i,j) < 0)
Gtheta(i,j) = Gtheta(i,j) + 180;
end
if ((Gtheta(i,j) >= 0) && (Gtheta(i,j) < 22.5) || ...
(Gtheta(i,j) >= 157.5) && (Gtheta(i,j) < 180))
q = Gmag(i, j+1);
r = Gmag(i, j-1);
elseif ((Gtheta(i,j) >= 22.5) && (Gtheta(i,j) < 67.5))
q = Gmag(i+1, j-1);
r = Gmag(i-1, j+1);
elseif ((Gtheta(i,j) >= 67.5) && (Gtheta(i,j) < 112.5))
q = Gmag(i+1, j);
r = Gmag(i-1, j);
elseif ((Gtheta(i,j) >= 112.5) && (Gtheta(i,j) < 157.5))
q = Gmag(i-1, j-1);
r = Gmag(i+1, j+1);
end
if (Gmag(i,j) >= q) && (Gmag(i,j) >= r)
edgeImg(i,j) = Gmag(i,j);
end
end
end
% Hysteresis thresholding
thLow = thLow * max(max(edgeImg));
thHigh = thHigh * max(max(edgeImg));
for i = 1:n
for j = 1:m
if (edgeImg(i,j) < thLow)
edgeImg(i,j) = 0;
elseif (edgeImg(i,j) > thHigh)
edgeImg(i,j) = 1;
else
if ((edgeImg(i-1,j-1) > thHigh) || (edgeImg(i-1,j) > thHigh) || ...
(edgeImg(i-1,j+1) > thHigh) || (edgeImg(i,j-1) > thHigh) || ...
(edgeImg(i,j+1) > thHigh) || (edgeImg(i+1,j-1) > thHigh) || ...
(edgeImg(i+1,j) > thHigh) || (edgeImg(i+1,j+1) > thHigh))
edgeImg(i,j) = 1;
end
end
end
end
% Convert edge map to binary image
edgeImg = im2bw(edgeImg);
end
```
使用方法:
```matlab
im = imread('lena.jpg');
sigma = 1.5;
thLow = 0.05;
thHigh = 0.15;
edgeImg = myCanny(im, sigma, thLow, thHigh);
imshow(edgeImg);
```
其中,'lena.jpg'是您需要读取的图像文件名,sigma是高斯滤波器的标准差,thLow和thHigh是用于滞后阈值的阈值。您可以根据需要调整这些参数以获得最佳结果。
阅读全文
相关推荐















