opencv 随机数生成器

生成随机数

《learning opencv》ex7-1 解决方案

opencv提供了RNG类,能够非常方便的处理随机数,有如下任务:

  1. 生成3个float类型的随机数,且服从均匀分布,每个随机数的范围是0.0-1.0
  2. 生成3个double类型的随机数,且服从均值为0,方差为1的高斯分布
  3. 生成3个unsigned byte类型的随机数,服从均匀分布,每个数的取值范围是0-255

针对以上问题,实现代码如下:

#include
#include
using namespace std;
using uint = unsigned;
/*
1. Generate and print three floating-point numbers,each drawn from a distribution from 0.0 to 1.0
2. Generate and print three double-preision numbers,each drown from a Guassian distribution centered at
    0.0 and with standard deviation of 1.0
3. Generate and print three unsigned bytes,each drawn from a uniform distibution from 0 to 255
*/


void generate_random_numbers()
{
    cv::RNG rng = cv::theRNG();
    float f_1 = rng.uniform(0.f, 1.f);
    float f_2 = rng.uniform(0.f, 1.f);
    float f_3 = rng.uniform(0.f, 1.f);


    double d_1 = rng.gaussian(1.0);
    double d_2 = rng.gaussian(1.0);
    double d_3 = rng.gaussian(1.0);

    uint u_1 = (uint)rng.uniform(0, 255);
    uint u_2 = (uint)rng.uniform(0, 255);
    uint u_3 = (uint)rng.uniform(0, 255);

    cout << "f_1: " << f_1 << " f_2: " << f_2 << " f_3: " << f_3 << endl;
    cout << "d_1: " << d_1 << " d_2: " << d_2 << " d_3: " << d_3 << endl;
    cout << "u_1: " << u_1 << " u_2: " << u_2 << " u_3: " << u_3 << endl;
    
}

生成随机数矩阵

《learining opencv》ex7-2 解决方案

RNG类,不仅可以方便快捷的生成随机数,而且也支持生成随机数矩阵,针对随机数填充的矩阵,有一下任务:

  1. 生成一个包含20个随机数的矩阵,每个随机数类型为float,且服从0.0-1.0的均匀分布;
  2. 生成一个包含20个随机数的矩阵,每个随机数类型为float,且服从均值为0,方差为1的高斯分布
  3. 生成一个包含20个随机数的矩阵,每个随机数类型为unsigned byte,且服从0-255的均匀分布;
  4. 生成20个三元组构成的随机数矩阵,每个随机数类型为unsigned byte,且服从0-255的均匀分布。

其代码如下所示:

#include
#include


/*
1. Using the fill method of the cv::RNG random number generator,create an array of:
    a. 20 floating-point numbers with uniform distribution from 0.0 to 1.0
    b. 20 floating-point numbers with guassian distribution centered at 0.0 and with a standard deviation of 1.0
    c. 20 unsigned bytes with a uniform distribution from 0 to 255
    d. 20 color triples,each of three bytes with a uniform distribution from 0 to 255 
*/
using namespace std;

void generate_random_matrix()
{
    cv::RNG rng = cv::theRNG();
    cv::Mat m_uniform = cv::Mat(20, 1, CV_32F, cv::Scalar(0));
    rng.fill(m_uniform, cv::RNG::UNIFORM,0.f,1.f);

    cv::Mat m_guassian = cv::Mat(20, 1, CV_32F, cv::Scalar(0));
    rng.fill(m_guassian, cv::RNG::NORMAL, 0.0, 1.0);
    //cout << m_guassian << endl;

    cv::Mat mu_uniform = cv::Mat(20, 1, CV_8UC1, cv::Scalar(0));
    rng.fill(mu_uniform, cv::RNG::UNIFORM, 0, 255);
    //cout << mu_uniform << endl;

    cv::Mat mt_uniform = cv::Mat(20, 1, CV_8UC3, cv::Scalar(0, 0, 0));
    rng.fill(mt_uniform, cv::RNG::UNIFORM, 0, 255);
    cout << mt_uniform << endl;


}

你可能感兴趣的:(opencv 随机数生成器)