Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Image Fourier transform with Python OpenCV

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how Python OpenCV implements Fourier transform of images. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

Two-dimensional Discrete Fourier Transform (DFT)

For two-dimensional image processing, it is common to use x , y x, yx,y to represent discrete spatial domain coordinate variables and u ,v to represent discrete frequency domain variables. Two-dimensional discrete Fourier transform (DFT) and inverse transform (IDFT) are:

Two-dimensional discrete Fourier transforms can also be expressed in polar coordinates:

The Fourier spectrum is:

The Fourier phase spectrum is:

The Fourier power spectrum is:

Spatial sampling and frequency spacing correspond to each other, and the spacing between discrete variables corresponding to frequency domain is: Δu=1/MΔT, Δ u =1/NΔZ. That is, the spacing between samples in the frequency domain is inversely proportional to the product of the spacing between spatial samples and the number of samples.

Spatial domain filters and frequency domain filters are also corresponding to each other. The two-dimensional convolution theorem is the link between spatial domain and frequency domain filters:

This shows that F and H are Fourier transforms of f and h, respectively; the Fourier transform of the spatial convolution of f and h is the product of their transforms.

OpenCV implements image Fourier transform (cv.dft)

Fourier transform of images can also be realized by using cv.dft() function in OpenCV, and cv.idft() function realizes inverse Fourier transform of images.

Function Description:

cv.dft(src[, dst[, flags[, nonzeroRows]]]) → dstcv.idft(src[, dst[, flags[, nonzeroRows]]]) → dst

Parameter Description:

src: Input image, single channel grayscale image, using np.float32 format

dst: Output image, image size is the same as src, data type is determined by flag

flag: conversion identifier

cv.DFT_INVERSE: Replace default forward transform with one or two dimensional inverse transform

cv.DFT_SCALE: scaling identifier, scaling results based on the number of elements, often used with DFT_INVERSE

cv.DFT_ROWS: Forward or inverse Fourier transform of each row of the input matrix, often used for complex operations such as three-dimensional or high-dimensional transformations

cv.DFT_COMPLEX_OUTPUT: Forward transforms a one-or two-dimensional real array, default method, resulting in a complex array represented by 2 channels, the first channel being the real part and the second channel being the imaginary part

cv.DFT_REAL_OUTPUT: Inverse transform of one or two dimensional array of complex numbers, the result is usually a complex matrix of the same size

Notes:

1. The input image src is in np.float32 format. If the image is in np.uint8 format, it must be converted to np.float32 format first.

2. With the default method cv.DFT_COMPLEX_OUTPUT, the input src is a single-channel two-dimensional array in np.float32 format, and the output dst is a two-dimensional array of 2 channels, dft[:,:,0] for the first channel being the real part and dft[:,:,1] for the second channel being the imaginary part.

3. It cannot be used directly to display images. The result of the Fourier transform can be converted to gray [0,255] using the cv.magnitude() function.

idft (src, dst, flags) is equivalent to dft(src, dst, flags=DFT_INVERSE).

5. OpenCV implements Fourier transform, which is faster than Numpy.

When the transformation identifier is cv.DFT_COMPLEX_OUTPUT, the output of the cv.dft() function is a two-dimensional array of 2 channels, and the cv.magnitude() function can be used to calculate the magnitude of the two-dimensional vector.

Function Description:

cv.magnitude(x, y[, magnitude]) → dst

Parameter Description:

x: One dimensional or multidimensional array, also represents the real part of a complex number, floating point type

y: One dimensional or multidimensional array, also represents the imaginary part of complex numbers, floating point type, array size must be the same as x

dst: Output array, array size and data type are the same as x, operation formula is:

The range of Fourier transform and correlation operation may not be suitable for image display, so normalization is needed. The cv.normalize() function in OpenCV enables normalization of images.

Function Description:

cv.normalize(src, dst[, alpha[, beta[, norm_type[, dtype[, mask]]]]]) → dst

Parameter Description:

src: Input image

dst: output result, same size and type as input image

alpha: Minimum normalized value, optional, default 0

