Arul
Arul

Reputation: 303

Issue with drawContours OpenCV c++

I have a code in python and I am porting it to c++. I am getting a weird issue with drawContours function in OpenCV c++.

self.contours[i] = cv2.convexHull(self.contours[i])
cv2.drawContours(self.segments[object], [self.contours[i]], 0, 255, -1)

this is the function call in python and the value -1 for the thickness parameter is used for filling the contour and the result looks like

looks like

I am doing exactly the same in c++,

cv::convexHull(cv::Mat(contour), hull);
cv::drawContours(this->objectSegments[currentObject], cv::Mat(hull), -1, 255, -1);

but this is the resulting image:

image

(please look careful to see the convexhull points, this is not easily visible). I am getting only the points and not the filled polygon. I also tried using fillPoly like,

cv::fillPoly(this->objectSegments[currentObject],cv::Mat(hull),255);

but doesn't help. Please help me in fixing the issue. I am sure that i am missing something very trivial but couldn't spot it.

Upvotes: 2

Views: 3741

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19041

The function drawContours() expects to receive a sequence of contours, each contour being a "vector of points".

The expression cv::Mat(hull) you use as a parameter returns the matrix in incorrect format, with each point being treated as a separate contour -- that's why you see only a few pixels.

According to the documentation of cv::Mat::Mat(const std::vector<_Tp>& vec) the vector passed into the constructor is used in the following manner:

STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements.

Considering this, you have two options:

  • Transpose the matrix you've created (using cv::Mat::t()
  • Just use a vector of vectors of Points directly

The following sample shows how to use the vector directly:

cv::Mat output_image; // Work image

typedef std::vector<cv::Point> point_vector;
typedef std::vector<point_vector> contour_vector;

// Create with 1 "contour" for our convex hull
contour_vector hulls(1);

// Initialize the contour with the convex hull points
cv::convexHull(cv::Mat(contour), hulls[0]);

// And draw that single contour, filled
cv::drawContours(output_image, hulls, 0, 255, -1);

Upvotes: 1

Related Questions