2012-11-11 180 views
1

我正試圖在Matlab中實現Prewitt濾波器。我知道Matlab已經有這種過濾器,但我需要自己編寫代碼。下面是我的代碼,唯一的問題是,在過濾結束時,我得到一個明亮的圖像,而不是看到邊緣。 我使用Prewitt過濾器的可分性屬性來實現過濾器。有任何想法嗎?我非常感謝你的幫助。Prewitt濾波器實現Matlab

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

回答

1

解決方案非常明顯,但花了我一些時間弄清楚。 我所做的只是將uint32更改爲int32,並確保在將值從uint32更改爲int32後執行操作(例如,乘以-1)。

2

這太糟糕了,你沒有使用convn(卷積),因爲加權和只是尖叫它。 簡而言之,你通過在圖像矩陣上使用convn來生成Gx,Gy,使用合適的內核,如wikipedia

+0

的描述那麼有時候我需要通過編程這種東西來學習基本知識。我知道Matlab有一個很好的卷積實現。 – BRabbit27