我想加载 MNIST 并计算一些随机图像的功率谱的振幅。我收到的与我预期的非常不同。如何计算功率谱的振幅然后将它们并排绘制(我不知道该怎么做——所以我只绘制光谱)
这是我的尝试:
import torch
import numpy as np
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
# Define the batch size
batch_size = 32
# Define the transform to normalize the images
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Load the dataset
trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True)
# The Fourier transform function
def fourier_transform(image):
image = image.numpy()[0] # Convert the tensor to a numpy array
f = np.fft.fft2(image) # Compute the 2D Fourier transform
fshift = np.fft.fftshift(f) # Shift the zero-frequency component to the center of the spectrum
magnitude_spectrum = np.log(np.abs(fshift)) # Compute the magnitude spectrum and take the logarithm for visualization
return magnitude_spectrum
X,y = next(iter(trainloader))
images, labels = next(iter(trainloader))
fig,ax = plt.subplots(3,6,figsize=(10,6))
for (i,ax) in enumerate(ax.flatten()):
# extract that image
magnitude_spectrum = fourier_transform(images[i])
# and its label
label = trainset.classes[y[i]]
# and show
ax.imshow(magnitude_spectrum)
ax.text(14,0,label,ha='center',fontweight='bold',color='k',backgroundcolor='y')
ax.axis('off')
plt.tight_layout()
plt.show()
你需要取傅里叶变换的绝对值并平方。在您的
fourier_transform
函数中,替换此行:
magnitude_spectrum = np.abs(fshift) ** 2
这条线:
magnitude_spectrum = np.abs(fshift) **