Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert contour to 2d point list in opencv

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))
like image 890
Jay Avatar asked Apr 08 '14 08:04

Jay


1 Answers

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.

like image 97
lightalchemist Avatar answered Oct 11 '22 00:10

lightalchemist