图形的绘制与填充:
//图形的绘制与填充
Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);
namedWindow("canvas", WINDOW_AUTOSIZE);
//相关绘制API演示
//绘制直线
line(canvas, Point(10, 10), Point(400, 400), Scalar(255, 0, 0), 1, LINE_8);
//绘制矩形
Rect rect(150, 150, 250, 250);
rectangle(canvas, rect, Scalar(0, 255, 0), 1, 8);
//绘制圆
circle(canvas, Point(256, 256), 100, Scalar(0, 255, 255), -1, 8);
//线粗为-1时自动填充颜色,大于0时就是普通的线粗
RotatedRect rrt;
rrt.center = Point2f(256, 256);
rrt.angle = 90.0;
rrt.size = Size(100, 200);
//绘制椭圆
ellipse(canvas, rrt, Scalar(0, 255, 0), -1, LINE_8);
imshow("canvas", canvas);
运行结果:
RNG随机函数的使用:
Mat image = Mat::zeros(Size(512, 512), CV_8UC3);
namedWindow("image", WINDOW_AUTOSIZE);
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 0;
RNG rng(123456);
while (1) {
x1 = (int)rng.uniform(0, 512); //设置随机值的范围
x2 = (int)rng.uniform(0, 512);
y1 = (int)rng.uniform(0, 512);
y2 = (int)rng.uniform(0, 512);
int w = abs(x2 - x1);
int h = abs(y2 - y1);
Rect rect;
rect.x = x1;
rect.y = y1;
rect.width = w;
rect.height = h;
//在画布上随机绘制多个矩形
/*rectangle(image, rect, Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256)), 1, 8);*/
//在画布上随机绘制单个矩形
image = Scalar(0, 0, 0);
rectangle(image, Point(x1, y1), Point(x2, y2), Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256)), 1, 8);
imshow("image", image);
char c = waitKey(10);
if (c == 27) { //按Esc退出
break;
}
}
绘制多个矩形运行结果图: