附代码如下:
import cv2 as cv import numpy as np def noise(): src = cv.imread("D:/matplotlib/0.jpg") cv.imshow("input", src) h,w = src.shape[:2] rows = np.random.randint(0,h,(5000),dtype=np.int) cols = np.random.randint(0, w, (5000), dtype=np.int) for i in range(5000): if i % 2 == 1: src[rows[i],cols[i]] = (255,255,255) else: src[rows[i], cols[i]] = (0, 0, 0) cv.imshow("noise",src) cv.waitKey(0) cv.destroyAllWindows() noise()
运行结果:
代码解释:
import cv2 as cv import numpy as np def noise(): src = cv.imread("D:/matplotlib/0.jpg") cv.imshow("input", src) h,w = src.shape[:2] #获取图像属性 rows = np.random.randint(0,h,(5000),dtype=np.int) #随机产生5000个噪声点 cols = np.random.randint(0, w, (5000), dtype=np.int) for i in range(5000): if i % 2 == 1: src[rows[i],cols[i]] = (255,255,255) #当为奇数的时候给白色的噪声点 else: src[rows[i], cols[i]] = (0, 0, 0) cv.imshow("noise",src) cv.waitKey(0) cv.destroyAllWindows() noise()