Prewitt Filter实现Matlab

时间:2012-11-11 11:47:16

标签: matlab image-processing filtering lowpass-filter

我正在尝试在Matlab中实现Prewitt过滤器。我知道Matlab已经有了这种过滤器,但我需要自己编写代码。下面是我的代码,唯一的问题是在滤镜结束时我得到一个明亮的图像而不是看到边缘。 我正在使用Prewitt过滤器的可分离性来实现过滤器。有任何想法吗?我非常感谢你的帮助。

%% 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]);

2 个答案:

答案 0 :(得分:2)

你没有使用convn(卷积)太糟糕了,因为加权和只是尖叫它。 简而言之,您可以使用适当的内核在图像矩阵上使用convn来生成Gx,Gy,如wikipedia

中所述

答案 1 :(得分:1)

解决方案非常明显,但花了我一些时间才弄明白。 我所做的只是将uint32更改为int32,并确保在将值从uint32更改为int32后执行操作(例如乘以-1)。