赞
踩
import matplotlib.pyplot as plt
import cv2 as cv
import numpy as np
import random
def salt_pepper_noise(img,prob): #椒盐噪声
imgin = img.copy()
width, height = img.shape[:2]
thres = 1-prob
for i in range(width):
for j in range(height):
noi_num = random.random()
if noi_num < prob:
noi_flag = 0
elif noi_num > thres:
noi_flag = 255
else:
noi_flag = imgin[i][j]
imgin[i][j] = noi_flag
return imgin
def self_adp_med_filter(img):
imgin = img.copy()
imgout = np.zeros(imgin.shape, dtype=np.uint16) #使用uint16是因为发现图片数字可能超过255
width, height = imgin.shape[:2]
for i in range(width):
for j in range(height):
window = 1
filflag = 0
if (i>=window and i<(width - window)) and (j>=window and j<(height - window)): #不计算图像最外圈
while filflag == 0:
square_sequance = np.zeros((window * 2 + 1) ** 2, dtype=np.uint16)
seqc = 0
for m in range(window * 2 + 1):
for n in range(window * 2 + 1):
if (i-window + m == width) or (j-window + n == height):
break
square_sequance[seqc] = imgin[i-window + m][j-window + n]
seqc += 1
#square_sequance.append(imgin[i-window + m][j-window + n])
square_sequance.sort() #排序
a1 = np.float32(square_sequance[((window * 2 + 1)**2//2)]) - np.float32(square_sequance[0]) #A层
a2 = np.float32(square_sequance[((window * 2 + 1)**2//2)]) - np.float32(square_sequance[(window * 2 + 1)**2-1])
if a1 > 0 and a2 < 0: #转到B层
b1 = np.float32(imgin[i][j]) - np.float32(square_sequance[0]) #B层
b2 = np.float32(imgin[i][j]) - np.float32(square_sequance[(window * 2 + 1)**2-1]) #计算时使用float,因为图像进行计算时不会出现负数
if b1 > 0 and b2 < 0:
imgout[i][j] = imgin[i][j]
else:
imgout[i][j] = np.uint16(square_sequance[((window * 2 + 1)**2//2)])
break
else: #增大窗口尺寸
if window <= i and window <= j and (height - j-1) >= window and (width - i-1) >= window: #防止窗口溢出边缘
window += 1
continue
else :
imgout[i][j] = imgin[i][j]
break
else:
imgout[i][j] = np.uint8(imgin[i][j])
return imgout
if __name__ == '__main__':
img_orig = cv.imread('/Users/mushroom/Downloads/python_jup/a.jpg') # 读取灰度图片
grayimg=cv.cvtColor(img_orig,cv.COLOR_BGRA2GRAY) # 将图片设置为仅为灰度图
outimg50 = salt_pepper_noise(grayimg,0.25)
outimg20 = salt_pepper_noise(grayimg,0.1)
imgrebuild50 = self_adp_med_filter(outimg50)
imgrebuild20 = self_adp_med_filter(outimg20)
plt.subplot(111),plt.imshow(cv.cvtColor(img_orig, cv.COLOR_BGR2RGB))
plt.show()
plt.subplot(121),plt.imshow(cv.cvtColor(outimg50, cv.COLOR_BGR2RGB))
plt.subplot(122),plt.imshow(cv.cvtColor(outimg20, cv.COLOR_BGR2RGB))
plt.show()
plt.subplot(121),plt.imshow(cv.cvtColor(imgrebuild50, cv.COLOR_BGR2RGB))
plt.subplot(122),plt.imshow(cv.cvtColor(imgrebuild20, cv.COLOR_BGR2RGB))
plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。