Hanson
Hanson

Reputation: 301

How can I convert from contour vector to MAT?

This is the code I have to find the contour of an image:

contour, heir= cv2.findContours(hmg,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

I want to find the area of a contour with

cv2.contourArea(contour)

but that needs a MAT datatype, and not the contour vector type

How can I convert contour so I can do this?

Upvotes: 1

Views: 245

Answers (1)

Calvin Yan
Calvin Yan

Reputation: 36

The contour object is in fact a list of all contours found in the image, each of which are in the correct format. A name like contours might be more appropriate, but that's non-essential.

Your post assumes a singular contour; this is rarely the case due to filtering noise, but you could single the contour out by sorting by descending area:

contours, heir= cv2.findContours(hmg,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
print(cv2.contourArea(contours[0]))

Upvotes: 2

Related Questions