#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> using namespace cv; using namespace std; //线 void MyLines(Mat &bgImage) { Point p1 = Point(20, 30); Point p2; p2.x = 300; p2.y = 300; Scalar color = Scalar(0, 0, 255); //抗锯齿 line(bgImage, p1, p2, color, 6, LINE_AA); putText(bgImage, "test", Point(300, 300), CV_FONT_HERSHEY_COMPLEX, 2.0, Scalar(255, 0, 0),3,8); } //矩形 void MyRectangle(Mat& bgImage) { Rect rect = Rect(510, 30, 60, 60); Scalar color = Scalar(0, 255, 0); //抗锯齿 rectangle(bgImage, rect, color,2, LINE_AA); } //椭圆 void MyEllipse(Mat& bgImag) { Scalar color = Scalar(0, 255, 0); //顺时针旋转45度,从0度画到360度 ellipse(bgImag, Point(bgImag.cols / 2, bgImag.rows / 2), Size(bgImag.cols / 4, bgImag.rows / 8),45, 0, 360, color, 2, LINE_4); } //圆 void MyCircle(Mat& bgImag) { Scalar color = Scalar(255, 0, 0); Point center = Point(bgImag.cols / 2, bgImag.rows / 2); circle(bgImag, center, 150, color, 2); } //多边形 void MyPolygon(Mat& bgImag) { Point pts[2][5]; pts[0][0] = Point(100, 100); pts[0][1] = Point(100, 300); pts[0][2] = Point(200, 200); pts[0][3] = Point(200, 100); pts[0][4] = Point(100, 100); pts[1][0] = Point(0, 100); pts[1][1] = Point(50, 300); pts[1][2] = Point(0, 200); pts[1][3] = Point(0, 100); pts[1][4] = Point(0, 100); //行指针 Point(*ppts)[] //元素指针 const Point* ppts[2]; ppts[0] = pts[0]; ppts[1] = pts[1]; int npt[2]; npt[0] = 5; npt[1] = 5; Scalar color = Scalar(255, 12, 255); fillPoly(bgImag, ppts, npt, 1, color, 8); //fillPoly(bgImag, &ppts[1], npt, 1, color, 8); } //随机画线 void randomLine(Mat& bgImag) { RNG rng(12345); Point pt1; Point pt2; Mat bg = Mat::zeros(bgImag.size(), bgImag.type()); namedWindow("随机画线", CV_WINDOW_AUTOSIZE); while (1) { pt1.x = rng.uniform(0, bgImag.cols); pt2.x = rng.uniform(0, bgImag.cols); pt1.y = rng.uniform(0, bgImag.rows); pt2.y = rng.uniform(0, bgImag.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("随机线条", bg); } } int main() { Mat src,dst; //原图 src = imread(".//pic//kate.png",IMREAD_UNCHANGED); if (!src.data) { cout << "load error" << endl; return -1; } /*MyLines(src); MyRectangle(src); MyEllipse(src); MyCircle(src); MyPolygon(src);*/ randomLine(src); namedWindow("demo", CV_WINDOW_AUTOSIZE); imshow("line", src); waitKey(0); return 0; }