What's the problem in implementing this MATLAB Prewitt operator?

I am trying to code an implementation of the Prewitt operator for edge detection. So far I have tried:

openImage = im2double(rgb2gray(imread(imageSource)));
[rows,cols] =  size(openImage);

N(1:rows,1:cols)=0;
for i=1:rows-2;
    for j=1:rows-2;
        N(i,j)=-1*openImage(i,j)-1*openImage(i,j+1)-1*openImage(i,j+2)+0+0+0+1*openImage(i+2,j)+1*openImage(i+2,j+1)+1*openImage(i+2,j+2);
    end;
end;
O(1:rows,1:cols)=0;
for i=1:rows-2;
    for j=1:rows-2;
        O(i,j)=-1*openImage(i,j)+0+1*openImage(i,j+2)-1*openImage(i+2,j)+0+1*openImage(i+1,j+2)-1*openImage(i+2,j)+0+1*openImage(i+2,j+2);
    end
end
Z = N + O;

      

For which I can get:

enter image description here

As you can see, this image received half the processed image and half the space. What am I doing wrong?

This is the original image:

enter image description here

+3


source to share


2 answers


Consider the following code:

I = im2double(rgb2gray(..));
[rows,cols] =  size(I);

N = zeros(size(I));
for i=2:rows-1;
    for j=2:cols-1;
        N(i,j) = 1*I(i-1,j-1) +  1*I(i-1,j) +  1*I(i-1,j+1) + ...
                 0            +  0          +  0            + ...
                -1*I(i+1,j-1) + -1*I(i+1,j) + -1*I(i+1,j+1);
    end
end

O = zeros(size(I));
for i=2:rows-1;
    for j=2:cols-1;
        O(i,j) = 1*I(i-1,j-1) + 0 + -1*I(i-1,j+1) + ...
                 1*I(i,j-1)   + 0 + -1*I(i,j+1)   + ...
                 1*I(i+1,j-1) + 0 + -1*I(i+1,j+1);
    end
end

Z = sqrt(N.^2 + O.^2);
imshow(Z)

      

Then compare it to:



Gx = conv2(I, [-1 0 1; -1 0 1; -1 0 1]);
Gy = conv2(I, [-1 -1 -1; 0 0 0; 1 1 1]);

G = sqrt(Gx.^2 + Gy.^2);
T = atan2(Gy, Gx);

imshow(G)

      

Note. You may need to use imshow(result,[])

outside the range of [0,1] to display results correctly.

+3


source


for j=1:rows-2;

      

it should be



for j=1:cols-2;

      

+3


source







All Articles