今天爱分享给大家带来椒盐噪声图片 python opencv实现[附代码],希望能够帮助到大家。
方法
import random import cv2 import numpy as np ''' 添加椒盐噪声 :param img: 原始图片 :param prob: 噪声比例 :return: resultImg ''' def noiseSP(img, prob): resultImg = np.zeros(img.shape, np.uint8) thres = 1 - prob for i in range(img.shape[0]): for j in range(img.shape[1]): rdn = random.random() if rdn < prob: resultImg[i][j] = 0 elif rdn > thres: resultImg[i][j] = 255 else: resultImg[i][j] = img[i][j] return resultImg img = cv2.imread('test.jpg') resultImg = noiseSP(img, 0.05, 2) cv2.imwrite('result.jpg',resultImg)
效果