#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
void Myline(Mat);
void MyRectangle(Mat);
void MyEllipse(Mat);
void MyCircle(Mat);
void MyPolygon(Mat);
void RandomLine(Mat src);
int main()
{
Mat cat = imread("F:\\visual studio\\Image\\cat.jpg");
imshow("cat", cat);
Myline(cat);
MyRectangle(cat);
MyEllipse(cat);
MyCircle(cat);
MyPolygon(cat);
putText(cat, "Hello OpenCV", Point(500, 200), CV_FONT_HERSHEY_COMPLEX, 1.0, Scalar(255, 100, 100), 2, LINE_AA);
imshow("cat", cat);
RandomLine(cat);
waitKey(0);
}
void Myline(Mat src)
{
Point p1 = Point(20, 30);
Point p2;
p2.x = 300;
p2.y = 300;
Scalar color = Scalar(0, 0, 255);
line(src, p1, p2, color, 2, LINE_AA);
}
void MyRectangle(Mat src)
{
Rect rect(300, 300, 200, 200);
Scalar color(255, 0, 0);
rectangle(src, rect, color, 2, LINE_AA);
}
void MyEllipse(Mat src)
{
Scalar color(0, 255, 0);
//设置椭圆的中心坐标 长轴短轴 倾斜角
RotatedRect rect(Point2f(300, 300), Size2f(200, 100), 45);
ellipse(src, rect, color,2,LINE_AA);
//通过设置起始角度以及终止角度可以画椭圆的一段弧
ellipse(src, Point(600, 300), Size(200, 100), 0, 90, 360, color, 2, LINE_AA);
}
void MyCircle(Mat src)
{
Scalar color(0, 255, 255);
circle(src, Point(600, 400), 100, color, 2, LINE_AA);
}
void MyPolygon(Mat src)
{
Scalar color(255, 255, 0);
//设置多边形的坐标,需要保证闭合
Point pts1[1][5] = { Point(700,100),Point(700,200),Point(650,150),Point(650,100),Point(700,100) };
Point pts2[1][4] = { Point(100,100),Point(100,200),Point(200,250),Point(100,100) };
const Point * ppts[] = { pts1[0],pts2[0] };
const int npts[] = { 5,4 };
//填充两个多边形
fillPoly(src,ppts,npts,2,color,LINE_AA);
}
//随机画线
void RandomLine(Mat src)
{
Mat dst = Mat::zeros(src.size(), src.type());
//设置种子为tick数
RNG rng(getTickCount());
for (int i = 0; i < 10000; i++)
{
//uniform(a,b)返回[a,b)范围内的均匀分布整数随机数
Point point1(rng.uniform(0, dst.cols), rng.uniform(0, dst.rows));
Point point2(rng.uniform(0, dst.cols), rng.uniform(0, dst.rows));
Scalar color(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
line(dst, point1, point2, color, 2, LINE_AA);
imshow("dst", dst);
if (waitKey(50) > 0)
break;
}
}
void Myline(Mat src)在图像中画线,void MyRectangle(Mat src)画出矩阵,void MyEllipse(Mat src)画出椭圆,void MyCircle(Mat src)画出圆,void MyPolygon(Mat src)填充多边形.
putText(cat, "Hello OpenCV", Point(500, 200), CV_FONT_HERSHEY_COMPLEX, 1.0, Scalar(255, 100, 100), 2, LINE_AA);
可以在指定坐标处绘制文字。效果如下:
void RandomLine(Mat src)实现了一个随机画线的功能,首先使用Mat::zeros()初始化一个Mat,接着利用RNG生成随机数,循环执行在随机两点间,使用随机的颜色画线的操作,利用if (waitKey(50) > 0)实现按键退出.效果如下: