简体   繁体   中英

Sorting a list which contains numpy.ndarray elements PYTHON

I'm working on a project of computer vision and I'd like to ask you something. I use cv2.findContours() the method then approxPolyDP() and I have 4-4 detected edges for every shape. There are three rectangles on the picture next to each other. The problem is, that I'd like to sort the list based on the first x,y coordinates. From left-to-right.

Thanks!

contours, _ = cv2.findContours(raw_image2, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx= cv2.approxPolyDP(contour,0.1*cv2.arcLength(contour,True),True)
    contur_list.append(approx)


   [array([[[383,  22]],

   [[384, 127]],

   [[492, 127]],

   [[491,  20]]], dtype=int32), array([[[ 54,  16]],

   [[ 52, 123]],

   [[160, 124]],

   [[160,  17]]], dtype=int32), array([[[222,  14]],

   [[220, 124]],

   [[328, 125]],

   [[328,  15]]], dtype=int32)]

That's the not sorted output, but I wish to be this one:

   [array([[[ 54,  16]],

   [[ 52, 123]],

   [[160, 124]],

   [[160,  17]]],dtype=int32), array([[[222,  14]],

   [[220, 124]],

   [[328, 125]],

   [[328,  15]]], dtype=int32), array([[[383,  22]],

   [[384, 127]],

   [[492, 127]],

   [[491,  20]]], dtype=int32)]

Try the built-in function sorted like this:

sorted(contur_list, key=lambda approx: approx[0,0,0])

here the key parameter specifies a function to be called on each list element prior to making comparisons. A reversed function can be called if you want a reversed version of the sorted list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM