2012-09-17 142 views
0

我试图通过使用为FFTW C库提供Python绑定并且似乎是〜2的函数来提高计算搜索图像与模板图像之间的归一化互相关的函数的速度,为我的目的比scipy.fftpack快3倍。如何在scipy.fftpack中为二维数组填充零填充?

当我对我的模板进行FFT处理时,我需要将结果填充到与我的搜索图像相同的大小,以便我可以将它们进行卷积。使用scipy.fftpack.fftn我只会使用shape参数来填充/截断,但anfft.fftn更简约,并且不会执行任何零填充本身。

当我尝试自己做零填充时,我得到了与使用shape的结果截然不同的结果。这个例子只使用scipy.fftpack,但我有anfft同样的问题:

import numpy as np 
from scipy.fftpack import fftn 
from scipy.misc import lena 

img = lena() 
temp = img[240:281,240:281] 

def procrustes(a,target,padval=0): 

    # Forces an array to a target size by either padding it with a constant or 
    # truncating it 

    b = np.ones(target,a.dtype)*padval 
    aind = [slice(None,None)]*a.ndim 
    bind = [slice(None,None)]*a.ndim 
    for dd in xrange(a.ndim): 
     if a.shape[dd] > target[dd]: 
      diff = (a.shape[dd]-b.shape[dd])/2. 
      aind[dd] = slice(np.floor(diff),a.shape[dd]-np.ceil(diff)) 
     elif a.shape[dd] < target[dd]: 
      diff = (b.shape[dd]-a.shape[dd])/2. 
      bind[dd] = slice(np.floor(diff),b.shape[dd]-np.ceil(diff)) 
    b[bind] = a[aind] 
    return b 

# using scipy.fftpack.fftn's shape parameter 
F1 = fftn(temp,shape=img.shape) 

# doing my own zero-padding 
temp_padded = procrustes(temp,img.shape) 
F2 = fftn(temp_padded) 

# these results are quite different 
np.allclose(F1,F2) 

我怀疑我可能做一个很基本的错误,因为我不是太熟悉的离散傅里叶变换。

回答

1

只是做逆变换,你会看到SciPy的确实略有不同的填充(只有顶部和右侧边缘):

plt.imshow(ifftn(fftn(procrustes(temp,img.shape))).real) 

plt.imshow(ifftn(fftn(temp,shape=img.shape)).real) 
+0

是啊,preeeetty基本的错误在那里。谢谢你清理那个。 –