?
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),逆过程变换结果会出现正弦分量。