2012-12-24 58 views
1

我的主要目標是證明卷積定理起作用(只是提醒一下:卷積定理意味着idft(dft(im) .* dft(mask)) = conv(im, mask))。我正在編程。驗證卷積定理

這裏是我的代碼:

function displayTransform(im) 
% This routine displays the Fourier spectrum of an image. 
% 
% Input:  im - a grayscale image (values in [0,255]) 
% 
% Method: Computes the Fourier transform of im and displays its spectrum, 
%     (if F(u,v) = a+ib, displays sqrt(a^2+b^2)). 
%     Uses display techniques for visualization: log, and stretch values to full range, 
%     cyclic shift DC to center (use fftshift). 
%     Use showImage to display and fft2 to apply transform. 

%displays the image in grayscale in the Frequency domain 
imfft = fft2(im); 
imagesc(log(abs(fftshift(imfft))+1)), colormap(gray); 

% building mask and padding it with Zeros in order to create same size mask 
b = 1/16*[1 1 1 1;1 1 1 1; 1 1 1 1; 1 1 1 1]; 
paddedB = padarray(b, [floor(size(im,1)/2)-2 floor(size(im,2)/2)-2]); 
paddedB = fft2(paddedB); 
C = imfft.*paddedB; 
resIFFT = ifft2(C); 

%reguler convolution 
resConv = conv2(im,b); 
showImage(resConv); 

end 

我想比較resIFFTresConv。我想我錯過了一些投射,因爲如果我使用投射來翻倍,我將矩陣中的數字靠得更近。 也許我在鑄造或填充的地方有一些錯誤?

+0

我在這裏沒有看到問題。我所看到的只是一個代碼轉儲和一條聲明,表明您「缺少某些東西」。嗯,是的,你可能是,我們也是 - 也就是你的問題的明確描述。 –

+0

@IlmariKaronen我試圖清除我的問題。請再次查看。 – Gilad

+1

@Androidy - 仍然不清楚。將你的'im'和'b'轉換成雙打。 – Shai

回答

7
  1. 爲了使用DFT計算線性卷積,你需要張貼墊用零兩個信號,否則結果將是circular convolution。您不必手動墊的信號,雖然,fft2能爲你做,如果你添加額外的參數,函數調用,就像這樣:

    fft2(X, M, N) 
    

    該墊(或截斷)信號X創建一個M在進行變換之前用逐個N信號。
    墊在每個維度爲等於兩個信號的長度之和的長度每一個信號,那就是:

    代替
    M = size(im, 1) + size(mask, 1); 
    N = size(im, 2) + size(mask, 2); 
    
  2. 只是爲了很好的做法,:

    b = 1/16 * [1 1 1 1; 1 1 1 1; 1 1 1 1; 1 1 1 1]; 
    

    可以寫:

    b = ones(4)/16; 
    

總之,這裏的固定鱈魚E(我已經生成一個隨機的形象只是爲了舉例起見):

im = fix(255 * rand(500));   % # Generate a random image 
mask = ones(4)/16;     % # Mask 

% # Circular convolution 
resConv = conv2(im, mask); 

% # Discrete Fourier transform 
M = size(im, 1) + size(mask, 1); 
N = size(im, 2) + size(mask, 2); 
resIFFT = ifft2(fft2(im, M, N) .* fft2(mask, M, N)); 
resIFFT = resIFFT(1:end-1, 1:end-1); % # Adjust dimensions 

% # Check the difference 
max(abs(resConv(:) - resIFFT(:))) 

你應該得到的結果應該是零:

ans = 

    8.5265e-014 

足夠接近。