# OpenCV 基础图形的绘制及其随机生成

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

using namespace std;
using namespace cv;

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

void MyRectangle() {
Rect rect = Rect(150, 30, 300, 350); // parameter: x, y, width, height

rectangle(bgImage, rect, Scalar(255, 0, 0 ), 2, 8);
}

void MyEllipse() {
ellipse(bgImage, Point(bgImage.cols / 2, bgImage.rows / 2), Size(bgImage.cols / 4, bgImage.rows / 6), 90, 0, 180, Scalar(0, 255, 0), 2, LINE_AA);
}

void MyCircle() {
circle(bgImage, Point(bgImage.cols / 2, bgImage.rows / 2), 123, Scalar(0, 255, 255), 2, LINE_AA);
}

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);

Point pts[5];
pts[0] = Point(100, 100);
pts[1] = Point(100, 200);
pts[2] = Point(200, 200);
pts[3] = Point(200, 100);
pts[4] = Point(100, 100);

// const Point* ppts[] = {pst[0]};
const Point* ppts[] = {pts};
int ppt[] = {5};
Scalar color = Scalar(255, 100, 255);
fillPoly(bgImage, ppts, ppt, 1, color, 8); // src, Point **pts, int *npts, int ncontours, color
}

void RandomLineDemo() {
RNG rng(12345);
Point pt1, pt2;
Mat bg = Mat::zeros(bgImage.size(), bgImage.type());
for (int i = 0; i < 10000; 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 img", bg);
}

}

int main() {
//Mat src1, src2, gray_src, dst;
if (bgImage.empty()) { // if (!src.data())
cout << "could not load image..." << endl;
return -1;
}

//    Mylines();
//    MyRectangle();
//    MyEllipse();
//    MyCircle();
MyPolygon();
//    putText(bgImage, "Hello World!", Point(150, 50), CV_FONT_BLACK, 2, Scalar(123, 55, 200));
imshow("output", bgImage);
//
//    RandomLineDemo();
waitKey(0);

return 0;
}



• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120