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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With