椒盐噪声也称为脉冲噪声,是图像中经常见到的一种噪声
def salt_and_pepper_noise():
'''
添加椒盐噪声
image:原始图片
prob:噪声比例
'''
prob = 0.1
import cv2
import random
image = cv2.imread('sample1.jpg')
output = np.zeros(image.shape,np.uint8)
noise_out = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()#随机生成0-1之间的数字
if rdn < prob:#如果生成的随机数小于噪声比例则将该像素点添加黑点,即椒噪声
output[i][j] = 0
noise_out[i][j] = 0
elif rdn > thres:#如果生成的随机数大于(1-噪声比例)则将该像素点添加白点,即盐噪声
output[i][j] = 255
noise_out[i][j] = 255
else:
output[i][j] = image[i][j]#其他情况像素点不变
noise_out[i][j] = 100
cv2.imshow('random_noise', noise_out+output)
cv2.waitKey(0)