图像插入——线,椭圆,圆,文字,矩形,多边形,
程序员文章站
2022-03-31 19:44:08
...
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2/core/core_c.h>
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\imgproc\types_c.h>
using namespace std;
using namespace cv;
Mat bgImage;
const char* drawdemo_win = "draw shapes and test demo";
//函数声明
void MyLines();
void MyRectangle();
void MyEllipse();
void MyCircle();
void MyPolygin();
void RandonLineDemo();
int main(int argc, char** argv)
{
bgImage = imread("F:\\1.jpg");
if (bgImage.empty())
{
printf("could not load image src...\n");
return -1;
}
/*MyLines();//函数调用:划线
MyRectangle();//函数调用:矩形
MyEllipse();// 椭圆
MyCircle();//圆
MyPolygin();//多边形
*/
RandonLineDemo();
//putText(bgImage, "Hi", Point(200, 200), FONT_HERSHEY_COMPLEX, 1.0, Scalar(0, 0, 255), 2, 8);//插入文字
namedWindow("drawdemo_win", WINDOW_AUTOSIZE);
imshow("drawdemo_win", bgImage);
waitKey(0);
return 0;
}
void MyLines()
{
Point p1 = Point(20, 30);
Point p2;
p2.x = 700;
p2.y = 700;
Scalar color = Scalar(0, 0, 255);
line(bgImage, p1, p2, color, 1, LINE_AA);//AA反锯齿
}
void MyRectangle()
{
Rect rect = Rect(200, 100, 200, 200);//起始位置200,100 ;宽高为300,300
Scalar color = Scalar(255, 0, 0);//定义色彩
rectangle(bgImage, rect, color, 2, LINE_8);//2是线宽
}
void MyEllipse()
{
Scalar color = Scalar(0, 25, 5);
//point 椭圆中心;椭圆半径(长轴,短轴);45是与x轴的角度;
ellipse(bgImage, Point(bgImage.cols / 2, bgImage.rows / 2), Size(bgImage.cols / 4, bgImage.rows / 8), 45, 0, 240, color, LINE_8);
}
void MyCircle()
{
Scalar color = Scalar(0, 255, 0);
Point center = Point(bgImage.cols / 2, bgImage.rows / 2);//圆的中心
circle(bgImage, center, 150, color, 8);
}
void MyPolygin()
{
Point pts[1][5];
pts[0][0] = Point(100, 100);
pts[0][2] = Point(100, 200);
pts[0][3] = Point(200, 100);
pts[0][4] = Point(100, 100);
const Point* ppts[] = { pts[0] };//point的指针
int rpt[] = { 5 };//有5个指针
Scalar color = Scalar(255, 255, 0);
fillPoly(bgImage, ppts, rpt, 1, color, 8);//1和pts[1][5]中的1对应,rpt画在哪边
}
void RandonLineDemo()
{
RNG rng(12345);//RNG(int seed) 使用种子seed产生一个64位随机整数,默认-1
Point pt1;
Point pt2;
Mat dst = Mat::zeros(bgImage.size(), bgImage.type());
for (int i = 0; i < 100000; i++) {
pt1.x = rng.uniform(0, dst.cols);//生成正态分布随机数uniform (int a, int b)
pt2.x = rng.uniform(0, dst.cols);
pt1.y = rng.uniform(0, dst.rows);
pt2.y = rng.uniform(0, dst.rows);
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//随机生成颜色
if (waitKey(100) > 0) //100ms退出
{
break;
}
line(bgImage, pt1, pt2, color, 1, 8);
imshow("RandonLineDemo", bgImage);
}
}