【千律】OpenCV基础:频域滤波--巴特沃斯滤波

环境:Python3.8 和 OpenCV

内容:频域滤波--巴特沃斯滤波

低通滤波:

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


# 封装图片显示函数
def image_show(image):
    if image.ndim == 2:
        plt.imshow(image, cmap='gray')
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        plt.imshow(image)
    plt.show()

# 巴特沃斯滤波
def Low_filter(N, M, D0, n):
    x, y = np.meshgrid(np.arange(M) - M//2, np.arange(N) - N//2)
    D = np.sqrt(x**2 + y**2)
    H = 1 / (1 + (D / D0) ** (2*n))
    return H

if __name__ == '__main__':

    # 读取图像
    img_desk = cv.imread('desk.png', 0)

    # 参数设置
    D0 = 20      # 滤波器参数1
    n = 4        # 滤波器参数2
    M, N = img_desk.shape

    # 二维离散傅里叶变换
    desk_fft = np.fft.fft2(img_desk)
    desk_ffts = np.fft.fftshift(desk_fft)

    # 低通滤波变换
    desk_low = Low_filter(M, N, D0, n)
    desk_HF = desk_low * desk_ffts

    # 傅里叶反变换
    img_desk_rec = np.fft.ifft2(desk_HF)

    # 显示结果
    image_show(np.abs(img_desk_rec))

高通滤波:

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


# 封装图片显示函数
def image_show(image):
    if image.ndim == 2:
        plt.imshow(image, cmap='gray')
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        plt.imshow(image)
    plt.show()

# 巴特沃斯滤波
def High_filter(N, M, D0, n):
    x, y = np.meshgrid(np.arange(M) - M//2, np.arange(N) - N//2)
    D = np.sqrt(x**2 + y**2)
    H = 1 / (1 + (D0 / (D + 1e-5)) ** (2*n))
    return H

if __name__ == '__main__':

    # 读取图像
    img_desk = cv.imread('desk.png', 0)

    # 参数设置
    D0 = 20      # 滤波器参数1
    n = 4        # 滤波器参数2
    M, N = img_desk.shape

    # 二维离散傅里叶变换
    desk_fft = np.fft.fft2(img_desk)
    desk_ffts = np.fft.fftshift(desk_fft)

    # 高通滤波变换
    desk_low = High_filter(M, N, D0, n)
    desk_HF = desk_low * desk_ffts

    # 傅里叶反变换
    img_desk_rec = np.fft.ifft2(desk_HF)

    # 显示结果
    image_show(np.abs(img_desk_rec))

你可能感兴趣的:(OpenCV基础,opencv,计算机视觉,python)