Search code examples
opencvimutils

How to use the contours related functions in the imutils library


Regarding the imutils library related to OpenCV, I have the following questions:

  1. What is the function of contours.sort_contours()?

  2. (cnts, _) = contours.sort_contours(cnts) In the above statement, what is the meaning of (cnts, _), especially '_'

Note: cnts is a variable containing the contours of the recognized image My English is not very good, sorry! Thank you all for your answers and help!


Solution

  • The imutils library is a convenience library written to make basic image processing tasks easier (https://github.com/PyImageSearch/imutils).

    One such task is sorting and labelling contours in images. Based on documentation provided here, there is a separate contours.py file hosting sort_contours() and label_contour functions. (You need to remember that these functions can be used only after finding contours using OpenCV)

    Now to answer your questions:

    1. What is the function of contours.sort_contours() ?

    • I will refer you to a sample code here. In line 35, the author accesses the function sort_contour() from the file contours.py in this way: contours.sort_contours().
    • The function accepts two parameters: the contours and the sorting arrangements ("left-to-right", "right-to-left", "top-to-bottom", "bottom-to-top")
    • The function returns a list of the sorted contours and its corresponding bounding boxes

    2. Understanding (cnts, _) = contours.sort_contours(cnts)

    • As stated previously, the function accepts contours as input cnts.
    • The same variable cnts is used to store the sorted contours.
    • Since the function returns dual output (sorted contours and its bounding boxes), the second variable is assigned _, which stores the bounding boxes. _ is mostly used a variable when it will not be needed for further processing.