OpenCV实现傅里叶滤波(个人笔记)

import cv2 as cv
import numpy as np
from timeit import default_timer


def fft(gray_img):
    dft = cv.dft(np.float32(img), flags=cv.DFT_COMPLEX_OUTPUT)
    dft_shift = dft  # np.fft.fftshift(dft)
    magnitude_spectrum = 20 * np.log(cv.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
    cv.normalize(magnitude_spectrum, magnitude_spectrum, 0, 255, cv.NORM_MINMAX)
    magnitude_spectrum = np.uint8(magnitude_spectrum)
    cv.imshow("mag", magnitude_spectrum)
    # ret, thresh = cv.threshold(magnitude_spectrum, 0, 255, cv.THRESH_OTSU)
    # cv.imshow("thresh", thresh)

    rows, cols = gray_img.shape

    # 将低频的信号设置为0
    # 一般不使用矩阵窗口,而是使用高斯窗口
    mask = np.full((rows, cols), fill_value=0, dtype=np.uint8)
    ratio = 0.5
    cv.ellipse(mask, (cols // 2, rows // 2), (int(ratio * cols), int(ratio * rows)), 0, 0, 360, 1, -1)
    # crow, ccol = rows // 2, cols // 2
    # dr, dc = int(0.01 * rows), int(0.01 * cols)
    # mask[:, ccol - dc:ccol + dc] = 0
    # mask[crow - dr:crow + dr, :] = 0
    cv.normalize(mask, mask, 0, 255, cv.NORM_MINMAX)
    cv.imshow("mask", mask)
    mask = np.tile(np.expand_dims(mask, axis=-1), [1, 1, 2])
    dft_shift = dft_shift * mask

    # 将频域偏移,转化为时域
    f_ishift = dft_shift  # np.fft.ifftshift(dft_shift)
    img_back = cv.idft(f_ishift)
    img_back_int = cv.magnitude(img_back[:, :, 0], img_back[:, :, 1])
    cv.normalize(img_back_int, img_back_int, 0, 255, cv.NORM_MINMAX)
    img_back_int = np.uint8(img_back_int)

    return img_back_int


if __name__ == "__main__":
    data_list = "./dataset/total/screen_00.txt"
    with open(data_list, "r") as file:
        data = file.readlines()

    for file in data:
        file = file.strip().split()
        path = file[0]
        path = path.replace("/dahuafs/userdata/231365", "Z:")
        img = cv.imread(path, cv.IMREAD_GRAYSCALE)
        # img = cv.resize(img, dsize=None, fx=0.5, fy=0.5)
        cv.imshow("src", img)
        start = default_timer()
        res = fft(img)
        print("time cost:", default_timer() - start)
        cv.imshow("res", res)

        if cv.waitKey() & 0xFF == ord('q'):
            break
    cv.destroyAllWindows()

 


版权声明:本文为vector_Lu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。