1.绘制线段
void Mylines() {
Point p1 = Point(20, 30);
Point p2;
p2.x = 300;
p2.y = 300;
Scalar color = Scalar(0, 0, 255);
line(src,p1,p2,color,1,LINE_8);
}
2.绘制矩形
void MyRectngle() {
Rect rect = Rect(200, 100, 300, 300);
//参数说明:1矩形左上角点的横坐标 2矩形左上角点的纵坐标 3矩形的长 4矩形的宽
Scalar color = Scalar(0, 255, 0);
rectangle(src, rect, color, 2, LINE_8); //2表示线的宽度
}
3.绘制椭圆
void MyEllipse() {
Scalar color = Scalar(255, 0, 0);
ellipse(src, Point(src.cols / 2, src.rows / 2),
Size(src.cols / 4, src.rows / 8), 90, 0, 360,color,2,LINE_8);
//参数说明:0源图像 1椭圆中心
//2椭圆的规格(长轴,短轴) 3椭圆的倾斜角度 4起始角度 5终止角度 6颜色 7线条宽度 8线的类型
}
4.绘制圆
void MyCircle() {
Scalar color = Scalar(0, 255, 255);
Point center = Point(src.cols / 2, src.rows / 2); //圆心
circle(src, center, 200, color, 2, LINE_AA);
}
5.随机绘制线段
void RandomLineDemo() {
Mat src1 = Mat::zeros(src.size(), src.type());
RNG rng(12345);
Point pt1;
Point pt2;
//namedWindow("random line demo", WINDOW_AUTOSIZE);
for (int i = 0; i < 100000; i++) {
pt1.x = rng.uniform(0, src.cols); //pt1中x的取值范围 rng.uniform表示取随机数
pt2.x = rng.uniform(0, src.cols); //pt2中x的取值范围
pt1.y = rng.uniform(0, src.rows);//pt1中y的取值范围
pt2.y = rng.uniform(0, src.rows);//pt2中y的取值范围
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
if (waitKey(50) > 0) {
break;
}
line(src1, pt1, pt2, color, 1, LINE_AA);
imshow("random line demo", src1);
}
}
6.绘制多边形
void MyPolygon() {
Point pts[1][6];
pts[0][0] = Point(100, 100);
pts[0][1] = Point(100, 200);
pts[0][2] = Point(300, 200);
pts[0][3] = Point(200, 300);
pts[0][4] = Point(300, 100);
pts[0][5] = Point(100, 100);
const Point* ppts[] = { pts[0] };
int npt[] = { 6 };
Scalar color = Scalar(255, 12, 255);
fillPoly(src, ppts, npt, 1,color,LINE_8); //1表示只有一个轮廓
}
添加绘制文字+主函数:
int main(int argc, char** argv) {
src = imread("D:/image/img1.jpg");
if (src.empty()) {
printf("could not load image ... \n");
return -1;
}
Mylines();
MyRectngle();
MyEllipse();
MyCircle();
MyPolygon();
putText(src,"hello world",Point(200,200),FONT_HERSHEY_COMPLEX,1.0,Scalar(12,255,200),1,LINE_8);
//参数说明:1源图像 2显示内容 3显示起始位置 4字体 5缩放比例 6颜色 7线条宽度 8线条类型
RandomLineDemo();
namedWindow("src", WINDOW_AUTOSIZE);
imshow("src", src);
waitKey(0);
return 0;
}