import cv2
import numpy as np
def add_peppersalt_noise(image,n=1000): #图像中噪声点的个数(n可修改)
result=image.copy()
w,h=image.shape[:2]#测量图片长和宽,2表示只取前两个数,image.shape返回三个参数
for i in range(n):
x=np.random.randint(1,w)
y=np.random.randint(1,h)
if np.random.randint(0,2) == 0:
result[x,y]=0
else:
result[x,y]=255
return result
image=cv2.imread('cai.png') #想要添加噪声点的图(引号内需修改)
noise = add_peppersalt_noise(image)
# noise =cv2.resize(noise,(800,700))
# cv2.imshow('yuan',image)
# cv2.waitKey(1000)
cv2.imshow('cai',noise)
cv2.imwrite('cai_zao.jpg',noise) #保存噪声点图,(引号内需修改)
cv2.waitKey(1000)