import numpy as np
import cv2
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def add_sp_noise(img,sp_number):
new_image=img
row,col,channel=img.shape#获取行列,通道信息
s=int(sp_number*img.size/channel)#根据sp_number确定椒盐噪声
#确定要扫椒盐的像素值
change=np.concatenate((np.random.randint(0,row,size=(s,1)),np.random.randint(0,col,size=(s,1))),axis=1)
for i in range(s):
r=np.random.randint(0,2)#确定撒椒(0)还是盐(1)
for j in range(channel):
new_image[change[i,0],change[i,1],j]=r
return new_image
def salt_pepper_noise(image, prob):
"""
添加椒盐噪声
:param image: 输入图像
:param prob: 噪声比
:return: 带有椒盐噪声的图像
"""
salt = np.zeros(image.shape, np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = np.random.rand()
if rdn < prob:
salt[i][j] = 0
elif rdn > thres:
salt[i][j] = 255
else:
salt[i][j] = image[i][j]
return salt