The following is a contour structure returned by OpenCV. It's deeply nested, the first element of the tuple is a list of points in the contour.
Any idea to convert this to a 2d point list (n x 2)? I think numpy.reshape
can be used, but I couldn't find a very general way to do that. Thanks.
contours = cv2.findContours(bw_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours =>
([array([[[ 19, 20]],
[[ 18, 21]],
[[ 17, 21]],
[[ 17, 22]],
[[ 16, 23]],
[[ 16, 130]],
[[ 17, 131]],
[[ 17, 132]],
[[ 21, 132]],
[[ 43, 110]],
[[ 44, 110]],
[[ 75, 141]],
[[ 81, 141]],
[[109, 113]],
[[145, 149]],
[[149, 149]],
[[149, 21]],
[[148, 21]],
[[147, 20]]], dtype=int32)], array([[[-1, -1, -1, -1]]], dtype=int32))
import numpy as np
contours, hierarchy = cv2.findContours(bw_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = np.vstack(contours).squeeze()
Note that cv2.findContours actually return 2 items. "contours" here is a list. So we use numpy's vstack()
to stack them together, followed by squeeze()
to remove any redundant axis.
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