📌  相关文章
📜  MATLAB –使用Scratch中的Prewitt运算符进行图像边缘检测

📅  最后修改于: 2021-04-16 06:15:54             🧑  作者: Mango

Prewitt运算符:这是一个基于梯度的运算符。这是检测图像方向和大小的最佳方法之一。它计算图像强度函数的梯度近似值以进行图像边缘检测。在图像的像素处,Prewitt运算符生成矢量的法线或相应的梯度矢量。它使用两个与输入图像卷积的3 x 3内核或遮罩来计算导数的近似值-一个用于水平变化,一个用于垂直变化-

    \[M_{x}=\left[\begin{array}{ccc}-1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1\end{array}\right] \quad M_{y}=\left[\begin{array}{ccc}-1 & -1 & -1 \\ 0 & 0 & 0 \\ 1 & 1 & 1\end{array}\right]\]

在MATLAB中的实现:

% MATLAB Code | Prewitt Operator from Scratch
  
% Read Input Image
input_image = imread('[name of input image file].[file format]');
  
% Displaying Input Image
input_image = uint8(input_image);
figure, imshow(input_image); title('Input Image');
  
% Convert the truecolor RGB image to the grayscale image
input_image = rgb2gray(input_image);
  
% Convert the image to double
input_image = double(input_image);
  
% Pre-allocate the filtered_image matrix with zeros
filtered_image = zeros(size(input_image));
  
% Prewitt Operator Mask
Mx = [-1 0 1; -1 0 1; -1 0 1];
My = [-1 -1 -1; 0 0 0; 1 1 1];
  
% Edge Detection Process
% When i = 1 and j = 1, then filtered_image pixel  
% position will be filtered_image(2, 2)
% The mask is of 3x3, so we need to traverse 
% to filtered_image(size(input_image, 1) - 2
%, size(input_image, 2) - 2)
% Thus we are not considering the borders.
for i = 1:size(input_image, 1) - 2
    for j = 1:size(input_image, 2) - 2
  
        % Gradient approximations
        Gx = sum(sum(Mx.*input_image(i:i+2, j:j+2)));
        Gy = sum(sum(My.*input_image(i:i+2, j:j+2)));
                 
        % Calculate magnitude of vector
        filtered_image(i+1, j+1) = sqrt(Gx.^2 + Gy.^2);
         
    end
end
  
% Displaying Filtered Image
filtered_image = uint8(filtered_image);
figure, imshow(filtered_image); title('Filtered Image');
  
% Define a threshold value
thresholdValue = 100; % varies between [0 255]
output_image = max(filtered_image, thresholdValue);
output_image(output_image == round(thresholdValue)) = 0;
  
% Displaying Output Image
output_image = im2bw(output_image);
figure, imshow(output_image); title('Edge Detected Image');

输入图像–

过滤图像:

边缘检测图像:

好处:

  1. 在检测垂直和水平边缘方面表现出色
  2. 检测图像方向的最佳运算符

局限性:

  1. 系数的大小是固定的,无法更改
  2. 对角方向点不会始终保留