matlab编程实现 canny 算子进行边缘检测完整代码
时间: 2023-07-15 08:13:35 浏览: 86
matlab canny算子边缘检测函数代码.pdf
以下是 Matlab 实现的 Canny 边缘检测算法的完整代码:
```matlab
% 读取原始图像
img = imread('lena.jpg');
% 转为灰度图像
gray_img = rgb2gray(img);
% 高斯滤波
gaussian_filter = fspecial('gaussian', [5 5], 1.4);
img_smooth = conv2(double(gray_img), double(gaussian_filter), 'same');
% 计算梯度幅值和方向
Gx = [-1 0 1; -2 0 2; -1 0 1];
Gy = [-1 -2 -1; 0 0 0; 1 2 1];
img_dx = conv2(double(img_smooth), double(Gx), 'same');
img_dy = conv2(double(img_smooth), double(Gy), 'same');
grad_mag = sqrt(img_dx.^2 + img_dy.^2);
grad_ori = atan2(img_dy, img_dx) * 180 / pi;
% 非极大值抑制
grad_mag_nms = zeros(size(grad_mag));
for i = 2:size(grad_mag, 1)-1
for j = 2:size(grad_mag, 2)-1
if grad_ori(i,j) < 0
grad_ori(i,j) = grad_ori(i,j) + 180;
end
if grad_ori(i,j) < 22.5 || grad_ori(i,j) > 157.5
if grad_mag(i,j) >= grad_mag(i-1,j) && grad_mag(i,j) >= grad_mag(i+1,j)
grad_mag_nms(i,j) = grad_mag(i,j);
end
elseif grad_ori(i,j) >= 22.5 && grad_ori(i,j) < 67.5
if grad_mag(i,j) >= grad_mag(i-1,j-1) && grad_mag(i,j) >= grad_mag(i+1,j+1)
grad_mag_nms(i,j) = grad_mag(i,j);
end
elseif grad_ori(i,j) >= 67.5 && grad_ori(i,j) < 112.5
if grad_mag(i,j) >= grad_mag(i,j-1) && grad_mag(i,j) >= grad_mag(i,j+1)
grad_mag_nms(i,j) = grad_mag(i,j);
end
elseif grad_ori(i,j) >= 112.5 && grad_ori(i,j) < 157.5
if grad_mag(i,j) >= grad_mag(i-1,j+1) && grad_mag(i,j) >= grad_mag(i+1,j-1)
grad_mag_nms(i,j) = grad_mag(i,j);
end
end
end
end
% 双阈值检测
high_threshold = 0.15 * max(max(grad_mag_nms));
low_threshold = 0.05 * max(max(grad_mag_nms));
edge_map = zeros(size(grad_mag_nms));
edge_map(grad_mag_nms >= high_threshold) = 1;
edge_weak = grad_mag_nms >= low_threshold & grad_mag_nms < high_threshold;
[row, col] = find(edge_weak);
for i = 1:length(row)
if row(i) > 1 && row(i) < size(grad_mag,1) && col(i) > 1 && col(i) < size(grad_mag,2)
if any(edge_map(row(i)-1:row(i)+1, col(i)-1:col(i)+1))
edge_map(row(i), col(i)) = 1;
end
end
end
% 显示边缘图像
figure;
imshow(edge_map);
```
注:代码中的 `lena.jpg` 是一个测试图像,可以替换成其他图像。
阅读全文