用PyTorch证明卷积定理

 

import numpy as np
import matplotlib.pyplot as plt
import torch 


weight = np.array([-1,-2,-1,-1,9,-1,-1,-2,-1]).reshape(1,1,3,3)
conv1 = torch.nn.Conv2d(1,1,3,1,1)
weight_conv = torch.Tensor(weight)
conv1.weight = torch.nn.Parameter(weight_conv)

# weight = weight[0]
img = plt.imread("img1.png")[:,:,0]
img = torch.Tensor(img).unsqueeze(dim=0).unsqueeze(dim=0)

weight_fre = torch.zeros((img.shape[2:4]))
weight = torch.Tensor(weight)[0,0]
for i in range((len(weight))):
    for j in range((len(weight))):
        weight_fre[i][j]=weight[i][j]

#spacial conv
space_img = conv1(img)

#frequency conv
fre_img  = torch.fft.ifft2(torch.fft.fft2(img.squeeze()) * torch.fft.fft2(weight_fre.squeeze()))

plt.subplot(231)
plt.title("original img")
plt.imshow(np.array(img.cpu().detach())[0,0])


plt.subplot(232)
plt.title("space filt img")
plt.imshow(np.array(space_img.cpu().detach())[0,0])

plt.subplot(233)
plt.title("fre filt img")
plt.imshow(np.array(abs(fre_img.cpu().detach())))

plt.subplot(234)
plt.title("fre of img")
plt.imshow(np.array(torch.log(1+abs(torch.fft.fftshift(torch.fft.fft2(img[0,0]).cpu().detach())))))


plt.subplot(235)
plt.title("fre of filt kernel")
plt.imshow(np.array(abs(torch.fft.fftshift(torch.fft.fft2(weight_fre).cpu().detach()))))

plt.subplot(236)
plt.title("space of filt kernel")
plt.imshow(np.array(abs((weight).cpu().detach())))


plt.show()

效果相近,但是torch.fft的计算值不同,整体过滤效果相近。

尝试多种滤波器

发现现象

torch.fft 当矩阵长度大于一定限量时(>8~16),逆过程变换结果会出现正弦分量。

  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值