如何使用OpenCV Python查詢影像的傅立葉變換?


離散傅立葉變換 (DFT) 和離散傅立葉逆變換 (IDFT) 應用於影像以查詢頻域。為了找到影像的傅立葉變換,我們使用函式cv2.dft()cv2.idft()。我們可以應用傅立葉變換來分析各種濾波器的頻率特性。

步驟

為了找到輸入影像的傅立葉變換,可以按照以下步驟操作:

  • 匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫為OpenCV、NumpyMatplotlib。請確保您已安裝它們。

  • 使用cv2.imread()方法將輸入影像載入為灰度影像。並將灰度影像的型別轉換為float32

  • 使用cv2.dft()並傳遞所需引數來查詢影像上的離散傅立葉變換。

  • 呼叫np.fft.fftshift()將零頻率分量移到頻譜的中心。

  • 應用對數變換並可視化幅度譜。

  • 為了視覺化變換後的影像,我們應用逆變換np.fft.ifftshift()cv2.idft()。請參見下面討論的第二個示例。

讓我們來看一些例子,以便清楚地理解這個問題。

輸入影像

我們將在下面的示例中使用此影像作為輸入檔案。


示例

在這個程式中,我們找到輸入影像的離散傅立葉變換。我們找到並繪製幅度譜。

# import required libraries import numpy as np import cv2 from matplotlib import pyplot as plt # read input image img = cv2.imread('film.jpg',0) # find the discrete fourier transform of the image dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT) # shift zero-frequency component to the center of the spectrum dft_shift = np.fft.fftshift(dft) magnitude_spectrum = 20*np.log(cv2.magnitude( dft_shift[:,:,0], dft_shift[:,:,1]) ) # visualize input image and the magnitude spectrum 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 程式後,它將生成以下輸出視窗:


示例

在這個程式中,我們找到輸入影像的離散傅立葉變換。我們使用諸如ifftshift()idft()之類的反函式重建影像。

import numpy as np import cv2 from matplotlib import pyplot as plt # read the input image img = cv2.imread('film.jpg',0) # find the discrete fourier transform of the image dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT) # hift zero-frequency component to the center of the spectrum dft_shift = np.fft.fftshift(dft) rows, cols = img.shape crow,ccol = rows//2 , cols//2 mask = np.zeros((rows,cols,2),np.uint8) mask[crow-30:crow+30, ccol-30:ccol+30] = 1 # apply mask and inverse DFT fshift = dft_shift*mask f_ishift = np.fft.ifftshift(fshift) img_back = cv2.idft(f_ishift) img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1]) # visualize the images plt.subplot(121),plt.imshow(img, cmap = 'gray') plt.title('Input Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(img_back, cmap = 'gray') plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([]) plt.show()

輸出

執行上面的 Python 程式後,它將生成以下輸出視窗:


更新於:2022年12月2日

4K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.