接上篇数据增强
代码6:高斯噪声、椒盐噪声
import cv2
import random
from numpy import *
def PepperandSalt(src,percetage):
NoiseImg=src
NoiseNum=int(percetage*src.shape[0]*src.shape[1])
for i in range(NoiseNum):
randX=random.random_integers(0,src.shape[0]-1)
randY=random.random_integers(0,src.shape[1]-1)
if random.random_integers(0,1)<=0.5:
NoiseImg[randX,randY]=0
else:
NoiseImg[randX,randY]=255
return NoiseImg
def GaussianNoise(src,means,sigma):
NoiseImg=src
rows=NoiseImg.shape[0]
cols=NoiseImg.shape[1]
for i in range(rows):
for j in range(cols):
NoiseImg[i,j]=NoiseImg[i,j]+random.gauss(means,sigma)
if NoiseImg[i,j]< 0:
NoiseImg[i,j]=0
elif NoiseImg[i,j]>255:
NoiseImg[i,j]=255
return NoiseImg
img=cv2.imread('img/a.jpg',0)
img1=PepperandSalt(img,0.2)
cv2.imwrite('img2/a2.jpg',img1)
cv2.imshow('PepperandSalt',img1)
cv2.waitKey(0)
关于噪声的具体像素计算过程如下:
#1、生成高斯噪声
fn = "img/a.jpg"
if __name__ == '__main__':
img = cv2.imread(fn)
coutn = 10000
for k in range(0,coutn):
#get the random point
xi = int(np.random.uniform(0,img.shape[1]))
xj = int(np.random.uniform(0,img.shape[0]))
#add noise
if img.ndim == 2:
img[xj,xi] = 255
elif img.ndim == 3:
img[xj,xi,0] = 25
img[xj,xi,1] = 20
img[xj,xi,2] = 20
cv2.namedWindow('img')
cv2.imshow('img',img)
cv2.waitKey()
cv2.destroyAllWindows()
#2、椒盐噪声
filename = "img/a.jpg"
winname = "figure"
img = cv2.imread(filename)
def addSaltNoise():
# 指定信噪比
SNR = 0.99
# 获取总共像素个数
size = img.size
# 因为信噪比是 SNR ,所以噪声占据百分之10,所以需要对这百分之10加噪声
noiseSize = int(size * (1 - SNR))
# 对这些点加噪声
for k in range(0, noiseSize):
# 随机获取 某个点
xi = int(np.random.uniform(0, img.shape[1]))
xj = int(np.random.uniform(0, img.shape[0]))
# 增加噪声
if img.ndim == 2:
img[xj, xi] = 255
elif img.ndim == 3:
img[xj, xi] = 0
cv2.imshow(winname, img)
# cv2.waitKey(0)
cv2.imwrite('img2/a1.jpg',img)
def main():
addSaltNoise()
if __name__ == '__main__':
main()
3、随机椒盐
img=cv2.imread('img/a.jpg')
height,weight,channel = img.shape
#随机生成5000个椒盐噪声
for i in range(5000):
x = np.random.randint(0,height)
y = np.random.randint(0,weight)
img[x ,y ,:] = 255
cv2.imshow("123.jpg",img)
cv2.waitKey(0)