首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用FFT加速2D卷积?

如何使用FFT加速2D卷积?
EN

Stack Overflow用户
提问于 2018-08-19 17:44:15
回答 1查看 94关注 0票数 2
代码语言:javascript
复制
# Zero-pad an image
def zero_pad(image, pad_height, pad_width):
    H, W = image.shape
    out = np.zeros((H+2*pad_height, W+2*pad_width))
    out[pad_height:H+pad_height,pad_width:W+pad_width] = image
    return out

# An step-by-step implementation of convolution filter
def conv(image, kernel):
    Hi, Wi = image.shape
    Hk, Wk = kernel.shape
    out = np.zeros((Hi, Wi))
    image_pad = zero_pad(image, (Hk-1)//2, (Wk-1)//2)
    for i in range(Hi):
        for j in range(Wi):
            out[i,j] = np.sum(kernel*image_pad[i:Hk+i,j:Wk+j])
    return out

# accelerate convolution using FFT
def conv_faster(image, kernel): 
    Hi, Wi = image.shape
    Hk, Wk = kernel.shape
    out = np.zeros((Hi, Wi))

    # expand image and kernel by zero-padding
    if( (Hi+Hk) % 2 == 0):
        x = (Hi+Hk)
    else:
        x = (Hi+Hk)-1
    if( (Wi+Wk) % 2 == 0):
        y = (Wi+Wk)
    else:
        y = (Wi+Wk)-1
    image_pad = np.zeros((x,y))
    kernel_pad = np.zeros((x,y))
    image_pad[0:Hi,0:Wi] = image
    kernel_pad[0:Hk,0:Wk] = kernel

    # make image and kernel at the center of frequency domain
    for p in range(Hi):
        for q in range(Wi):
            image_pad[p,q]*=(-1)**(p+q)
    for p in range(Hk):
        for q in range(Wk):
            kernel_pad[p,q]*=(-1)**(p+q)

    # do fft for image and kernel
    image_pad_fft = np.fft.fft2(image_pad)
    kernel_pad_fft = np.fft.fft2(kernel_pad) 


    # get the imaginary part of kernel's transformation
    kernel_pad_fft = 1j*np.imag(kernel_pad_fft)

    # multiply the two in frequency domain
    out_pad = np.fft.ifft2(image_pad_fft*kernel_pad_fft)

    # get he real part of result 
    out = np.real(out_pad[0:Hi,0:Wi])

    # Counteract the preceding centralization
    for p in range(Hi):
        for q in range(Wi):
            out[p,q]*=(-1)**(p+q)
    return out

它们的回报之间存在一些差异。我认为结果应该是一样的,我怎么改进它呢?想一想!内核为[1,0,-1,2,0,-2,1,0,-1]

我为这两个函数输入此图像

step-by-step函数可获得此结果

加速函数得到这样的结果

EN

回答 1

Stack Overflow用户

发布于 2018-08-19 18:13:34

对于卷积,必须翻转内核。您在conv()中所做的是一种关联。由于内核是对称的,除了减号外,当前结果中的result2 = -result1

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51916413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档