Contents
  1. I. How to Use Random Numbers
  2. II. Example Program for Generating Random Lines

I. How to Use Random Numbers

  C and C++ provide the rand() and srand() functions for generating random numbers, and they can also be used when writing OpenCV code in C++. OpenCV itself also provides the RNG class for generating random numbers, which is very convenient to use. The following section mainly explains how to use the RNG class.

//RNG类对象的创建
 RNG rng(int seed);	//使用种子seed产生一个RNG类对象

//产生一个在区间[a,b)的均匀分布的整数随机数
int x = rng.uniform(a, b);
//产生一个在区间[0,1)的均匀分布的浮点随机数
int x = rng.uniform(0.f,1.f);
//产生一个均值为0,标准差为2的高斯分布的随机数
int x = rng.gaussian(2);

II. Example Program for Generating Random Lines

void MyDemo::random_Demo() {
	Mat bg = Mat::zeros(Size(512, 512), CV_8UC3);	//创建背景
	int width = bg.cols;
	int height = bg.rows;
	RNG rng(666);	//种子随意设置
	while (true) {
		//等待按键按下,同时限制两线条生成间隔实现
		char k = waitKey(100);
		if(k == 'q')
		{
			break;
		}
		int x1 = rng.uniform(0, width);
		int y1 = rng.uniform(0, height);
		int x2 = rng.uniform(0, width);
		int y2 = rng.uniform(0, height);
		int b = rng.uniform(0, 255);
		int g = rng.uniform(0, 255);
		int r = rng.uniform(0, 255);

		line(bg, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);
		imshow("Randow image", bg);
	}
}

II. Example Program for Generating Random Lines