prewitt边缘检测matlab代码
时间: 2024-06-09 12:06:40 浏览: 27
以下是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];
% 对图像进行卷积操作
Gx = conv2(double(I), Px, 'same');
Gy = conv2(double(I), Py, 'same');
% 计算梯度幅值和方向
G = sqrt(Gx.^2 + Gy.^2);
theta = atan2(Gy, Gx);
% 将方向转换为角度
theta = theta * 180 / pi;
% 对梯度方向进行量化
theta(theta < -22.5) = 180 + theta(theta < -22.5);
theta(theta > 157.5) = theta(theta > 157.5) - 180;
% 非极大值抑制
[row, col] = size(I);
NMS = zeros(row, col);
for i = 2:row-1
for j = 2:col-1
% 梯度方向为0度的情况
if (theta(i,j) >= -22.5 && theta(i,j) <= 22.5) || (theta(i,j) < -157.5 && theta(i,j) >= -180) || (theta(i,j) > 157.5 && 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
% 梯度方向为45度的情况
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
% 梯度方向为90度的情况
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
% 梯度方向为135度的情况
elseif (theta(i,j) > 112.5 && theta(i,j) <= 157.5) || (theta(i,j) < -22.5 && 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
end
end
% 双阈值检测
highThresholdRatio = 0.2;
lowThresholdRatio = 0.1;
highThreshold = max(max(NMS)) * highThresholdRatio;
lowThreshold = highThreshold * lowThresholdRatio;
[row, col] = size(NMS);
res = zeros(row, col);
for i = 2:row-1
for j = 2:col-1
if (NMS(i,j) > highThreshold)
res(i,j) = 1;
elseif (NMS(i,j) < lowThreshold)
res(i,j) = 0;
% 连通性检测
elseif (NMS(i+1,j)>highThreshold) || (NMS(i-1,j)>highThreshold) || (NMS(i,j+1)>highThreshold) || (NMS(i,j-1)>highThreshold) || (NMS(i-1,j-1)>highThreshold) || (NMS(i-1,j+1)>highThreshold) || (NMS(i+1,j+1)>highThreshold) || (NMS(i+1,j-1)>highThreshold)
res(i,j) = 1;
end
end
end
% 显示结果
figure;
subplot(1,2,1);imshow(I);title('原图');
subplot(1,2,2);imshow(res);title('Prewitt边缘检测结果');
```
阅读全文