首页 > 解决方案 > OpenCV Python 频域过滤结果不如预期

问题描述

希望你们一切都好。

现在我正在做一个作业,要求我在频域中创建高通滤波器。我创建了所有过滤器。在我应用我的过滤器之后(当然是在将输入图像转换为频域,然后应用逆傅立叶进入空间域之后),输出图像是紫色调,而输入图像是灰度级。这是我的理想高通滤波器的输出:

在此处输入图像描述

这是输入图像:

在此处输入图像描述

这是我的高通滤波器功能:

import numpy as np

# The function takes two dimension inputs for the filter image;
# the third filter is D0, which defines the circle area of the High Pass Filter.
def idealHighPass(M, N, D0):
    # Initializing the filter with ones; since the filter is a complex function,
    # it has two channels, representing the real and imaginary parts:
    filter = np.ones((M, N, 2), dtype=np.uint8)
    
    # Scanning through each pixel and calculating the distance of each pixel
    # to the image center. If the pixel is within D0, it is changed to 0:
    for i in range(M):
        for j in range(N):
           filter[i][j] = 0

    return filter

这是我的主要代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt
from idealHighPass import idealHighPass
from highButterworth import highButterworth
from highGaussian import highGaussian

#img = cv2.imread("airfield-05small-auto.tif")
img = cv2.imread("input.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

m, n = img.shape

ft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
ft_shifted = dft_shift = np.fft.fftshift(ft)

# - IDEAL HIGH-PASS FILTER EXECUTION START -

filter = idealHighPass(m, n, 80)
filter = filter.astype((np.float32))

applied = ft_shifted * filter
fshift_mask_mag = 20 * np.log(cv2.magnitude(applied[:, :, 0], applied[:, :, 1]))
f_ishift = np.fft.ifftshift(applied)
img_back = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1])
cv2.imwrite("high_passed.png", img_back)
print(img_back.shape)

imgplot = plt.imshow(img_back)
plt.show()

# - IDEAL HIGH-PASS FILTER EXECUTION END -

标签: pythonfftopencv-pythonfrequency-analysis

解决方案


推荐阅读