drawContours
之前使用mask图还进行了连通域有无status分析,然后才进行的绘制。
今天发现直接使用mask图进行绘制,然后通过设置drawContours的参数可以进行不同层次上缺陷的绘制,然后通过这个事情也说明,有问题可以直接找opencv官网源码进行查看和分析说明。
方法1:
cv::RNG rng(12345);
cv::Mat cc_out;
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarcy;
cv::findContours(mask, contours, hierarcy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);
//绘制全部轮廓,直接绘制全部会很快 9ms 10ms 8ms
// drawContours(out, contours, -1, cv::Scalar(rng.uniform(0,256), rng.uniform(0, 256), rng.uniform(0, 256)), 2);
for (int k = 0; k < contours.size(); k++) {
cv::Scalar colors = cv::Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
if (contourArea(contours[k]) < 50)
continue;
if(isFilled)
drawContours(out, contours, k, colors, cv::FILLED, 8, hierarcy);
else
drawContours(out, contours, k, colors, 2);
}
cv::FILLED 第五个参数设置成这个,可以以填充的方式进行绘制缺陷区域。之前是通过遍历整个mask区域然后绘制,不仅慢,而且调用复杂。

Parameters
image Destination image.
contours All the input contours. Each contour is stored as a point vector.
contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
color Color of the contours.
thickness Thickness of lines the contours are drawn with. If it is negative (for example, thickness=FILLED ), the contour interiors are drawn.
lineType Line connectivity. See LineTypes
hierarchy Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see maxLevel ).
maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available.
offset Optional contour shift parameter. Shift all the drawn contours by the specified offset=(dx,dy) .
Note
When thickness=FILLED, the function is designed to handle connected components with holes correctly even when no hierarchy data is provided. This is done by analyzing all the outlines together using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved contours. In order to solve this problem, you need to call drawContours separately for each sub-group of contours, or iterate over the collection using contourIdx parameter.
百度翻译后:
当厚度=填充时,该函数设计用于正确处理带孔的连接部件,即使未提供层次结构数据。这是通过使用奇偶规则一起分析所有轮廓来完成的。如果您有单独检索的等高线的联合集合,这可能会给出错误的结果。为了解决这个问题,您需要为每个等高线子组分别调用drawContours,或者使用contourIdx参数遍历集合。
其实大致的写法应该就是上述那样,每个轮廓都挑选出来进行一个绘制。
如果进行一个连通域的分析,可以调用如下的代码进行尝试。
注意:使用下述connectedComponentsWithStats代码进行分析时比较费时的,可按需看是否需要。
方法2:
cv::Mat labels, stats, centroids

本文介绍了如何使用OpenCV的drawContours函数高效地绘制图像中的连通域和缺陷区域。通过调整参数,可以实现不同层次的绘制,包括填充和轮廓线。同时对比了直接使用mask图进行绘制与使用connectedComponentsWithStats进行连通域分析的方法,探讨了它们的时间效率和适用场景。此外,还提供了不同方法的代码示例,包括直接绘制、连通域分析后的绘制以及通过connectedComponents创建新图的绘制方式。

1万+

被折叠的 条评论
为什么被折叠?



