目錄
原理(岡薩雷斯第四版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()
原文描述:
自適應中值濾波器的另一個優點是它會在試圖保留圖像細節的同時平滑非沖激噪聲,而傳統中值濾波器是做不到這一點的。
可見實驗結果證實了這一點!