OpenCV(cv::drawContours())
1. 函数原型
cv::drawContours() 用于在图像上绘制轮廓。函数原型:
void cv::drawContours(
cv::InputOutputArray image,
const std::vector<std::vector<cv::Point>>& contours,
int contourIdx,
const cv::Scalar& color,
int thickness = 1,
int lineType = 8,
const cv::Mat& hierarchy = cv::Mat(),
int maxLevel = INT_MAX,
cv::Point offset = cv::Point()
);
参数:
image: 输入输出图像,在其上绘制轮廓。contours: 轮廓的集合,每个轮廓是一个点的向量。轮廓通常由cv::findContours()函数生成。每个轮廓是一个std::vector<cv::Point>对象,包含了一系列按顺序排列的点。contourIdx: 该参数指定绘制哪个轮廓。- 取值
-1表示绘制所有轮廓。 - 非负值指定绘制特定索引的轮廓。
- 取值
color: 绘制轮廓的颜色,类型是cv::Scalar。- 对于彩色图像,
cv::Scalar(0, 255, 0)表示绿色。 - 对于灰度图像,
cv::Scalar(255)表示白色(轮廓)。
- 对于彩色图像,
thickness: 轮廓线的厚度。- 取值:正整数,表示轮廓线的宽度。当为
-1或cv::FILLED表示填充轮廓内部区域。
- 取值:正整数,表示轮廓线的宽度。当为
lineType: 线条类型,指定绘制轮廓线的连接方式。8:8-connectivity(默认),连通性为8。4:4-connectivity,连通性为4。CV_AA:抗锯齿线条(Anti-Aliasing),更平滑的线条,但计算更复杂。
hierarchy: 轮廓的层次结构矩阵(可选)。类型是cv::Mat,通常由cv::findContours()函数返回。maxLevel: 绘制的最大层级(可选)。- 取值:整数,
INT_MAX表示绘制所有层级的轮廓。
- 取值:整数,
offset: 对绘制轮廓的坐标进行偏移(可选)。类型是cv::Point,用于将所有轮廓点的坐标偏移到指定位置,通常用于处理多个图像拼接的情况。
2. 示例
cv::Mat img = cv::imread("image.jpg");
std::vector<std::vector<cv::Point>> contours;
cv::findContours(img, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
cv::drawContours(img, contours, -1, cv::Scalar(0, 255, 0), 2);
cv::imshow("Contours", img);
cv::waitKey(0);
在这个示例中,我们先找到轮廓,然后用绿色(cv::Scalar(0, 255, 0))和线宽为2绘制所有轮廓。

浙公网安备 33010602011771号