How to transform a FFT (Fast Fourier Transform) into a Polar Transformation with Python?
我可以根据自己的图像创建FFT转换,但不知道如何继续...
我正在使用它来解决我的问题:对齐OCR的文本
到目前为止,这段代码对我一直有效:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import cv2 import numpy as np from matplotlib import pyplot as plt %matplotlib inline img = cv2.imread(r'test.jpg', cv2.IMREAD_GRAYSCALE) f = np.fft.fft2(img) fshift = np.fft.fftshift(f) magnitude_spectrum = 20 * np.log(np.abs(fshift)) plt.subplot(121), plt.imshow(img, cmap='gray') plt.title('Input Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(magnitude_spectrum, cmap='gray') plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([]) plt.show() |
我需要从极坐标转换生成的平均值,但是我不知道如何在Python中将FFT转换为极坐标转换。
这大致解决了您的问题; 在一个样本图像上进行了测试,结果看起来是可信的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # your code goes here... def transform_data(m): dpix, dpiy = m.shape x_c, y_c = np.unravel_index(np.argmax(m), m.shape) angles = np.linspace(0, np.pi*2, min(dpix, dpiy)) mrc = min(abs(x_c - dpix), abs(y_c - dpiy), x_c, y_c) radiuses = np.linspace(0, mrc, max(dpix, dpiy)) A, R = np.meshgrid(angles, radiuses) X = R * np.cos(A) Y = R * np.sin(A) return A, R, m[X.astype(int) + mrc - 1, Y.astype(int) + mrc - 1] angles, radiuses, m = transform_data(magnitude_spectrum) plt.contourf(angles, radiuses, m) |
最后,我们可以得到想要旋转原始图像的角度:
1 2 | sample_angles = np.linspace(0, 2 * np.pi, len(c.sum(axis=0))) / np.pi*180 turn_angle_in_degrees = 90 - sample_angles[np.argmax(c.sum(axis=0))] |
对于我的示例图像,我得到了:
1 | turn_angle_in_degrees = 3.2015810276679844 degrees. |
此外,我们可以绘制预计的频谱幅度:
1 | plt.plot(sample_angles, c.sum(axis=0)) |
希望有帮助...