欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

opencv学习记录08:绘制形状和文字(直线/椭圆/圆/矩形/多边形/显示字母(putText显示中文乱码解决办法))

程序员文章站 2022-03-31 19:52:40
...

写论文无暇记录。。。。
本博客主要是几个画出形状和文字的API以及关于解决putText显示中文乱码感觉opencv处理图像还是看需求来处理,然后准备整理出常用的图像处理的API。

1、绘制直线

函数:line(两点连成一条直线)

void MyLines() {
	Point p1 = Point(20, 30);
	Point p2;
	p2.x = 400;
	p2.y = 400;
	Scalar color = Scalar(0, 0, 255);
	line(bgImage, p1, p2, color, 1, LINE_AA);
}

2、绘制圆形

函数:circle(确定圆心和半径)

void MyCircle() {
	Scalar color = Scalar(0, 255, 255);
	Point center = Point(bgImage.cols / 2, bgImage.rows / 2);
	circle(bgImage, center, 150, color, 2, 8);
}

3、绘制椭圆

函数:ellipse(确定椭圆心和长轴短轴)

void MyEllipse() {
	Scalar color = Scalar(0, 255, 0);
	ellipse(bgImage, Point(bgImage.cols / 2, bgImage.rows / 2), Size(bgImage.cols / 4, bgImage.rows / 8), 90, 0, 360, color, 2, LINE_8);
}

4、绘制矩形

函数:rectangle(确定第一个点和长宽)

void MyRectangle() {
	Rect rect = Rect(200, 100, 300, 300);
	Scalar color = Scalar(255, 0, 0);
	rectangle(bgImage, rect, color, 2, LINE_8);
}

5、绘制多边形

函数:fillPoly

void MyPolygon() {
	Point pts[1][5];  //一个多边形  
	pts[0][0] = Point(100, 100);
	pts[0][1] = Point(100, 200);
	pts[0][2] = Point(200, 200);
	pts[0][3] = Point(200, 100);
	pts[0][4] = Point(100, 100);

	const Point* ppts[] = { pts[0] };//定义Point指针,存放点
	int npt[] = { 5 };
	Scalar color = Scalar(255, 12, 255);
	fillPoly(bgImage, ppts, npt, 1, color, 8);
}

6、显示字母标题(putText)

putText(bgImage, "Hello OpenCV", Point(300, 300), CV_FONT_HERSHEY_COMPLEX, 1.0, Scalar(12, 23, 200), 3, 8);

采用putText这种方法显示中文字符的时候会乱码,想要显示中文字符采用freetype库
参考博客:https://blog.csdn.net/qq_33485434/article/details/81512943.

7、随机画直n条直线

void RandomLineDemo() {
	RNG rng(12345);
	Point pt1;
	Point pt2;
	Mat bg = Mat::zeros(bgImage.size(), bgImage.type());
	namedWindow("random line demo", CV_WINDOW_AUTOSIZE);
	for (int i = 0; i < 100000; i++) {
		pt1.x = rng.uniform(0, bgImage.cols);
		pt2.x = rng.uniform(0, bgImage.cols);
		pt1.y = rng.uniform(0, bgImage.rows);
		pt2.y = rng.uniform(0, bgImage.rows);
		Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
		if (waitKey(50) > 0) {
			break;
		}
		line(bg, pt1, pt2, color, 1, 8);
		imshow("random line demo", bg);
	}
}