canny边缘检测算法 matlab代码
时间: 2023-11-10 22:58:07 浏览: 49
以下是canny边缘检测算法的matlab代码:
```matlab
function edgeImg = cannyEdgeDetection(grayImg, sigma, thresholdLow, thresholdHigh)
% 高斯滤波
G = fspecial('gaussian', [5 5], sigma);
grayImg = imfilter(grayImg, G, 'same');
% 计算梯度幅值和方向
Sx = [-1 0 1; -2 0 2; -1 0 1];
Sy = [-1 -2 -1; 0 0 0; 1 2 1];
Gx = imfilter(double(grayImg), Sx);
Gy = imfilter(double(grayImg), Sy);
Gmag = sqrt(Gx.^2 + Gy.^2);
Gdir = atan2(Gy, Gx) * 180 / pi;
% 非极大值抑制
[nRows, nCols] = size(grayImg);
edgeImg = zeros(nRows, nCols);
for i = 2:nRows-1
for j = 2:nCols-1
if (Gdir(i,j) < 0)
Gdir(i,j) = Gdir(i,j) + 180;
end
if ((Gdir(i,j) >= 0) && (Gdir(i,j) < 22.5) || (Gdir(i,j) >= 157.5) && (Gdir(i,j) < 202.5) || (Gdir(i,j) >= 337.5) && (Gdir(i,j) <= 360))
if ((Gmag(i,j) > Gmag(i,j+1)) && (Gmag(i,j) > Gmag(i,j-1)))
edgeImg(i,j) = Gmag(i,j);
end
end
if ((Gdir(i,j) >= 22.5) && (Gdir(i,j) < 67.5) || (Gdir(i,j) >= 202.5) && (Gdir(i,j) < 247.5))
if ((Gmag(i,j) > Gmag(i+1,j+1)) && (Gmag(i,j) > Gmag(i-1,j-1)))
edgeImg(i,j) = Gmag(i,j);
end
end
if ((Gdir(i,j) >= 67.5) && (Gdir(i,j) < 112.5) || (Gdir(i,j) >= 247.5) && (Gdir(i,j) < 292.5))
if ((Gmag(i,j) > Gmag(i+1,j)) && (Gmag(i,j) > Gmag(i-1,j)))
edgeImg(i,j) = Gmag(i,j);
end
end
if ((Gdir(i,j) >= 112.5) && (Gdir(i,j) < 157.5) || (Gdir(i,j) >= 292.5) && (Gdir(i,j) < 337.5))
if ((Gmag(i,j) > Gmag(i-1,j+1)) && (Gmag(i,j) > Gmag(i+1,j-1)))
edgeImg(i,j) = Gmag(i,j);
end
end
end
end
% 双阈值处理
edgeImg(edgeImg < thresholdLow) = 0;
edgeImg(edgeImg >= thresholdHigh) = 1;
edgeImg((edgeImg < thresholdHigh) & (edgeImg > thresholdLow)) = 0.5;
% 滞后阈值处理
for i = 2:nRows-1
for j = 2:nCols-1
if (edgeImg(i,j) == 0.5)
if ((edgeImg(i-1,j-1) == 1) || (edgeImg(i-1,j) == 1) || (edgeImg(i-1,j+1) == 1) || (edgeImg(i,j-1) == 1) || (edgeImg(i,j+1) == 1) || (edgeImg(i+1,j-1) == 1) || (edgeImg(i+1,j) == 1) || (edgeImg(i+1,j+1) == 1))
edgeImg(i,j) = 1;
end
end
end
end
edgeImg(edgeImg == 0.5) = 0;
end
```
函数接受四个参数:灰度图像、高斯核尺寸、低阈值和高阈值。返回二值化的边缘图像。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)