Drawing Polygons in OpenCV?

Just for the record (and because the opencv docu is very sparse here) a more reduced snippet using the 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));

Let's analyse the offending line:

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

You declared contourElement as vector <vector<Point> >, which means that contourElement.at(0) returns a vector<Point> and not a const cv::Point*. So that's the first error.

In the end, you need to do something like:

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

Later, call it as:

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

contourElement is vector of vector<Point> and not Point :) so instead of:

const Point *elementPoints

put

const vector<Point> *elementPoints

Some people may arrive here due to an apparently bug in the samples/cpp/create_mask.cpp from the OpenCV. This way, considering the above explained I edited the "if (event == EVENT_RBUTTONUP)" branch para to:

    ...
    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);
    ...

Hope it may help someone.