- import numpy as np
- import cv2
- import matplotlib.pyplot as plt
- import skimage
- from skimage import io
- import random
-
- def addGaussNoise(origin,var=0.0005):#添加高斯噪声函数
- var = random.uniform(0.0001, 0.04)
- noisy = skimage.util.random_noise(origin, mode='gaussian', var=var)
- return noisy
-
- def addSaltNoise(origin,var=0.01):#添加椒盐噪声函数
- var = random.uniform(0.01, 0.2)
- noisy = skimage.util.random_noise(origin, mode='s&p', amount=var)
- return noisy
-
- def addSpeckleNoise(origin,var=0.001):#添加乘法噪声函数
- var = random.uniform(0.0001, 0.04)
- noisy = skimage.util.random_noise(origin, mode='speckle', var=var)
- return noisy
- # img = cv2.imread('img1.png',cv2.IMREAD_GRAYSCALE)
- # img = plt.imread('img1.png')
- img=io.imread('img1.png')
- fig=plt.figure(figsize=(10, 50))
- img = addGaussNoise(img)
- img1 = addSaltNoise(img)
- img2 = addSpeckleNoise(img)
-
- plt.subplot(2,2,1),plt.imshow(img,'gray'),plt.title('original')
- plt.subplot(2,2,2),plt.imshow(img,'gray'),plt.title('img_add_gaussin')
- plt.subplot(2,2,3),plt.imshow(img1,'gray'),plt.title('SaltNoise')
- plt.subplot(2,2,4),plt.imshow(img2,'gray'),plt.title('SpeckleNoise')
- plt.show()
- import numpy as np
- import random
- import cv2
-
- def sp_noise(image,prob):
- '''
- 添加椒盐噪声
- 盐粒噪声salt : 是指灰度值突变成白色点的噪声(白色--->255)
- 胡椒噪声pepper:是指灰度值突变成黑色点的噪声(黑色--->0)
- prob:盐粒噪声
- prob:胡椒噪声
- '''
- output = np.zeros(image.shape,np.uint8)
- thres = 1 - prob
- for i in range(image.shape[0]):
- for j in range(image.shape[1]):
- #生成随机数
- rdn = random.random()
- if rdn < prob:
- output[i][j] = 0
- elif rdn > thres:
- output[i][j] = 255
- else:
- output[i][j] = image[i][j]
- return output
-
-
- def gasuss_noise(image, mean=0, var=0.01):
- '''
- 添加高斯噪声
- mean : 均值
- var : 方差
- '''
- image = np.array(image/255, dtype=float)
- ##生成均值,方差的类似Image矩阵
- noise = np.random.normal(mean, var ** 0.5, image.shape)
- out = image + noise
- if out.min() < 0:
- low_clip = -1.
- else:
- low_clip = 0.
- out = np.clip(out, low_clip, 1.0)
- out = np.uint8(out*255)
- return out
- img=cv2.imread('img1.png')
- out1=sp_noise(img,0.05)
- out2=gasuss_noise(img)
- cv2.imshow('img',np.hstack((img,out1,out2)))
- cv2.imwrite('image.png',np.hstack((img,out1,out2)))
- cv2.waitKey()