本系列代码托管于:https://github.com/chintsan-code/opencv4-tutorials

本篇使用的项目为:drawing

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, const char** argv) {
	Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);
	Rect rect;
	rect.x = 200;
	rect.y = 200;
	rect.width = 150;
	rect.height = 200;
	rectangle(canvas, rect, Scalar(0, 0, 255), 2, LINE_8);
	circle(canvas, Point(100, 100), 50, Scalar(255, 0, 0), -1, LINE_8);
	line(canvas, Point(0, 0), Point(350, 400), Scalar(0, 255, 0), 1, LINE_AA);
	RotatedRect rrt;
	rrt.center = Point(300, 300);
	rrt.size = Size(100, 50);
	rrt.angle = 45.0;
	ellipse(canvas, rrt, Scalar(255, 255, 0), 2, LINE_8);
	// 获取旋转矩形的四个顶点
	cv::Point2f* vertices = new cv::Point2f[4];
	rrt.points(vertices);
	// 绘制旋转矩形rrt
	for (size_t i = 0; i < 4; i++)
	{
		cv::line(canvas, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0),2,LINE_AA);
	}
	putText(canvas, "hello, opencv", Point(100, 100), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 255, 0));
	imshow("img", canvas);

	waitKey(0);
	destroyAllWindows();
	return 0;
}

line:绘制直线

void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0);
  • img:绘制背景,在image上绘制
  • pt1:要绘制直线的起始位置坐标
  • pt2:要绘制直线的终止位置坐标
  • color:颜色
  • thickness:线宽
  • lineType:绘制时的渲染方式
    • LINE_4
    • LINE_8
    • LINE_AA:反锯齿。会更加平滑
  • shift:一般为0

rectangle:绘制矩形

void rectangle(InputOutputArray img, Rect rec, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0);
  • rec:要绘制的矩形,也可以用对角坐标pt1,pt2
  • thickness:线宽,当为-1时代表填充矩形

circle:绘制圆形

void circle(InputOutputArray img, Point center, int radius, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0);
  • center:圆心坐标
  • radius:半径

ellipse:绘制椭圆

void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, int thickness = 1, int lineType = LINE_8);
  • box:椭圆对应的旋转矩形
    • Point2f center:矩形中心(质心)
    • float angle:旋转角度
    • Size2f size:矩形大小

putText:绘制文本

void putText( InputOutputArray img, const String& text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false );
  • text:要绘制的文本
  • org:绘制位置(文本左下角坐标)
  • fontFace:字体
  • fontScale:字体大小
  • bottomLeftOrigin:一般为false,设置垂直镜像时可用

绘制旋转矩形RotatedRect:

// 获取旋转矩形的四个顶点
cv::Point2f* vertices = new cv::Point2f[4];
rrt.points(vertices);
// 绘制旋转矩形rrt
for (size_t i = 0; i < 4; i++)
{
	cv::line(canvas, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0),2,LINE_AA);
}