编程求给定图像f的均值滤波结果g1,中值滤波结果g2,滤波核大小均设为3×3,边界填充选择0填充方式。打印结果进行比较。可自编函数,也可使用opencv库函数。
f=
1 | 1 | 1 | 1 | 3 |
1 | 1 | 1 | 3 | 7 |
1 | 1 | 3 | 7 | 7 |
1 | 3 | 7 | 1 | 7 |
3 | 7 | 7 | 7 | 7 |
import numpy as np
def mean_filter(img, kernel_size=3):
# 获取图像的行数和列数
rows, cols = img.shape
# 构建0填充的滤波核
pad = kernel_size // 2
kernel = np.ones((kernel_size, kernel_size), dtype=np.float32) / (kernel_size ** 2)
# 执行0填充
img_pad = np.pad(img, ((pad, pad), (pad, pad)), mode='constant', constant_values=0)
# 定义输出图像
img_out = np.zeros_like(img, dtype=np.float32)
# 执行均值滤波操作
for i in range(rows):
for j in range(cols):
img_out[i, j] = np.sum(kernel * img_pad[i:i+kernel_size, j:j+kernel_size])
# 将输出图像转换为8位无符号整型
img_out = np.clip(img_out, 0, 255).astype(np.uint8)
return img_out
def median_filter(img, kernel_size=3):
# 获取图像的行数和列数
rows, cols = img.shape
# 构建0填充的滤波核
pad = kernel_size // 2
# 定义输出图像
img_out = np.zeros_like(img, dtype=np.uint8)
# 执行中值滤波操作
for i in range(rows):
for j in range(cols):
img_out[i, j] = np.median(img[max(i-pad,0):i+pad+1, max(j-pad,0):j+pad+1])
return img_out
# 定义图像f
f = np.array([[1, 1, 1, 1, 3],
[1, 1, 1, 3, 7],
[1, 1, 3, 7, 7],
[1, 3, 7, 1, 7],
[3, 7, 7, 7, 7]], dtype=np.uint8)
# 均值滤波
g1 = mean_filter(f, kernel_size=3)
# 中值滤波
g2 = median_filter(f, kernel_size=3)
# 打印结果
print("均值滤波结果g1:")
print(g1)
print("\n中值滤波结果g2:")
print(g2)
# 显示原图像f、均值滤波结果g1和中值滤波结果g2
import cv2
cv2.imshow("Original Image", f)
cv2.imshow("Mean Filtered Image", g1)
cv2.imshow("Median Filtered Image", g2)
cv2.waitKey(0)
cv2.destroyAllWindows()