用matlab写一段canny算子的边缘检测代码
时间: 2023-11-21 07:06:51 浏览: 38
以下是用MATLAB实现Canny算子的边缘检测代码:
% 读取图像
I = imread('test.jpg');
% 转换为灰度图像
Igray = rgb2gray(I);
% 高斯平滑
Iblur = imgaussfilt(Igray, 1);
% 计算梯度
Ix = imfilter(double(Iblur), [-1 0 1; -2 0 2; -1 0 1]);
Iy = imfilter(double(Iblur), [-1 -2 -1; 0 0 0; 1 2 1]);
G = sqrt(Ix.^2 + Iy.^2);
theta = atan2(Iy, Ix) * 180 / pi;
% 非极大值抑制
[nrows, ncols] = size(G);
nms = zeros(nrows, ncols);
for i = 2:nrows-1
for j = 2:ncols-1
if (theta(i, j) >= -22.5 && theta(i, j) < 22.5) || (theta(i, j) < -157.5 || theta(i, j) >= 157.5)
if (G(i, j) >= G(i, j+1)) && (G(i, j) >= G(i, j-1))
nms(i, j) = G(i, j);
end
elseif (theta(i, j) >= 22.5 && theta(i, j) < 67.5) || (theta(i, j) < -112.5 && theta(i, j) >= -157.5)
if (G(i, j) >= G(i-1, j+1)) && (G(i, j) >= G(i+1, j-1))
nms(i, j) = G(i, j);
end
elseif (theta(i, j) >= 67.5 && theta(i, j) < 112.5) || (theta(i, j) < -67.5 && theta(i, j) >= -112.5)
if (G(i, j) >= G(i-1, j)) && (G(i, j) >= G(i+1, j))
nms(i, j) = G(i, j);
end
else
if (G(i, j) >= G(i-1, j-1)) && (G(i, j) >= G(i+1, j+1))
nms(i, j) = G(i, j);
end
end
end
end
% 双阈值处理
lowthresh = 0.2;
highthresh = 0.4;
edge = zeros(nrows, ncols);
for i = 2:nrows-1
for j = 2:ncols-1
if nms(i, j) < lowthresh
edge(i, j) = 0;
elseif nms(i, j) >= highthresh
edge(i, j) = 1;
elseif nms(i, j) >= lowthresh && nms(i, j) < highthresh
if nms(i-1, j-1) >= highthresh || nms(i-1, j) >= highthresh || nms(i-1, j+1) >= highthresh || nms(i, j-1) >= highthresh || nms(i, j+1) >= highthresh || nms(i+1, j-1) >= highthresh || nms(i+1, j) >= highthresh || nms(i+1, j+1) >= highthresh
edge(i, j) = 1;
end
end
end
end
% 显示结果
imshow(edge);