1. 添加高斯噪声
import cv2
import numpy as np
def imnoise_gasussian(image, mean=0, var=0.001):
''' 添加高斯噪声
mean : 均值
var : 方差
'''
image = np.array(image/255, dtype=float)
noise = np.random.normal(mean, var ** 0.5, image.shape)
img_noise = image + noise
img_noise = np.clip(img_noise, 0, 1.0)
img_noise = np.uint8(img_noise*255)
return img_noise
if __name__ == '__main__':
img_file = './monarch.png'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)
img_noise = imnoise_gasussian(img, 0, 0.01)
cv2.imshow('noise', img_noise)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 添加椒盐噪声
import cv2
import numpy as np
import random
def imnoise_sp(image, prob):
''' 添加椒盐噪声
prob:噪声比例
'''
img_noise = np.copy(image)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
img_noise[i][j] = 0
elif rdn > thres:
img_noise[i][j] = 255
return img_noise
if __name__ == '__main__':
img_file = './monarch.png'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)
img_noise = imnoise_sp(img, 0.01)
cv2.imshow('noise', img_noise)
cv2.waitKey(0)
cv2.destroyAllWindows()