OpenCV——彩色图像添加高斯噪声

x33g5p2x  于2021-10-07 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(709)

一、高斯噪声

高斯分布,也称正态分布,又称常态分布,记为N ( μ , σ 2 ) N(μ,σ^2)N(μ,σ2) ,其中μ , σ 2 μ,σ^2μ,σ2为分布的参数,分别为高斯分布的期望和方差。当有确定值时,p ( x ) p(x)p(x)也就确定了,特别当μ = 0 μ=0μ=0,σ 2 = 1 σ^2=1σ2=1时,X XX的分布为标准正态分布。所谓高斯噪声是指它的概率密度函数服从高斯分布(即正态分布)的一类噪声。区别于椒盐噪声随机出现在图像的任意位置,高斯噪声出现在图像的所有位置。

二、C++代码

  1. #include <opencv2\opencv.hpp>
  2. #include <iostream>
  3. using namespace cv;
  4. using namespace std;
  5. int main()
  6. {
  7. Mat img = imread("qq.jpg");
  8. if (img.empty())
  9. {
  10. cout << "请确认图像文件名称是否正确" << endl;
  11. return -1;
  12. }
  13. //生成与原图像同尺寸、数据类型和通道数的矩阵
  14. Mat img_noise = Mat::zeros(img.rows, img.cols, img.type());
  15. imshow("lena原图", img);
  16. RNG rng; //创建一个RNG类
  17. rng.fill(img_noise, RNG::NORMAL, 10, 20); //生成三通道的高斯分布随机数(10,20)表示均值和标准差
  18. imshow("三通道高斯噪声", img_noise);
  19. img = img + img_noise; //在彩色图像中添加高斯噪声
  20. imwrite("gauss_noise.png", img);
  21. imshow("img添加噪声", img); //显示添加高斯噪声后的图像
  22. waitKey(0);
  23. return 0;
  24. }

三、python代码

  1. import numpy as np
  2. import cv2
  3. def gasuss_noise(image, mu=0.0, sigma=0.1):
  4. """ 添加高斯噪声 :param image: 输入的图像 :param mu: 均值 :param sigma: 标准差 :return: 含有高斯噪声的图像 """
  5. image = np.array(image / 255, dtype=float)
  6. noise = np.random.normal(mu, sigma, image.shape)
  7. gauss_noise = image + noise
  8. if gauss_noise.min() < 0:
  9. low_clip = -1.
  10. else:
  11. low_clip = 0.
  12. gauss_noise = np.clip(gauss_noise, low_clip, 1.0)
  13. gauss_noise = np.uint8(gauss_noise * 255)
  14. return gauss_noise
  15. if __name__ == '__main__':
  16. # ----------------------读取图片-----------------------------
  17. img = cv2.imread("qq.jpg")
  18. # --------------------添加高斯噪声---------------------------
  19. out2 = gasuss_noise(img, mu=0.0, sigma=0.1)
  20. # ----------------------显示结果-----------------------------
  21. cv2.imshow('origion_pic', img)
  22. cv2.imshow('gauss_noise', out2)
  23. cv2.waitKey(0)

四、结果展示

1、原始图像

2、添加高斯噪声

相关文章