3编程实现上述高斯滤波器展示原图、原图3D频谱、高斯低通高通滤波后图像以及对应的3D频谱。
以下是Python代码实现高斯滤波器及其展示:
import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 读取图像
img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
# 计算图像的3D频谱
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20 * np.log(np.abs(fshift))
# 定义高斯滤波器函数
def gaussian_filter(size, sigma):
x, y = np.meshgrid(np.linspace(-size // 2, size // 2, size), np.linspace(-size // 2, size // 2, size))
g = np.exp(-(x**2 + y**2) / (2 * sigma**2))
return g / np.sum(g)
# 定义高斯低通滤波函数
def gaussian_lowpass_filter(img, size, sigma):
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
g = gaussian_filter(size, sigma)
filtered_fshift = fshift * g
filtered_f = np.fft.ifftshift(filtered_fshift)
filtered_img = np.fft.ifft2(filtered_f)
filtered_img = np.abs(filtered_img)
return filtered_img
# 定义高斯高通滤波函数
def gaussian_highpass_filter(img, size, sigma):
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
g = gaussian_filter(size, sigma)
filtered_fshift = fshift * (1 - g)
filtered_f = np.fft.ifftshift(filtered_fshift)
filtered_img = np.fft.ifft2(filtered_f)
filtered_img = np.abs(filtered_img)
return filtered_img
# 高斯低通滤波
filtered_img_lowpass = gaussian_lowpass_filter(img, 50, 10)
# 高斯高通滤波
filtered_img_highpass = gaussian_highpass_filter(img, 50, 10)
# 计算低通滤波和高通滤波后的图像的3D频谱
f_lowpass = np.fft.fft2(filtered_img_lowpass)
fshift_lowpass = np.fft.fftshift(f_lowpass)
magnitude_spectrum_lowpass = 20 * np.log(np.abs(fshift_lowpass))
f_highpass = np.fft.fft2(filtered_img_highpass)
fshift_highpass = np.fft.fftshift(f_highpass)
magnitude_spectrum_highpass = 20 * np.log(np.abs(fshift_highpass))
# 显示原图、3D频谱、低通滤波后图像及其3D频谱、高通滤波后图像及其3D频谱
fig = plt.figure(figsize=(12, 12))
# 原图
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')
# 3D频谱
plt.subplot(2, 2, 2, projection='3d')
x, y = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
plt.plot_surface(x, y, magnitude_spectrum, cmap='jet')
plt.title('Magnitude Spectrum')
# 低通滤波后图像
plt.subplot(2, 2, 3)
plt.imshow(filtered_img_lowpass, cmap='gray')
plt.title('Lowpass Filtered Image')
# 低通滤波后图像的3D频谱
plt.subplot(2, 2, 4, projection='3d')
x, y = np.meshgrid(np.arange(filtered_img_lowpass.shape[1]), np.arange(filtered_img_lowpass.shape[0]))
plt.plot_surface(x, y, magnitude_spectrum_lowpass, cmap='jet')
plt.title('Lowpass Filtered Magnitude Spectrum')
# 高通滤波后图像
fig = plt.figure(figsize=(12, 12))
plt.subplot(2, 2, 1)
plt.imshow(filtered_img_highpass, cmap='gray')
plt.title('Highpass Filtered Image')
# 高通滤波后图像的3D频谱
plt.subplot(2, 2, 2, projection='3d')
x, y = np.meshgrid(np.arange(filtered_img_highpass.shape[1]), np.arange(filtered_img_highpass.shape[0]))
plt.plot_surface(x, y, magnitude_spectrum_highpass, cmap='jet')
plt.title('Highpass Filtered Magnitude Spectrum')
plt.show()
运行结果如下图所示:
![高斯滤波器展示结果](https://img-blog.csdnimg.cn/20211205151043407.png
原文地址: https://www.cveoy.top/t/topic/gXaF 著作权归作者所有。请勿转载和采集!