1. 程式人生 > >OpenCV 隨機數生成器 RNG

OpenCV 隨機數生成器 RNG

OpenCV 中有自己的隨機數生成類 RNG,先來看看 OpenCV 文件的介紹:

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.

建構函式

RNG::RNG()
RNG::RNG(uint64 state)

RNG 類有以上兩個建構函式,第二個建構函式傳入一個 uint64 型別的種子,若使用第一個建構函式則會使用預設的種子,一般使用系統時間來指定種子,這樣可以使得程式每次執行生成的隨機數不同。

RNG::next

unsigned int RNG::next()

返回下一個隨機數。

RNG::operator T

RNG::operator uchar()
RNG::operator schar()
RNG::operator ushort()
RNG::operator short int()
RNG::operator int()
RNG::operator unsigned int()
RNG::operator float()
RNG::operator double()

過載了型別轉換的操作符,返回指定型別的下一個隨機數。
轉換為整數型別,返回的是可取值範圍的隨機數;轉換為浮點型別,返回的是 [0,1) 之間的浮點數。

示例:

int main()
{
    RNG rng(100);
    cout << int(rng) << endl;
    cout << int(rng) << endl;
    cout << double(rng) << endl;
    system("pause");
    return 0;
}

RNG::operator ()

unsigned int RNG::operator()()
unsigned int RNG::operator()(unsigned int N)

過載了 (), 還是返回下一個隨機數… 第一個等價於 RNG::next(),第二個生成的隨機數對 N 取模,相當於生成 [0,N) 的隨機數。

RNG::uniform

int RNG::uniform(int a, int b)
float RNG::uniform(float a, float b)
double RNG::uniform(double a, double b)

這應該是我們最常用的函數了。
從 [a,b) 中返回下一個服從均勻分佈的隨機數。返回的型別由引數型別推斷得出,官方文件有個例子:

RNG rng;

// always produces 0
double a = rng.uniform(0, 1);

// produces double from [0, 1)
double a1 = rng.uniform((double)0, (double)1);

// produces float from [0, 1)
double b = rng.uniform(0.f, 1.f);

// produces double from [0, 1)
double c = rng.uniform(0., 1.);

// may cause compiler error because of ambiguity:
//  RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
double d = rng.uniform(0, 0.999999);

RNG::gaussian

double RNG::gaussian(double sigma)

返回下一個服從高斯分佈的隨機數。
傳人一個 double 型別的 sigma,生成的隨機數服從均值為 0,標準差為 sigma 的高斯分佈。

RNG::fill

void RNG::fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false )

用隨機數填充陣列。

  • 第一個引數,輸出的陣列或者矩陣,不支援超過 4 通道的矩陣。
  • 第二個引數,分佈型別,RNG::UNIFORM or RNG::NORMAL 。
  • 第三四個引數,如果第二個引數為 RNG::UNIFORM 那麼 a,b 就是上下限;如果第二個引數是 RNG::NORMAL,那麼 a,b 就是均值與標準差。
  • 第五個引數只對 RNG::UNIFORM 情況下有用,設定為 true 可以防止溢位。

其他有個隨機數的函式

template<typename _Tp> _Tp randu()
void randu(InputOutputArray dst, InputArray low, InputArray high)

生成一個指定型別的均勻分佈的陣列,範圍 [low,high)。

void randn(InputOutputArray dst, InputArray mean, InputArray stddev)

生成一個服從正太分佈的陣列。

void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng=0 )

隨機打亂陣列元素。
只支援1維陣列,iterFactor表示打亂的比例因子,預設全部打亂。第三個引數用於載入種子。