Home > other >  What does the 2nd dimension (index 1) of each contour represent in OpenCV
What does the 2nd dimension (index 1) of each contour represent in OpenCV

Time:11-08

In the following code:

contours, h = cv2.findContours(
    img_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE
)
print(contours[0].shape)

The output is:

(299, 1, 2)

What does the 2nd value (index 1 of the contour) represent? Does it always equal 1?

CodePudding user response:

OpenCV maps between numpy arrays and cv::Mat, which is used internally and in the C bindings.

A cv::Mat has a width and height and a number of channels.

That shape is mapped to a numpy array of shape (H, W, C), in both directions. If OpenCV seems fussy about some numpy array you give it, it helps to reshape/transpose the data into that specific shape.

By OpenCV convention, any list of points is commonly represented as a column vector cv::Mat of C-channel elements (the points). Hence the shape becomes (N, 1, 2)

When your numpy array has the shape (N, 2), the Python bindings of OpenCV may interpret that as a N-by-2, single-channel Mat. Most/all OpenCV APIs accept this format implicitly as an alternative to the column vector format.

The contours list (or tuple) from findContours contains a bunch of numpy arrays. Each contour will always have the shape (N, 1, 2) for however many points are in that specific contour.

You can call the .squeeze(axis=1) method to collapse that extra dimension.

  • Related