David Shaked
David Shaked

Reputation: 3381

OpenCV: Ordering a contours by area (Python)

The OpenCV library provides a function that returns a set of contours for a binary (thresholded) image. The contourArea() can be applied to find associated areas.

Is the list of contours out outputted by findContours() ordered in terms of area by default? If not, does anyone know of a cv2 function that orders a list of contours by area?

Please provide responses in Python, not C.

Upvotes: 8

Views: 32109

Answers (2)

Kanish Mathew
Kanish Mathew

Reputation: 905

image, cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = sorted(cnts, key=cv2.contourArea)

cnt gives you an ordered list of contours in increasing order w.r.t area.

You can find the area of contour by index:

area = cv2.contourArea(cnt[index])

index can be 1,2,3.....,len(cnts)

For accessing the largest area contour:

cnt[reverse_index]

give reverse_index as -1

For second largest give reverse_index as -2 and so on.

The above can also be achieved with:

cnt = sorted(cnts, key=cv2.contourArea, reverse=True)

so cnt[1] gives the largest contour cnt[2] second largest and so on.

Upvotes: 14

Dawn
Dawn

Reputation: 3628

Use sorted and sort by the area key:

cnts = cv2.findContours(boolImage.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]  
cntsSorted = sorted(cnts, key=lambda x: cv2.contourArea(x))

Upvotes: 18

Related Questions