我们将在这里演示如何使用几何形状和文本注释图像。
- Cv2.Line() 绘制直线
- Cv2.Ellipse() 绘制椭圆
- Cv2.Rectangle() 绘制矩形
- Cv2.Circle() 绘制圆
- Cv2.FillPoly() 绘制多边形
- Cv2.PutText() 绘制文本
一、绘制直线
Cv2.Line(image, start_point, end_point, color, thickness)
Mat img = new Mat(500, 500, MatType.CV_8UC3, Scalar.White); // 创建一个500x500的白色图像
Point pt1 = new Point(100, 100);
Point pt2 = new Point(400, 100);
Scalar color = new Scalar(0, 0, 255); // 红色线条
Cv2.Line(img, pt1, pt2, color, 2); // 在图像上绘制直线
Cv2.ImShow("Line", img); // 显示图像
二、绘制椭圆
Cv2.Ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness)
// 创建一个空白图像
Mat img = new Mat(500, 500, MatType.CV_8UC3, Scalar.White);
// 定义椭圆参数
Point center = new Point(250, 250);
Size axes = new Size(100, 200);
double angle = 30;
double startAngle = 0;
double endAngle = 360;
Scalar color = Scalar.Red;
int thickness = 2;
LineTypes lineType = LineTypes.Link8;
int shift = 0;
// 绘制椭圆
Cv2.Ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness, lineType, shift);
// 显示图像
Cv2.ImShow("Ellipse", img);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
三、绘制矩形
Cv2.Rectangle(image, pt1, pt2, rect, color,thickness,lineType)
// 创建一个空白图像
Mat img = new Mat(500, 500, MatType.CV_8UC3, Scalar.White);
Point start_point = new Point(300, 115);
Point end_point = new Point(475, 225);
Scalar color = new Scalar(0, 0, 255); // 红色线条
// 绘制矩形
Cv2.Rectangle(img, start_point, end_point, color, 3, (LineTypes)8, 0);
// 显示图像
Cv2.ImShow("Ellipse", img);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
四、绘制圆
Cv2.Circle(image, center_coordinates, radius, color, thickness)
// 创建一个空白图像
Mat image = new Mat(500, 500, MatType.CV_8UC3, Scalar.White);
// 定义圆心坐标和半径
Point center = new Point(250, 250);
int radius = 100;
// 在图像上绘制圆
Cv2.Circle(image, center, radius, Scalar.Red, 2);
// 显示图像
Cv2.ImShow("Circle", image);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
五、绘制多边形
Cv2.FillPoly(image,points,color,lineType)
using Point = OpenCvSharp.Point;
// 创建一个空白图像
Mat image = new Mat(500, 500, MatType.CV_8UC3, Scalar.White);
// 定义多边形的顶点坐标
Point[] points = new Point[]
{
new Point(100, 100),
new Point(200, 100),
new Point(200, 200),
new Point(100, 200)
};
// 将多边形绘制并填充到图像上
Cv2.FillPoly(image, new List<Point[]> { points }, Scalar.Red);
// 显示图像
Cv2.ImShow("Filled Polygon", image);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
六、绘制文本
Cv2.PutText(image, text, org, font, fontScale, color)
// 创建一个空白图像
Mat image = new Mat(500, 500, MatType.CV_8UC3, Scalar.White);
// 定义多边形的顶点坐标
Cv2.PutText(image, "Hello,OpenCvSharp!", new Point(20, 200), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2, LineTypes.Link4);
// 显示图像
Cv2.ImShow("Hello,OpenCvSharp", image);
c# OpenCV 基本绘画(直线、椭圆、矩形、圆、多边形、文本)(四)
c# OpenCV 图像裁剪、调整大小、旋转、透视(三)