opencv巴特沃兹低通滤波器python代码
时间: 2023-11-27 12:47:12 浏览: 41
以下是使用OpenCV实现巴特沃兹低通滤波器的Python代码:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg', 0)
# 定义巴特沃兹低通滤波器
def butterworth_lowpass_filter(img, d, n):
rows, cols = img.shape
crow, ccol = rows // 2, cols // 2
# 构建巴特沃兹低通滤波器
u, v = np.meshgrid(np.arange(cols), np.arange(rows))
d_uv = np.sqrt((u - ccol) ** 2 + (v - crow) ** 2)
H = 1 / (1 + (d / d_uv) ** (2 * n))
# 将滤波器应用于图像
img_fft = np.fft.fft2(img)
img_fft_shift = np.fft.fftshift(img_fft)
img_fft_shift_filtered = img_fft_shift * H
img_fft_filtered = np.fft.ifftshift(img_fft_shift_filtered)
img_filtered = np.fft.ifft2(img_fft_filtered)
img_filtered = np.abs(img_filtered)
return img_filtered
# 调用巴特沃兹低通滤波器函数
img_filtered = butterworth_lowpass_filter(img, 50, 2)
# 显示原始图像和滤波后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Butterworth Lowpass Filtered Image', img_filtered)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`butterworth_lowpass_filter`函数接受三个参数:输入图像`img`、截止频率`d`和阶数`n`。函数返回经过巴特沃兹低通滤波器处理后的图像。