知识点:
opencv内置随机数API
RNG rng(随机数种子)
在生成RNG实例后,一般会对其调用uniform函数,来返回某区间的随机数,如:
rng.uniform(0, 255)
应用:在画板上不断生成随机线条
代码
void QuickDemo::random_drawing_demo()
{
Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);
int w = canvas.cols;
int h = canvas.rows;
//用伪随机方法生成随机数,12345是随机数种子,可以把系统时间作为随机数种子实现真随机: RNG rng((unsigned)time(NULL))
RNG rng(12345);
while (true) {
int c = waitKey(1000);
if (c == 27) {
cout << "enter esc ,quit" << endl;
break;
}
//使用使用随机数和均匀分布返回随机数
int x1 = rng.uniform(0, w);
int y1 = rng.uniform(0, h);
int x2 = rng.uniform(0, w);
int y2 = rng.uniform(0, h);
int b = rng.uniform(0, 255), g = rng.uniform(0, 255), r = rng.uniform(0, 255);
line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 3, LINE_AA, 0);
imshow("随机绘制", canvas);
}
}
结果:
其中关于line函数的解释参见: