1

我正在尝试在 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]);
4

2 回答 2

2

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

于 2012-12-13T17:39:16.097 回答
1

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

于 2012-11-11T18:01:52.443 回答