OpenCV 多边形绘制与填充
一、知识点
1、void polylines(InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar & color, int thickness = 1, int lineType = LINE_8, int shift = 0 );
(1)、在图像上绘制多边形曲线。
(2)、参数说明:
img: 输入、输出参数,要绘制多边形曲线的图像。
pts: 多边形曲线的顶点数组。
isClosed: 标志多边形曲线是否闭合。 若为true,则在最后一个顶点和第一个顶点之间绘制一条线段。
color: 多边形曲线的颜色。
thickness: 多边形曲线的粗细。
lineType: 线条的类型,如8连通、4连通、抗锯齿等。
shift: 点坐标中的小数位数。
(3)、注意: thickness在此函数中只能大于0,否则运行会报错。 所以polylines()只能绘制,不能填充多边形。
2、void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar & color, int lineType = LINE_8, int shift = 0, Point offset = Point());
(1)、在图像上填充多边形。
(2)、参数说明:
img: 输入、输出参数,要填充多边形的图像。
pts: 多边形的顶点数组。
color: 多边形填充的颜色。
lineType: 线条的类型,如8连通、4连通、抗锯齿等。
shift: 点坐标中的小数位数。
offset: 轮廓所有点的可选偏移。
3、void drawContours(InputOutputArray image,
InputArrayOfArrays contours,
int contourIdx,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
InputArray hierarchy = noArray(),
int maxLevel = INT_MAX,
Point offset = Point());
(1)、在图像上绘制轮廓或填充轮廓。
(2)、参数说明:
image: 输入、输出参数,要绘制或填充轮廓的图像。
contours: 所有轮廓的点集数组。
contourIdx: 要绘制的轮廓的索引(从0开始)。 如果为负,表示绘制或填充所有的轮廓。
color: 要绘制或填充的轮廓的颜色。
thickness: >0时表示轮廓线框粗细,<0时表示填充轮廓。
lineType: 线条的类型,如8连通、4连通、抗锯齿等。
hierarchy: 关于层次结构的可选信息。
maxLevel: 绘制轮廓的最大级别。
offset: 轮廓所有点的可选偏移。
二、示例代码
#include <iostream>
#include <opencv2/opencv.hpp>int main()
{cv::Mat canvas = cv::Mat::zeros(cv::Size(512, 512), CV_8UC3);//定义多边形的多个顶点cv::Point p1(100, 100);cv::Point p2(350, 100);cv::Point p3(450, 280);cv::Point p4(320, 480);cv::Point p5(80, 400);//变成一个点集std::vector<cv::Point> pts;pts.push_back(p1);pts.push_back(p2);pts.push_back(p3);pts.push_back(p4);pts.push_back(p5);//绘制多边形(只能绘制,不能填充, thickness只能>0)cv::polylines(canvas, pts, true, cv::Scalar(0, 0, 255), 4, 8, 0);//填充多边形cv::fillPoly(canvas, pts, cv::Scalar(255, 255, 0), 8, 0);//创造两个点集std::vector<cv::Point> pts1;pts1.push_back(cv::Point(15, 20));pts1.push_back(cv::Point(75, 20));pts1.push_back(cv::Point(65, 60));pts1.push_back(cv::Point(30, 40));std::vector<cv::Point> pts2;pts2.push_back(cv::Point(25, 25));pts2.push_back(cv::Point(100, 30));pts2.push_back(cv::Point(65, 60));pts2.push_back(cv::Point(20, 25));std::vector<std::vector<cv::Point>> vvpts;vvpts.push_back(pts1);vvpts.push_back(pts2);//用红色线画出两个轮廓cv::drawContours(canvas, vvpts, -1, cv::Scalar(0, 0, 255), 4, 8);//用黄色填充第1个轮廓cv::drawContours(canvas, vvpts, 0, cv::Scalar(0, 255, 255), -1, 8);//用洋红填充第2个轮廓cv::drawContours(canvas, vvpts, 1, cv::Scalar(255, 0, 255), -1, 8);cv::imshow("多边形绘制", canvas);cv::waitKey(0);return 0;
}
输出结果: