基於opencv的python中3*3鄰域平滑,中值去模糊處理
調用numpy的zeros函數創建所需類型的3個數組,用於平滑,取中值和擴充之後的圖片。然後用冒泡排序取得中間值完成中值處理,最後在一個窗口上顯示。
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('Fig0335.tif') # 測試圖片
H = img.shape[0] #獲取圖片的高(像素點個數)
W = img.shape[1] #獲取圖片的寬(像素點個數)
img3 = np.zeros((H, W, 3), np.uint8) # 3*3鄰域平滑後的圖像
imgmid = np.zeros((H, W, 3), np.uint8) # 3*3鄰域內取中值的圖像
tmpImg = np.zeros((H + 2, W + 2, 3), np.uint8) # 擴充之後的圖像
for i in range(H):
for j in range(W):
tmpImg[i + 1, j + 1] = img[i, j] #將測試圖片複製到擴充之後的圖像中
for i in range(H):
for j in range(W):
S = []
for x in range(3):
for y in range(3): #3*3鄰域
# S[x * 3 + y] = tmpImg[i + x, j + y, 0]
S.append(tmpImg[i + x, j + y, 0])
img3[i, j, 0] = sum(S) // 9 #取平均值
img3[i, j, 1] = img3[i, j, 0]
img3[i, j, 2] = img3[i, j, 0]
# 冒泡排序,只要排到中間一個值,即4,因此x範圍是8->3
for x in range(8, 3, -1): #從8減少到3,每次減少1,因爲每循環一次就排好一個數
for y in range(x):
if S[y + 1] > S[y]: #小的數往後移
temp = S[y]
S[y] = S[y + 1]
S[y + 1] = temp
imgmid[i, j, 0] = S[4] #取中間值
imgmid[i, j, 1] = imgmid[i, j, 0]
imgmid[i, j, 2] = imgmid[i, j, 0]
# 原圖
plt.subplot(1, 3, 1) #將窗口分爲1行三列,第1個子圖
plt.axis('off') #不顯示座標尺寸
plt.title('Original image') #第一幅圖片標題
plt.imshow(img) #繪製第一幅圖片
# 3*3鄰域
plt.subplot(1, 3, 2)
plt.axis('off')
plt.title('3*3 smoothing')
plt.imshow(img3)
# 鄰域中值替換之後
plt.subplot(1, 3, 3)
plt.axis('off')
plt.title('Middle Value Replaced Image')
plt.imshow(imgmid)
plt.show()
一個運行截圖(基於一本數字圖像處理書:岡薩雷斯)