Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 894
David Shaked Avatar asked Dec 05 '22 20:12

David Shaked


2 Answers

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))
like image 92
shahar_m Avatar answered Feb 18 '23 03:02

shahar_m


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.

like image 26
Kanish Mathew Avatar answered Feb 18 '23 02:02

Kanish Mathew