beta: Maximum normalized value, optional, default 1

norm_type: Normalized type

NORM_INF: Linf norm (maximum of absolute values)

NORM_L1: L1 norm (sum of absolute values)

NORM_L2: L2 norm (Euclidean distance), default type

NORM_MINMAX: Linear zoom, common type

dtype: Optional, default value-1, means that the output matrix is the same as the input image type

mask: mask mask, optional, default no mask

Fourier transform theoretically requires O(MN)² operations, which is very time-consuming; fast Fourier transform only requires O(MN (MN)) operations to complete.

The Fourier transform function cv.dft() in OpenCV performs best for matrices whose rows and columns can be decomposed into 2^p*3^q*5^r. In order to improve the computational performance, 0 can be added to the right and lower sides of the original matrix to satisfy the decomposition condition. The cv.getOptimalDFTSize() function in OpenCV enables optimal DFT size expansion of images and works with cv.dft() and np.fft.fft2().

Function Description:

cv.getOptimalDFTSize(versize) → retval

Parameter Description:

size: array size

retval: optimal array size for DFT extensions

sample code # 8.11: OpenCV implements discrete Fourier transform of 2D images imgGray = cv2.imread("../ images/Fig0424a.tif", flags=0) # flags=0 Read as grayscale image # cv2.dft Fourier transform of images imgFloat32 = np.float32(imgGray) #Convert image to float32 dft = cv2.dft(imgFloat32, flags=cv2.DFT_COMPLEX_OUTPUT) #Fourier Transform dftShift = np.fft.fftshift(dft) #Move low frequency components to the center of the frequency domain image #Amplitude spectrum # ampSpe = np.sqrt(np.power(dft[:,:,0], 2) + np.power(dftShift[:,:,1], 2)) dftAmp = cv2.amplitude (dft[:,:,0], dft[:,:,1]) #amplitude spectrum, uncentered dftShiftAmp = cv2.amplitude (dftShift[:,:,0], dftShift[:,:,1]) #amplitude spectrum, centralizing dftAmpLog = np.log(1 + dftShiftAmp) #Log transform of amplitude spectrum for display #phase spectrum phase = np.arctan2(dftShift[:,:,1], dftShift[:,:,0]) #Calculate phase angle in radians dftPhi = phase / np.pi*180 #Convert phase angle to [-180, 180] print("dftMag max={}, min={}".format(dftAmp.max(), dftAmp.min())) print("dftPhi max={}, min={}".format(dftPhi.max(), dftPhi.min())) print("dftAmpLog max={}, min={}".format(dftAmpLog.max(), dftAmpLog.min())) # cv2.idft Implement inverse Fourier transform of images invShift = np.fft.ifftshift(dftShift) #Inverts low frequencies back to image corners imgIdft = cv2.idft(invShift) #Inverse Fourier Transform imgRebuild = cv2.magnitude(imgIdft[:,:,0], imgIdft[:,:,1]) #Rebuild Image plt.figure(figsize=(9, 6)) plt.subplot(231), plt.title("Original image"), plt.axis('off') plt.imshow(imgGray, cmap='gray') plt.subplot(232), plt.title("DFT Phase"), plt.axis('off') plt.imshow(dftPhi, cmap='gray') plt.subplot(233), plt.title("Rebuild image with IDFT"), plt.axis('off') plt.imshow(imgRebuild, cmap='gray') plt.subplot(234), plt.title("DFT amplitude spectrum"), plt.axis('off') plt.imshow(dftAmp, cmap='gray') plt.subplot(235), plt.title("DFT-shift amplitude"), plt.axis('off') plt.imshow(dftShiftAmp, cmap='gray') plt.subplot(236), plt.title("Log-trans of DFT amp"), plt.axis('off') plt.imshow(dftAmpLog, cmap='gray') plt.tight_layout() plt.show()

Thank you for reading! About "Python OpenCV how to achieve image Fourier transform" This article is shared here, I hope the above content can be of some help to everyone, so that everyone can learn more knowledge, if you think the article is good, you can share it to let more people see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report