0026-用OpenCV的RNG類為影象新增高斯噪聲
阿新 • • 發佈:2018-11-16
在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
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; }
執行結果如下圖所示: