What does hierarchy = hierarchy[0] mean in OpenCV Python?

Question:

I’ve been tasked to translate some Python code into C#, and I’ve been having some difficulty as I have no experience with Python, and the program is even using OpenCV and NumPy.

This is the part of the code, and I’m not sure how hierarchy[0] is being assigned

_, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

hierarchy = hierarchy[0]
Asked By: MigfibOri

||

Answers:

There is nothing special about that assignment.

Just from reading the code, it is clear to me that the findContours() method returns a tuple of three values, the third one is a sequence and is assigned to hierarchy. The next line then just takes the first element from that sequence and assigns it back to the same name.

If you are trying to understand why it does this and how to translate this to C++, you’d need to go read the cv2::findContours() documentation. When looking at cv2 documentation, it’s always going to show you the C++ version, and C++ uses output arguments; findCountours() takes contours and hierarchy as two output arrays, to which the function will write.

In Python code, you just get the arrays as return values instead. Here, hierarchy is documented as

Optional output vector, containing information about the image topology. It has as many elements as the number of contours.

So hierarchy[0] has information on the first contour found, and any other elemens are discarded.

In a C++ translation of the code, you’d have to pass in arrays for both contours and hierarchy, then again extract the first element from the latter.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.