我已经用 python 编写了一个调用 cv2.minEnclosingCircle 方法的脚本,我正在尝试用 c++ 重新创建一个类似的程序,但我无法通过引用传递半径和中心。
我已尝试使用有关无效初始化的替代答案并遵循有关函数的 openCV 文档,但尚不清楚,我能够通过没有“&”的半径和中心,但我不想。
这是我的代码:
if (contours.size() > 0)
{
auto c = *std::max_element(contours.begin(),contours.end(),
[](std::vector<cv::Point> const& lhs, std::vector<cv::Point> const& rhs)
{return contourArea(lhs, false) < contourArea(rhs, false); });
cv::minEnclosingCircle(c, ¢er, &radius); // not compiling
}
我已将半径和中心分别声明为 float 和 cv::Point2f 类型。
Error: invalid initialization of non-const reference of type 'cv::Point2f& {aka cv::Point_<float>& }' from an rvalue of type 'cv::Point2f* {aka cv::Point_<float>*}
这是我在 Python 中的做法:
if len(contours) > 0;
#find largest contour in mask, use to compute minEnCircle
c = max(contours, key = cv2.contourArea)
(x,y), radius) = cv2.minEnclosingCircle(c) #not compiling in c++
M = cv2.moments(c)
最佳答案
您可能不需要在 C++ 中使用 &
运算符显式传递变量,这可以简单地完成:
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// Here contours and hierarchy are implicitly passed by reference.
cv::findContours(img, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
cv::Point2f center;
float radius;
if (contours.size() > 0) {
// center and radius implicitly passed by reference.
cv::minEnclosingCircle(contours[0], center, radius);
}
std::cout << "Center : " << center << std::endl;
std::cout << "Radius : " << radius << std::endl;
关于python - 'cv::Point2f&' 类型的非常量引用的初始化无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747730/