0026-用OpenCV的RNG类为图像添加高斯噪声

在OpenCV中,可以用RNG类来产生均匀分布和正态分布(高斯分布)的随机数。RNG的英文全称是Random number generator,从名字上大家就可以看出这个类的用途。
我们可以用这个类的成员函数fill来为图像添加高斯噪声。RNG:fill的原型如下
C++: void RNG::fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false )
参数意义如下
mat:二维或多维矩阵,目前版本中,维数不能超过4。
distType:随机数的分布类型,有两种,即RNG::UNIFORM 或 RNG::NORMAL,前者表示均匀分布,后者表示正态分布(即高斯分布)。
a:分布规律参数之一。在均匀分布中表示下限(包含),在正态分布(即高斯分布)中,表示均值。
b:分布规律参数之一。在均匀分布中表示上限(包含),在正态分布(即高斯分布)中,表示标准差。
saturateRange:这个参数只对均匀分布时有用。具体是什么含义,笔者现在也没搞清楚,等搞清楚了再来通知大家吧。官方原文实在没有看懂,摘录如下(如果有朋友看懂了,记得告诉笔者一声哦,可以关注公众号"qxsf321"联系上作者)
saturateRange – pre-saturation flag; for uniform distribution only; if true, the method will first convert a and b to the acceptable value range (according to the mat datatype) and then will generate uniformly distributed random numbers within the range [saturate(a), saturate(b)), if saturateRange=false, the method will generate uniformly distributed random numbers in the original range [a, b) and then will saturate them, it means, for example, that theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely produce array mostly filled with 0’s and 255’s, since the range (0, 255) is significantly smaller than [-DBL_MAX, DBL_MAX).

用这个成员函数为图像添加高斯噪声的代码如下:

图像处理开发资料、图像处理开发需求、图像处理接私活挣零花钱,可以搜索公众号"qxsf321",并关注!
代码中用到的图像的下载链接为:http://pan.baidu.com/s/1c2ETzwc 密码:pvnz

//opencv版本:OpenCV3.0
//VS版本:VS2013
//Author:qxsf321.net

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>    
#include <opencv2/imgproc/types_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <time.h>  
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
        //源图像  
        Mat img_input = imread("zhi_zhi_hua.jpg");


        Mat img_output(img_input.size(), img_input.type());
        Mat noise(img_input.size(), img_input.type());  /**创建一个噪声矩阵*/
        RNG rng(time(NULL));
    rng.fill(noise, RNG::NORMAL, 10,  36);  /**高斯分布*/
    cv::add(img_input, noise, img_output);

        imshow("原图像", img_input);
        imshow("噪声图像", noise);
        imshow("加上高斯噪声后的图像", img_output);


        waitKey(0);
        return EXIT_SUCCESS;
}


运行结果如下图所示


 

猜你喜欢

转载自blog.csdn.net/lehuoziyuan/article/details/84102811