首首先我们先来看下python中shape()函数的用法
from numpy import *
a=array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
a.shape[0]
得到a的行数为 4
然后输入a.shape[1]
得到a的列数为 3
图1:运行在python的IDLE中示例
通过程序我们可以看到shape[0]表示的为行数,shape[1]表示的为列数
然后我们看下range()函数的用法
我们首先看下help('range')给我们的解释
意思是:返回一个从0开始的对象的整数序列,
进入正题:
我们先定义高斯噪声函数:GaussianNoise(src,means,sigma)
通过使用函数random.gauss(means,sigma)生成均值为means,标准差为sigma的高斯白噪声
高斯噪声的代码如下:
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
椒盐噪声的函数定义如下:
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
椒盐噪声总体代码如下:
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('C:/Users/Administrator/Desktop/12.jpg',0)
img1=PepperandSalt(img,0.2)
cv2.imwrite('C:/Users/Administrator/Desktop/3.jpg',img1)
cv2.imshow('PepperandSalt',img1)
cv2.waitKey(0)
加入椒盐噪声之后的运行结果如下:
图2:加入椒盐噪声的运行结果
高斯噪声的代码为:
import cv2
from numpy import shape
import random
def PepperandSalt(src,percetage):
NoiseImg=src
NoiseNum=int(percetage*src.shape[0]*src.shape[1])
for i in range(NoiseNum):
randX=random.randint(0,src.shape[0]-1)
randY=random.randint(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,percetage):
NoiseImg=src
NoiseNum=int(percetage*src.shape[0]*src.shape[1])
for i in range(NoiseNum):
randX=random.randint(0,src.shape[0]-1)
randY=random.randint(0,src.shape[1]-1)
NoiseImg[randX, randY]=NoiseImg[randX,randY]+random.gauss(means,sigma)
if NoiseImg[randX, randY]< 0:
NoiseImg[randX, randY]=0
elif NoiseImg[randX, randY]>255:
NoiseImg[randX, randY]=255
return NoiseImg
img=cv2.imread('C:/Users/Administrator/Desktop/12.jpg',0)
img1=GaussianNoise(img,2,4,0.8)
cv2.imwrite('C:/Users/Administrator/Desktop/3.jpg',img1)
cv2.imshow('PepperandSalt',img1)
cv2.waitKey(0)
加入高斯噪声的运行结果为: