目录
原理(冈萨雷斯第四版p235):
代码:
结果:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# for gray image
def auto_median_filter(img, S_max):
output = img.copy()
def class_B(z_xy, z_med, z_max, z_min):
if (z_min < z_xy) & (z_xy < z_max):
return z_xy
else:
return z_med
S_ori = 3
copy = cv2.copyMakeBorder(img, *[S_ori // 2] * 4, borderType=cv2.BORDER_DEFAULT) # 补零
for i in range(img.shape[0]):
for j in range(img.shape[1]):
def class_A(copy, S_ori=3):
board = S_ori // 2
z_med = np.median(copy[i:i + board, j:j + board])
z_max = np.max(copy[i:i + board, j:j + board])
z_min = np.min(copy[i:i + board, j:j + board])
if (z_min < z_med) & (z_med < z_max):
output[i, j] = class_B(copy[i, j], z_med, z_max, z_min)
else:
# next_size = S_ori + 2
next_size = cv2.copyMakeBorder(copy, *[1] * 4, borderType=cv2.BORDER_DEFAULT) # 增尺寸
S_ori = S_ori + 2
if S_ori <= S_max:
return class_A(next_size, S_ori)
else:
output[i, j] = z_med
class_A(copy, 3)
return output.astype(np.uint8)
def label_def(): # 定义坐标数字字体及大小
plt.xticks(fontproperties='Times New Roman', size=8)
plt.yticks(fontproperties='Times New Roman', size=8)
if __name__ == '__main__':
img = cv2.imread('D://pictures//Fig0335(a)(ckt_board_saltpep_prob_pt05).tif', 0)
img_median = cv2.medianBlur(img, 7)
out = auto_median_filter(img, 7)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.subplot(131), plt.imshow(img, "gray"), plt.title('椒盐噪声', fontsize='small'), label_def()
plt.subplot(132), plt.imshow(img_median, "gray"), plt.title('中值滤波', fontsize='small'), label_def()
plt.subplot(133), plt.imshow(out, "gray"), plt.title('自适应中值滤波', fontsize='small'), label_def()
plt.show()
原文描述:
自适应中值滤波器的另一个优点是它会在试图保留图像细节的同时平滑非冲激噪声,而传统中值滤波器是做不到这一点的。
可见实验结果证实了这一点!