Prewitt边缘检测matlab代码
时间: 2024-06-09 22:09:38 浏览: 5
以下是Prewitt边缘检测的MATLAB代码:
```matlab
% 读入图像
I = imread('image.jpg');
% 转换为灰度图像
I = rgb2gray(I);
% 定义Prewitt算子
Px = [-1,0,1;-1,0,1;-1,0,1];
Py = [1,1,1;0,0,0;-1,-1,-1];
% 计算x方向和y方向梯度
Gx = conv2(double(I),Px,'same');
Gy = conv2(double(I),Py,'same');
% 计算梯度幅值和方向
G = sqrt(Gx.^2+Gy.^2);
theta = atan2(Gy,Gx);
% 将方向转换为0-180度的角度
theta = theta*180/pi;
theta(theta<0) = theta(theta<0)+180;
% 非极大值抑制
[n,m] = size(I);
NMS = zeros(n,m);
for i = 2:n-1
for j = 2:m-1
if ( (0 <= theta(i,j) && theta(i,j) < 22.5) || (157.5 <= theta(i,j) && theta(i,j) <= 180) )
if (G(i,j) > G(i,j-1) && G(i,j) > G(i,j+1))
NMS(i,j) = G(i,j);
end
end
if ( (22.5 <= theta(i,j) && theta(i,j) < 67.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
end
if ( (67.5 <= theta(i,j) && 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
end
if ( (112.5 <= theta(i,j) && 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
end
end
end
% 双阈值处理
TL = 0.1*max(max(NMS));
TH = 0.3*max(max(NMS));
T = zeros(n,m);
T(NMS >= TH) = 1;
T(NMS <= TL) = 0;
for i = 2:n-1
for j = 2:m-1
if (NMS(i,j) >= TL && NMS(i,j) < TH)
if ( any(any(T(i-1:i+1,j-1:j+1)==1)) )
T(i,j) = 1;
end
end
end
end
% 显示结果
figure(1);
subplot(2,2,1);imshow(I);title('原图像');
subplot(2,2,2);imshow(NMS);title('非极大值抑制');
subplot(2,2,3);imshow(T);title('双阈值处理');
subplot(2,2,4);imshow(uint8(T.*I));title('边缘检测结果');
```
注意,该代码中的图像文件名为“image.jpg”,需要根据实际情况进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)