我想使用pointPolygonTest
,但是有问题。我的OpenCV版本是2.2。
我尝试使用this tutorial中的代码。
我使用findContours
来检测图像中的轮廓。在OpenCV 2.2下,返回vector<vector<Point> >
。
问题是pointPolygonTest
接受cv::Mat
作为条目。因此,该代码无法与OpenCV 2.2一起编译:
error: invalid initialization of reference of type ‘const cv::Mat&’ from expression of type ‘std::vector<cv::Point_<int>, std::allocator<cv::Point_<int> > >’
在较新的OpenCV版本中,
findContours
函数返回vector<Mat>
,因此很容易传递给pointPolygonTest
(请参见示例)。我想我可以将
vector< vector<Point> >
转换为vector<Mat>
。不幸的是,文档对格式不是很清楚。
有人有建议吗?
最佳答案
那么,为什么要使用旧版本的OpenCV?这是OpenCV版本中此方法的声明。 2.4.1:
C++: double pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)
如您所见,第一个参数是InputArray而不是矩阵。从那篇文章:
因此,这意味着您可以将
std::vector<vector<Point> >
用作InputArray
并用作函数pointPolygonTest
的输入。这是使用
pointPolygonTest
的简单示例(当然是新版本):vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat src;
findContours(src, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
for(size_t i = 0; i<contours.size(); i++)
{
if (pointPolygonTest(contours[i], point, false) > 0)
{
//point is inside polygon
...
break;
}
}
因此,只需更新到新版本即可。
或者,如果要在旧版本中使用它,请尝试以下强制转换:
(Mat)contours[i]
或使用构造函数:
Mat(contours[i])
希望能帮助到你。