我有一个Python代码,用于生成五个不同函数的图像及其频谱,但是存在一个问题,即从第二个函数开始到第五个函数,在计算频谱时都输出的是全黑图像,而非期望的结果。
问题在于:
RuntimeWarning: divide by zero encountered in log10
magnitude_spectrum_2 = 20 * np.log10(np.abs(dft_signal_2))
对于信号3-5也有同样的警告。
import numpy as np
import matplotlib.pyplot as plt
# Dimensiunile imaginii
M, N = 256, 256
# Generare coordonate n1, n2
n1 = np.arange(0, M)
n2 = np.arange(0, N)
n1, n2 = np.meshgrid(n1, n2)
# Definirea celor cinci funcții date
def signal_function_1(n1, n2):
return np.sin(2 * np.pi * n1 + 3 * np.pi * n2)
def signal_function_2(n1, n2):
return np.sin(4 * np.pi * n1) + np.cos(6 * np.pi * n2)
def signal_function_3(n1, n2):
Y = np.zeros_like(n1, dtype=complex)
Y[0, 5] = Y[0, N-5] = 1
return np.real(np.fft.ifft2(Y))
def signal_function_4(n1, n2):
Y = np.zeros_like(n1, dtype=complex)
Y[5, 0] = Y[N-5, 0] = 1
return np.real(np.fft.ifft2(Y))
def signal_function_5(n1, n2):
Y = np.zeros_like(n1, dtype=complex)
Y[5, 5] = Y[N-5, N-5] = 1
return np.real(np.fft.ifft2(Y))
# Calculul semnalelor
signal_1 = signal_function_1(n1, n2)
signal_2 = signal_function_2(n1, n2)
signal_3 = signal_function_3(n1, n2)
signal_4 = signal_function_4(n1, n2)
signal_5 = signal_function_5(n1, n2)
# Calculul DFT bidimensional
dft_signal_1 = np.fft.fft2(signal_1)
dft_signal_2 = np.fft.fft2(signal_2)
dft_signal_3 = np.fft.fft2(signal_3)
dft_signal_4 = np.fft.fft2(signal_4)
dft_signal_5 = np.fft.fft2(signal_5)
magnitude_spectrum_1 = 20 * np.log10(np.abs(dft_signal_1))
magnitude_spectrum_2 = 20 * np.log10(np.abs(dft_signal_2))
magnitude_spectrum_3 = 20 * np.log10(np.abs(dft_signal_3))
magnitude_spectrum_4 = 20 * np.log10(np.abs(dft_signal_4))
magnitude_spectrum_5 = 20 * np.log10(np.abs(dft_signal_5))
# Vizualizare pentru prima funcție
plt.figure(figsize=(12, 8))
plt.subplot(221), plt.imshow(signal_1, cmap='gray'), plt.title('Imagine 1')
plt.subplot(222), plt.imshow(magnitude_spectrum_1), plt.title('Spectru 1')
# Vizualizare pentru a doua funcție
plt.subplot(223), plt.imshow(signal_2, cmap='gray'), plt.title('Imagine 2')
plt.subplot(224), plt.imshow(magnitude_spectrum_2), plt.title('Spectru 2')
plt.show()
plt.figure(figsize=(12, 8))
# Vizualizare pentru a treia funcție
plt.subplot(221), plt.imshow(signal_3, cmap='gray'), plt.title('Imagine 3')
plt.subplot(222), plt.imshow(magnitude_spectrum_3), plt.title('Spectru 3')
plt.show()
# Vizualizare pentru a patra funcție
plt.figure(figsize=(12, 8))
plt.subplot(221), plt.imshow(signal_4, cmap='gray'), plt.title('Imagine 4')
plt.subplot(222), plt.imshow(magnitude_spectrum_4), plt.title('Spectru 4')
# Vizualizare pentru a cincea funcție
plt.subplot(223), plt.imshow(signal_5, cmap='gray'), plt.title('Imagine 5')
plt.subplot(224), plt.imshow(magnitude_spectrum_5), plt.title('Spectru 5')
plt.show()
我尝试解决了这个问题,但未能成功。