In previous sections, we have seen how to calculate the size of a detected contour. The size of a detected contour can be calculated based on image moments or using the OpenCV function cv2.contourArea(). In this example, we are going to sort the detected contours based on the computed size for each one.
Therefore, the sort_contours_size() function is key:
def sort_contours_size(cnts):
""" Sort contours based on the size"""
cnts_sizes = [cv2.contourArea(contour) for contour in cnts]
(cnts_sizes, cnts) = zip(*sorted(zip(cnts_sizes, cnts)))
return cnts_sizes, cnts
Before explaining the code of this function, we are going to introduce some key points. The * operator can be used in conjunction with zip() to unzip the list:
coordinate = ['x', 'y', 'z']
value = [5, 4, 3]
result = zip(coordinate,...