我使用OpenCV和findContours
方法查找可以填充的多边形的轮廓。基本上,结果图像应看起来与输入相同。我提供的图像已经是黑白图像,因此不需要将其转换为灰度图像。
我遇到的问题是findContours
的结果不能总是被填充。 drawContours
可以绘制精美的轮廓,但是厚度= FILLED仅在某些情况下有效(这意味着在所示示例中不起作用,但可以在相似的输入上起作用)。最初使图像模糊,增加了成功的机会,但它仍然不是一个非常可靠的解决方案。
// blur( src_gray, src_gray, Size(2,2) ); - blurring an image with different kernel sizes might help sometimes
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
for(int i = 0; i <contours.size(); i++ ) {
drawContours( drawing, contours, i, Scalar(255, 255, 255), FILLED, 8);
}
我使用BOOST库将结果轮廓转换为多边形后,尝试验证结果轮廓出了什么问题,它告诉我Geometry has invalid self-intersections
或具有spikes
。在这种情况下,它无法纠正它。
是否有更好的解决方案可以给我填充的形状,假设仅绘制轮廓线效果很好?
如果将drawContours()函数中的i变量替换为-1,则可以得到一个填充的多边形。您必须删除以进行循环。
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
drawContours( drawing, contours, -1, Scalar(255, 255, 255), FILLED, 8);