RNG
Generating random numbers is an operation often used in programming, especially when initializing some random values need to be assigned. The methods of generating random numbers in C and C++, such as rand(), srand(), etc., can still be used in OpenCV.
In addition, OpenCV also specially compiled C++'s random number class RNG, C's random number class CvRNG, and some related functions, which are more convenient to use.
Description
- The words with cv before the keywords are written in C, and the ones without cv are written in C++. For example, CvRNG and RNG are the same in essence.
- The random numbers generated by the computer are pseudo-random numbers, which are calculated according to the seed and a specific algorithm. Therefore, as long as the seed is certain, the algorithm is certain, and the random numbers generated are the same
- If you want to generate completely repeated random numbers, you can use system time as a seed. Use GetTickCount() in OpenCV and time() in C
API
RNG can generate 3 kinds of random numbers
RNG(int seed) //使用种子seed产生一个64位随机整数,默认-1
RNG::uniform( ) // 产生一个均匀分布的随机数
RNG::gaussian( ) // 产生一个高斯分布的随机数
Code
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
Mat src1 = imread("C:/Users/86176/Desktop/pics/lena(1).tiff");
void randonLine() {
RNG rng(12345);
Point pt1;
Point pt2;
Mat dst = Mat::zeros(src1.size(), src1.type());//一个和源图一样大小的全黑图
namedWindow("output randon Line", CV_WINDOW_AUTOSIZE);
for (int i = 0; i < 100000; i++)//一直画
{
pt1.x = rng.uniform(0, src1.cols);
pt1.y = rng.uniform(0, src1.rows);
pt2.x = rng.uniform(0, src1.cols);
pt2.y = rng.uniform(0, src1.rows);//两个点随机生成
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//颜色随机生成
if (waitKey(50) > 0)
{
break;
}
line(dst, pt1, pt2, color, 1, LINE_8);
imshow("output randon Line", dst);
}
}
void main()
{
if (!src1.data)
{
printf("could not load image...\n");
return;
}
imshow("【input picture】", src1);
randonLine();
waitKey(0);
}
effect
opencv draws lines randomly