c++画直线、矩形、圆、椭圆

c++画图

1、画直线
line(src, p1, p2, color, thickness, typeline) // src:图像,p1:起始点,p2:终止点,color:颜色,thickness:线宽,typeline:线型。
2、画矩形
rectangle(src, rect, color, thickness, typeline) // rect:矩形的形状。
3、画椭圆
ellipse(src, 中心点,长轴长, 短轴长, 旋转角度,椭圆的起始度数,椭圆的终止度数,线宽,线型) //ellipse(img, Point(img.cols/2, img.rows/2), Size(img.cols/4, img.rows/6), 45, 0, 360, 1, LINE_8);
4、画圆
circle(src, 圆中心点, 半径,颜色,线宽,线型); //circle(img, center, 100, color, 1 , 8)
4、填充多边形
fillPoly(src, 起始指针,个数,颜色,线宽,线型); //fillPoly(img, ppts, ptn, color, 1, 8);
5、在图像上显示文字
putText(src “文字”, 起始点坐标, 字体, 尺寸因子, 颜色, 线宽, 线型); //putText(dst, “the number of lines”, Point(100, 100), FONT_HERSHEY_COMPLEX, 1.0, Scalar(125, 125, 125), 1, 8);

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

using namespace std;
using namespace cv;


void Lines(); 
void Rectangles();
void Ellipses();
void Circle();
void RandomLines();
void Polygons();

Mat img = imread("G:/testpic/img.png");

int main(int argc, char** args)
{
	if (img.empty())
	{
		printf("the image cannot load");
		return -1;
	}
	Lines();
	Rectangles();
	Ellipses();
	Circle();
	RandomLines();
	Polygons();
	namedWindow("input", WINDOW_AUTOSIZE);
	imshow("input", img);
	putText(img, "draw", Point(100,100), Font__HERSHEY_COMPLEX, 1.0, Scalar(125,125,125), 1, 8);
}

//直线
void Lines()
{
	Point p1 = Point(20,30);
	Point p2;
	p2.x = 300;
	p2.y = 300;
	Scalar color = Scalar(0,0,255);line(img, p1, p2, color, 1, LINE_8);
	
}

//矩形
void Rectangles()
{
	Rect rect = Rect(100,100, 200, 150); //(100,100)起始点坐标,宽200, 高150
	Scalar color = Scalar(0,255,255);
	rectangle(img, rect, color, 1, LINE_8);
	
}

//椭圆
void Ellipses()
{
	Scalar color = Scalar(255, 0, 0);
	ellipse(img, Point(img.cols/2, img.rows/2), Size(img.cols/4, img.rows/6), 45, 0, 360, 1, LINE_8);
}

//圆
void Circle()
{
	Scalar color = Scalar(255,0,0);
	Point center = Point(img.cols/2, img.rows/2);
	circle(img, center, 100, color, 1 , 8);
}

//随机直线
void RandomLines()
{
	RNG rng(1234);
	Point p1;
	Point p2;
	Mat dst = Mat::zeros(img.size(), img.type());
	
	for (int i=0; i < 1000; i++)
	{
		Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));
		p1.x = rng.uniform(0, img.cols);
		p1.y = rng.uniform(0, img.rows);
		p2.x = rng.uniform(0, img.cols);
		p2.y = rng.uniform(0, img.rows);
		if(waitKey(50)>0)
		{
			break;
		}
		line(dst, p1, p2, color, 1, 8);
		imshow("output", dst);
	}

}

//多边形
void Polygons()
{
	Point pts[1][5];
	const Point* ppts[] = {pts[0]};
	int ptn[] = {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);
	Scalar color = Scalar(125, 125, 255);
	fillPoly(img, ppts, ptn, color, 1, 8);
}

示例图
结果图:
在这里插入图片描述
结果图2