繁体   English   中英

如何使用 np.fft.ifft2 对图像进行反向傅立叶变换 - Python

[英]How to reverse Fourier Transform on an image with np.fft.ifft2 - Python

我是 Python 的傅里叶变换新手。

由于傅立叶变换,我想在图像上隔离一个场。 这是我的照片:

在此处输入图像描述

这是我应该获得的:

在此处输入图像描述

到目前为止,这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import cv2

path = "C:/Users/cecil/OneDrive/Bureau/00_TP_M2TSI/TP Traitement Image/BE1 PDF/BE1 PDF/champs.png"

img = plt.imread(path)

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #converting to grayscale


plt.set_cmap("gray")
plt.subplot(131)
plt.imshow(img)
plt.axis("off")

# Calculate the Fourier transform of the grating
ft = np.fft.ifftshift(img)
ft = np.fft.fft2(ft)
ft = np.fft.fftshift(ft)
plt.subplot(132)
plt.imshow(np.log(abs(ft)))
plt.axis("off")
    
#isolating the band we want to keep (we define 2 affine functions to border the band and keep only the 
    # values that are inbetween)
for x in range(0,512): 
    y1 = 0.77*x + 55
    y2 = 0.77*x + 65
    for y in range(0,512):
        if not(y > y1 and y < y2) : 
            ft[y,x] = 0

            
# Calculate the inverse Fourier transform of 
# the Fourier transform
ift = np.fft.ifftshift(ft)
ift = np.fft.ifft2(ift)
ift = np.fft.fftshift(ift)
ift = ift.real  # Take only the real part

plt.subplot(133)
plt.imshow(ift)
plt.axis("off")
plt.show()

我的问题是我获得了这张图片而不是我想要的图片(见上文):

在此处输入图像描述

谁能帮帮我吗?

所以显然我解决了这个问题。 看来我实际上需要像这样在分离的行中进行 shift 和 fft 以及 ishift 和 ifft :

# Calculate the Fourier transform of the grating
spectre = fft2(imgris)
spectre = fftshift(spectre)
plt.imshow(np.log(abs(spectre)))
plt.show()

bande = np.zeros((512,512), dtype=complex)

for x in range(0,512): 
    y1 = 0.77*x + 40
    y2 = 0.77*x + 80
    for y in range(0,512):
        if y > y1 and y < y2 : 
            bande[y,x] = spectre[y,x]
        if x > (512/2-20) and x < (512/2+20):
            bande[y,x] = 0
            
plt.imshow(abs(bande))
plt.show()

real = bande.real
phases = bande.imag
bande_mod = np.empty(real.shape, dtype=complex)
bande_mod.real = real
bande_mod.imag = phases

champisolé= ifftshift(bande_mod)
champisolé= np.abs(ifft2(champisolé))

plt.imshow(champisolé)
plt.show()

获得的图像(第一张图片)有点模糊,我想隔离的区域周围有很多不需要的像素,但通过一些过滤器,我获得了一个完美的隔离区域(甚至比老师的更好。)(第二张图片)。

在此处输入图像描述

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM