Search code examples
matlabimage-processingfilteringlowpass-filter

Prewitt Filter implementation Matlab


I'm trying to implement the Prewitt Filter in Matlab. I know that Matlab has already this kind of filter but I need to code it myself. Below is my code, the only problem is that at the end of the filtering I get a bright image instead of seeing the edges. I'm implementing the filter using the separability property of the Prewitt Filter. Any ideas? I will appreciate very much your help.

%% 3x3 Prewitt Filter
close all
imageIn = imread('images/Bikesgray.jpg');

imageGx = zeros(size(imageIn));
imageGy = zeros(size(imageIn));
imageOut = zeros(size(imageIn));

ny = size(imageIn, 1);
nx = size(imageIn, 2);
average = 3;

imshow(imageIn);

u = [];
v = [];

tic
%Compute Gx
%For every row use the mask (-1 0 1)
for i = 1:ny
    u = imageIn(i,:);
    v = zeros(1, nx);
    for k = 2:nx-1
        v(k) = (uint32(-1*u(k-1))+uint32(0*u(k))+uint32(u(k+1)));
    end
    v(1) = (uint32(-1*u(2))+uint32(0*u(1))+uint32(u(2)));
    v(nx) = (uint32(-1*u(nx-1))+uint32(0*u(nx))+uint32(u(nx-1)));
    imageGx(i,:) = v;
end
%For every column use the mask (1 1 1)
for j = 1:nx
    u = imageGx(:,j);
    v = zeros(ny, 1);
    for k = 2:ny-1
        v(k) = (uint32(u(k-1))+uint32(u(k))+uint32(u(k+1)));
    end
    v(1) = (uint32(u(2))+uint32(u(1))+uint32(u(2)));
    v(ny) = (uint32(u(ny-1))+uint32(u(ny))+uint32(u(ny-1)));
    imageGx(:,j) = v;
end
%Compute Gy
%For every row use the mask (1 1 1)
for i = 1:ny
    u = imageIn(i,:);
    v = zeros(1, nx);
    for k = 2:nx-1
        v(k) = (uint32(u(k-1))+uint32(u(k))+uint32(u(k+1)));
    end
    v(1) = (uint32(u(2))+uint32(u(1))+uint32(u(2)));
    v(nx) = (uint32(u(nx-1))+uint32(u(nx))+uint32(u(nx-1)));
    imageGy(i,:) = v;
end
%For every column use  the mask (1 0 -1)
for j = 1:nx
    u = imageGy(:,j);
    v = zeros(ny, 1);
    for k = 2:ny-1
        v(k) = (uint32(u(k-1))+uint32(0*u(k))+uint32(-1*u(k+1)));
    end
    v(1) = (uint32(u(2))+uint32(0*u(1))+uint32(-1*u(2)));
    v(ny) = (uint32(u(ny-1))+uint32(0*u(ny))+uint32(-1*u(ny-1)));
    imageGy(:,j) = v;
end

toc

figure
imshow(imageGx, [0 255]);

figure
imshow(imageGy, [0 255]);

%Compute the magnitude G = sqrt(Gx^2 + Gy^2);
imageOut(:,:) = sqrt(imageGx(:,:).^2 + imageGy(:,:).^2);
figure
imshow(imageOut, [0 255]);

Solution

  • The solution was really obvious but took me some time to figure it out. All I did is change the uint32 to int32 and be sure to perform the operations (e.g. multiplying by -1) after changing the values from uint32 to int32.