添加椒盐噪声/高斯噪声实验
使用opencv+python
一、实验思路
椒盐噪声(脉冲噪声),在一幅图像里随机的将一个像素点变成椒盐噪声,其中椒噪声像素值是0,盐噪声是255。 生成(添加)椒盐噪声算法步骤如下: (1)输入一幅图像并自定义信噪比 SNR (其取值范围在[0, 1]之间); (2)计算图像像素点个数 SP, 进而得到椒盐噪声的像素点数目 NP = SP * (1-SNR); (3)随机获取要加噪的每个像素位置img[i, j]; (4)随机生成[0,1]之间的一个浮点数; (5)判定浮点数是否大于0.5,并指定像素值为255或者0; (6)重复3,4,5三个步骤完成所有像素的NP个像素加粗样式; (7)输出加噪以后的图像。 高斯噪声,指的是他的概率密度函数服从高斯分布(正态分布)的一类噪声,计算过程与椒盐噪声类似。
二、实验代码
import cv2 as cv
import numpy as np
# 将rgb颜色通道的图像转为灰色
def rgb2gray(img):
h=img.shape[0]
w=img.shape[1]
img1=np.zeros((h,w),np.uint8)
for i in range(h):
for j in range(w):
# 变成灰色的公式
img1[i,j]=0.144*img[i,j,0]+0.587*img[i,j,1]+0.299*img[i,j,2]
return img1
# 添加噪声
def sp_noise(img,snr):
h=img.shape[0]
w=img.shape[1]
img1=img.copy()
sp=h*w # 计算图像像素点个数
NP=int(sp*(1-snr)) # 计算图像椒盐噪声点个数
for i in range (NP):
randx=np.random.randint(1,h-1) # 生成一个 1 至 h-1 之间的随机整数
randy=np.random.randint(1,w-1) # 生成一个 1 至 w-1 之间的随机整数
if np.random.random()<=0.5: # np.random.random()生成一个 0 至 1 之间的浮点数
img1[randx,randy]=0
else:
img1[randx,randy]=255
return img1
# 添加高斯噪声
def gasuss_noise(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)
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)
#cv.imshow("gasuss", out)
return out
image=cv.imread("test.jpeg")
grayimage=rgb2gray(image)
sp_noiseimage=sp_noise(grayimage,0.98) # 将信噪比设定为0.98
# cv2.GaussianBlur(grayimage, ksize=(9, 9), sigmaX=0, sigmaY=0) 这段代码也是可以添加高斯噪声的,更方便,但是不符合实验的初衷
gasuss_noiseimage=gasuss_noise(grayimage,0,0.02) # 将信噪比设定为0.98,就是将噪声的比例设置为0.02
cv.imshow("image",image)
cv.imshow("grayimage",grayimage)
cv.imshow("sp_noiseimage",sp_noiseimage)
cv.imshow("gasuss_noiseimage",gasuss_noiseimage)
cv.imwrite('grayimage.jpg',grayimage)
cv.imwrite('sp_noiseimage.jpg',sp_noiseimage)
cv.imwrite('gasuss_noiseimage.jpg',gasuss_noiseimage)
cv.waitKey(0)
cv.destroyAllWindows()
三、实验结果
参考资料
[1] ~沐春风~ Python+OpenCV添加椒盐噪声 链接:https://blog.csdn.net/Skymelu/article/details/89218558 [2] 我坚信阳关灿烂 给图像添加椒盐噪声和高斯噪声 python实现 连接:https://www.cnblogs.com/wojianxin/p/12499928.html