以下是几个绘制图形的api,细节不多说。值得注意的是指定线宽时候-1代表填充。
#include
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat canvas = Mat::zeros(Size(512,512),CV_8UC3);
//绘制
//1. 线
line(canvas, Point(10, 10), Point(400, 400), Scalar(0, 0, 255), 2, LINE_8);
//2. 矩形
Rect rect(100, 100, 200, 200);
rectangle(canvas, rect,Scalar(255,0,0),2,8);
//3. 圆
circle(canvas, Point(256,256),100,Scalar(0,255,0),1,8);
//4. 椭圆
RotatedRect rrt;
rrt.center = Point2f(256,256);
rrt.angle = 45; //旋转45°
rrt.size = Size(100,200);
ellipse(canvas, rrt, Scalar(0, 100, 100), -1, 8);
imshow("canvas", canvas);
waitKey(0);
destroyAllWindows();
return 0;
}
以下代码是在画布上随机画线段,这个看一下代码就懂。需要注意的是:指定退出键为esc,waitKey返回值为27代表按下的是esc,其他值可以看一下api中介绍,这里不详细说。
Mat image = Mat::zeros(Size(512, 512), CV_8UC3);
//rgn 种子初始化
RNG rng(12345);
//坐标
int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
//颜色
Scalar color = (0, 0, 0);
while (1){
x1 = (int)rng.uniform(0, 512);
y1 = (int)rng.uniform(0, 512);
x2 = (int)rng.uniform(0, 512);
y2 = (int)rng.uniform(0, 512);
color = Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
line(image, Point(x1, y1), Point(x2, y2), color, 1, 8);
imshow("image", image);
char c = waitKey(10);
if (c == 27)
{
break;
}
}