RNG类:
Random number generator
Random number generator. It encapsulates the state (currently, a 64-bit
integer) and has methods to return scalar random values and to fill
arrays with random values. Currently it supports uniform and Gaussian
(normal) distributions. The generator uses Multiply-With-Carry
algorithm, introduced by G. Marsaglia (
<http://en.wikipedia.org/wiki/Multiply-with-carry> ).
Gaussian-distribution random numbers are generated using the Ziggurat
algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ),
introduced by G. Marsaglia and W. W. Tsang.
*/
class CV_EXPORTS RNG
{
public:
enum { UNIFORM = 0,
NORMAL = 1
};
随机类RNG:计算机的伪随机数是由随机种子根据一定的计算方法计算出来的数值,所以只要计算方法一定,随机种子一定,那么产生的随机数就是固定的。
RNG rng(12345)
opencv 里RNG类构造函数初始化为固定值后,随机种子也是固定的,所以在相同的平台环境下,编译后每次运行它,显示的随机数是一样的。
其中12345就是随机种子;
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
RNG rng(12345);
for (int i = 0; i < 10; i++)
{
cout << rng.uniform(0, 100) << endl;
}
system("pause");
return 0;
}
其结果如下:
34
63
83
31
9
14
12
15
72
99
请按任意键继续. . .
用RNG产生的是伪随机数,产生的随机数和随机种子的取值有关,当随机种子的值一定时,产生的随机数是一样的。通常利用时间作为随机种子,这样产生的种子跟具有随机性;
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
RNG rng((unsigned)time(NULL));
for (int i = 0; i < 10; i++)
{
cout << rng.uniform(0, 100) << endl;
}
system("pause");
return 0;
}
成员函数
RNG类有多个成员函数:
fill()
Fills arrays with random numbers.用随机数填充数组
void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
/*Fills arrays with random numbers.用随机数填充数组*/
uniform()
returns uniformly distributed integer random number from [a,b) range,返回[a,b)范围内的均匀分布的整数随机数
/*returns uniformly distributed integer random number from [a,b) range,返回[a,b)范围内的均匀分布的整数随机数*/
int uniform(int a, int b);
/** @overload */
float uniform(float a, float b);
/** @overload */
double uniform(double a, double b);
gaussian()
Returns the next random number sampled from the Gaussian distribution,返回从高斯分布采样的下一个随机数
/* Returns the next random number sampled from the Gaussian distribution,返回从高斯分布采样的下一个随机数*/
double gaussian(double sigma);