Canny边缘检测matlab代码
时间: 2023-11-20 09:43:46 浏览: 34
以下是使用MATLAB实现Canny边缘检测的代码:
```matlab
% 读取图像
img = imread('lena.jpg');
% 转换为灰度图像
gray_img = rgb2gray(img);
% 高斯滤波
gaussian_img = imgaussfilt(gray_img, 1);
% 计算梯度
[Gx, Gy] = imgradientxy(gaussian_img);
% 计算梯度幅值和方向
[Gmag, Gdir] = imgradient(Gx, Gy);
% 非极大值抑制
nms_img = imgradient_nms(Gmag, Gdir);
% 双阈值处理
low_threshold = 0.1 * max(max(nms_img));
high_threshold = 0.3 * max(max(nms_img));
edge_img = double(nms_img > high_threshold) .* nms_img;
[r, c] = find(edge_img > low_threshold & edge_img <= high_threshold);
for i = 1:length(r)
if (edge_img(r(i)-1:r(i)+1, c(i)-1:c(i)+1) > high_threshold)
edge_img(r(i), c(i)) = edge_img(r(i)-1:r(i)+1, c(i)-1:c(i)+1);
end
end
edge_img = uint8(edge_img > low_threshold);
% 显示结果
imshow(edge_img);
```
其中,`imgradient_nms`是自定义的非极大值抑制函数,代码如下:
```matlab
function nms_img = imgradient_nms(Gmag, Gdir)
% 非极大值抑制
[r, c] = size(Gmag);
nms_img = zeros(r, c);
for i = 2:r-1
for j = 2:c-1
if (Gdir(i,j) >= -22.5 && Gdir(i,j) <= 22.5) || (Gdir(i,j) >= 157.5 && Gdir(i,j) <= -157.5)
if (Gmag(i,j) > Gmag(i,j+1) && Gmag(i,j) > Gmag(i,j-1))
nms_img(i,j) = Gmag(i,j);
end
elseif (Gdir(i,j) >= 22.5 && Gdir(i,j) <= 67.5) || (Gdir(i,j) >= -157.5 && Gdir(i,j) <= -112.5)
if (Gmag(i,j) > Gmag(i+1,j+1) && Gmag(i,j) > Gmag(i-1,j-1))
nms_img(i,j) = Gmag(i,j);
end
elseif (Gdir(i,j) >= 67.5 && Gdir(i,j) <= 112.5) || (Gdir(i,j) >= -112.5 && Gdir(i,j) <= -67.5)
if (Gmag(i,j) > Gmag(i+1,j) && Gmag(i,j) > Gmag(i-1,j))
nms_img(i,j) = Gmag(i,j);
end
elseif (Gdir(i,j) >= 112.5 && Gdir(i,j) <= 157.5) || (Gdir(i,j) >= -67.5 && Gdir(i,j) <= -22.5)
if (Gmag(i,j) > Gmag(i+1,j-1) && Gmag(i,j) > Gmag(i-1,j+1))
nms_img(i,j) = Gmag(i,j);
end
end
end
end
end
```