在OpenCV中绘制多边形?

时间:2011-11-26 20:05:20

标签: c++ arrays opencv image-processing vector

我在这里做错了什么?

vector <vector<Point> > contourElement;

for (int counter = 0; counter < contours -> size (); counter ++)
{   
    contourElement.push_back (contours -> at (counter));

    const Point *elementPoints [1] = {contourElement.at (0)};
    int numberOfPoints [] = {contourElement.at (0).size ()};

    fillPoly (contourMask, elementPoints, numberOfPoints, 1, Scalar (0, 0, 0), 8);

我一直在const Point部分出错。编译器说

error: cannot convert 'std::vector<cv::Point_<int>, std::allocator<cv::Point_<int> > >' to 'const cv::Point*' in initialization

我做错了什么? (PS:显然忽略for循环结束时缺少的括号,因为这只是我代码的一部分)

4 个答案:

答案 0 :(得分:12)

让我们分析一下违规行:

const Point *elementPoints [1] = { contourElement.at(0) };

您将contourElement声明为vector <vector<Point> >,这意味着contourElement.at(0)会返回vector<Point>而不是const cv::Point*。这是第一个错误。

最后,您需要执行以下操作:

vector<Point> tmp = contourElement.at(0);
const Point* elementPoints[1] = { &tmp[0] };
int numberOfPoints = (int)tmp.size();

稍后,将其命名为:

fillPoly (contourMask, elementPoints, &numberOfPoints, 1, Scalar (0, 0, 0), 8);

答案 1 :(得分:12)

仅仅是为了记录(因为opencv文档在这里非常稀疏),使用c ++ API的代码片段更少:

  std::vector<cv::Point> fillContSingle;
  [...]
  //add all points of the contour to the vector
  fillContSingle.push_back(cv::Point(x_coord,y_coord));
  [...]

  std::vector<std::vector<cv::Point> > fillContAll;
  //fill the single contour 
  //(one could add multiple other similar contours to the vector)
  fillContAll.push_back(fillContSingle);
  cv::fillPoly( image, fillContAll, cv::Scalar(128));

答案 2 :(得分:2)

contourElement是vector<Point>的向量而不是Point :) 所以代替:

const Point *elementPoints

const vector<Point> *elementPoints

答案 3 :(得分:0)

有些人可能会因为 OpenCV 中的 samples/cpp/create_mask.cpp 中的明显错误而到达这里。这样,考虑到上述解释,我将“if (event == EVENT_RBUTTONUP)”分支段编辑为:

    ...
    mask = Mat::zeros(src.size(), CV_8UC1);
    vector<Point> tmp = pts;
    const Point* elementPoints[1] = { &tmp[0] };        
    
    int npts = (int) pts.size();        
    
    cout << "elementsPoints=" << elementPoints << endl;

    fillPoly(mask, elementPoints, &npts, 1, Scalar(255, 255, 255), 8);     
    bitwise_and(src, src, final, mask);
    ...

希望它可以帮助某人。