程序及分析
RNG是OpenCV中的随机数生成类,其定义在core.hpp中,
class CV_EXPORTS RNG { public: enum { UNIFORM=0, NORMAL=1 }; RNG(); RNG(uint64 _state); //! updates the state and returns the next 32-bit unsigned integer random number unsigned next(); operator uchar(); operator schar(); operator ushort(); operator short(); operator unsigned(); //! returns a random integer sampled uniformly from [0, N). unsigned operator()(unsigned N); unsigned operator ()(); operator int(); operator float(); operator double(); //! returns uniformly distributed integer random number from [a,b) range int uniform(int a, int b); //! returns uniformly distributed floating-point random number from [a,b) range float uniform(float a, float b); //! returns uniformly distributed double-precision floating-point random number from [a,b) range double uniform(double a, double b); void fill( InputOutputArray mat, int distType, InputArray a, InputArray b ); //! returns Gaussian random variate with mean zero. double gaussian(double sigma); uint64 state; };
提供了两种随机数——均匀分布(uniform)和高斯正态分布(gaussian)。
本文使用的是随机分布,两个參数分布表示均匀分布的下限和上限。
RNG rng(0xFFFFFFFF);
中的0xFFFFFFFF表示初始的随机值。Mat矩阵初始化:
Mat image = Mat::zeros(height, width, CV_8UC3);
line用于绘制直线,也定义在core.hpp中,
//! draws the line segment (pt1, pt2) in the image CV_EXPORTS_W void line(Mat& img, Point pt1, Point pt2, const Scalar& color,int thickness=1, int lineType=8, int shift=0);
还有其他画图函数circle、ellipse、rectangle等也也能够从core.hpp中找到原型。可用到时自行学习。
putText能够将文字加入到图片中。
//! renders text string in the image CV_EXPORTS_W void putText( Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int linetype=8, bool bottomLeftOrigin=false );
其第一个參数img就是要加入文字的图像,第二个參数就是要加入的文字(程序中是"OpenCV")
关于颜色:颜色是用RGB三通道表示的,因此上面函数中颜色參数的类型都是Scalar类型。Scalar在OpenCV中相似于向量,但其长度最大为4通道。源程序中
Scalar(icolor&0xFF, (icolor>>8)&0xFF, (icolor>>16)&0xFF);
将随机数的值取出分别作为RGB三个通道的颜色值。
效果
随机线条的效果
加入“OpenCV”文字后效果