【OpenCV】绘制形状与文字
一、使用cv::Point与cv::Scalar
1、Point表示2D平面上一个点x,y
Point p;
p.x = 10;
p.y = 8;
或者
p = Pont(10,8);
2、Scalar表示四个元素的向量
Scalar(a, b, c);// a = blue, b = green, c = red表示RGB三个通道
二、绘制线、矩形、园、椭圆等基本几何形状
画线 cv::line (LINE_4\LINE_8\LINE_AA)
画椭圆cv::ellipse
画矩形cv::rectangle
画圆cv::circle
画填充cv::fillPoly
三、随机数生成cv::RNG
生成高斯随机数gaussian (double sigma)
生成正态分布随机数uniform (int a, int b)
四、绘制添加文字
putText
函数 中设置fontFace(cv::HersheyFonts),
- fontFace,
CV_FONT_HERSHEY_PLAIN
字体 - fontScale , 1.0, 2.0~ 8.0
代码实现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
Mat src;
void Mylines();
void Myrectangle();
void Mycircle();
void MyEllipse();
void MyFillpoly();
void RandomLine();
int main(int argc, char** argv)
{
src = imread("1.png");
if (src.empty()) {
cout << "cannot load the image..." << endl;
return -1;
}
//namedWindow("input", CV_WINDOW_AUTOSIZE);
//imshow("input", src);
Mylines();
Myrectangle();
Mycircle();
MyEllipse();
MyFillpoly();
putText(src, "hello baby!", Point(300, 300), CV_FONT_HERSHEY_COMPLEX, 1.0, Scalar(128, 128, 0), 1, 8);//在图片上添加文字
namedWindow("draw demo", CV_WINDOW_AUTOSIZE);
imshow("draw demo", src);
imwrite("draw demo.jpg", src);
RandomLine();
waitKey(0);
return 0;
}
void Mylines(){ //画直线
Point p1 = (100, 100);
Point p2;
p2.x = 300;
p2.y = 300;
Scalar color = Scalar(0, 0, 255);
line(src, p1, p2, color, LINE_AA);
}
void Myrectangle() { //画矩形
Rect rec = Rect(200, 200, 400, 400);
Scalar color = Scalar(255, 0, 0);
rectangle(src, rec, color, 3, 8, 0);
}
void Mycircle() { //画圆形
Scalar color = Scalar(0, 255, 0);
Point center = Point(src.cols / 2, src.rows / 2);
circle(src, center, src.rows / 6, color, 3, 8, 0);
}
void MyEllipse() { //画椭圆
Scalar color = Scalar(0, 128, 128);
Point center = Point(src.cols / 2, src.rows / 2);
ellipse(src, center, Size(src.cols / 4,src.rows / 8), 90, 0, 360, color, 2, LINE_8);
}
void MyFillpoly() { //画填充
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);
const Point* ppts[] = { pts[0] };
int npt[] = { 5 };
Scalar color = Scalar(255, 12, 255);
fillPoly(src, ppts, npt, 1, color, 8);
}
void RandomLine() { //在黑色背景画随机直线
RNG rng(12345);
Point pt1;
Point pt2;
Mat dst = Mat::zeros(src.size(), src.type());
for (int i = 1; i < 10000; i++) {
pt1.x = rng.uniform(0, src.cols);
pt1.y = rng.uniform(0, src.rows);
pt2.x = rng.uniform(0,src.cols);
pt2.y = rng.uniform(0,src.rows);
Scalar color = Scalar(255, 0, 14);
line(dst, pt1, pt2, color, 2, 8);
if (waitKey(50) > 0) {
break;
}
imshow("RandomLineDemo", dst);
imwrite("RandomLineDemo.jpg", dst);
}
}
实验效果图
1、draw demo
2、draw_random_line