提示:内容整理自:https://github.com/gzr2017/ImageProcessing100Wen
CV小白从0开始学数字图像处理
35 傅立叶变换——带通滤波
将imori.jpg
灰度化之后进行傅立叶变换并进行带通滤波,之后再用傅立叶逆变换复原!
在这里,我们使用可以保留介于低频成分和高频成分之间的分量的带通滤波器。在这里,我们使用可以去除低频部分,只保留高频部分的高通滤波器。假设从低频的中心到高频的距离为r,我们保留0.1r至0.5r的分量。
代码如下:
1.引入库
CV2计算机视觉库
import cv2
import numpy as np
import matplotlib.pyplot as plt
2.读入数据
img = cv2.imread("imori.jpg").astype(np.float32)
H, W, C = img.shape
3.灰度化
gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]
4.DFT
K = W
L = H
M = W
N = H
G = np.zeros((L, K), dtype=np.complex)
x = np.tile(np.arange(W), (H, 1))
y = np.arange(H).repeat(W).reshape(H, -1)
for l in range(L):
for k in range(K):
G[l, k] = np.sum(gray * np.exp(-2j * np.pi * (x * k / M + y * l / N))) / np.sqrt(M * N)
5.低通滤波
_G = np.zeros_like(G)
_G[:H//2, :W//2] = G[H//2:, W//2:]
_G[:H//2, W//2:] = G[H//2:, :W//2]
_G[H//2:, :W//2] = G[:H//2, W//2:]
_G[H//2:, W//2:] = G[:H//2, :W//2]
p1 = 0.1
p2 = 0.5
_x = x - W // 2
_y = y - H // 2
r = np.sqrt(_x ** 2 + _y ** 2)
mask = np.zeros((H, W), dtype=np.float32)
mask[np.where((r > (W//2*p1)) & (r < (W//2*p2)))] = 1
_G *= mask
G[:H//2, :W//2] = _G[H//2:, W//2:]
G[:H//2, W//2:] = _G[H//2:, :W//2]
G[H//2:, :W//2] = _G[:H//2, W//2:]
G[H//2:, W//2:] = _G[:H//2, :W//2]
6.IDFT
out = np.zeros((H, W), dtype=np.float32)
for n in range(N):
for m in range(M):
out[n,m] = np.abs(np.sum(G * np.exp(2j * np.pi * (x * m / M + y * n / N)))) / np.sqrt(M * N)
out[out>255] = 255
out = out.astype(np.uint8)
7.保存结果
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)