、读取图像Barbara.bmp,基于OpenCV设计滤波器模板为椭圆(a/b=2)的理想低通滤波与高通滤波,显示原始图像,滤波后的频谱图和高低通滤波处理后的图像。python代码
时间: 2024-10-05 19:01:30 浏览: 30
对三幅经典的图像(lena、peppers、barbara)分别加上加性噪声、椒盐噪声和乘性噪声 进行巴特沃斯、高斯低通等滤波
首先,你需要导入必要的库,然后读取图像,接着创建一个椭圆形滤波器模板,最后应用滤波器到图像上。这里是一个简单的Python代码片段,使用OpenCV完成上述任务:
```python
import cv2
import numpy as np
from scipy.signal import freqz
import matplotlib.pyplot as plt
# 读取图像
image = cv2.imread('Barbara.bmp', 0)
if image is None:
print("Image not found.")
else:
# 定义滤波器参数
a = 50 # 滤波器半径(假设a/b=2)
b = a / 2
# 创建理想低通滤波器模板(椭圆卷积核)
kernel_lowpass = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * a + 1, 2 * b + 1), (a, b))
# 创建理想高通滤波器模板(减去低通模板)
kernel_highpass = cv2.morphologyEx(kernel_lowpass, cv2.MORPH_OPEN, kernel_lowpass)
# 应用滤波器
filtered_lowpass = cv2.filter2D(image, -1, kernel_lowpass)
filtered_highpass = cv2.filter2D(image, -1, kernel_highpass)
# 计算滤波器的频率响应
w, h = freqz(kernel_lowpass.ravel(), worN=800)
lowpass_freq = 20*np.log10(np.abs(h))
_, highpass_freq = freqz(kernel_highpass.ravel(), worN=800)
highpass_freq = 20*np.log10(np.abs(h))
# 显示原始图像、滤波后的频谱图以及滤波结果
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
axs[0, 0].imshow(image, cmap='gray')
axs[0, 0].set_title('Original Image')
axs[0, 1].plot(w, lowpass_freq, label='Low-pass Filter')
axs[0, 1].plot(w, highpass_freq, label='High-pass Filter')
axs[0, 1].set_xlabel('Frequency (Hz)')
axs[0, 1].set_ylabel('Amplitude (dB)')
axs[0, 1].legend()
axs[0, 1].set_title('Filter Frequency Response')
axs[1, 0].imshow(filtered_lowpass, cmap='gray')
axs[1, 0].set_title('Filtered with Low-pass')
axs[1, 1].imshow(filtered_highpass, cmap='gray')
axs[1, 1].set_title('Filtered with High-pass')
for ax in axs.flat:
ax.set(xticks=[], yticks=[])
plt.tight_layout()
plt.show()
阅读全文