简体   繁体   English

对包含numpy.ndarray元素PYTHON的列表进行排序

[英]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. 我用cv2.findContours()则该方法approxPolyDP()我必须为每一个形状4-4检测到的边缘。 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. 问题是,我想根据第一个x,y坐标对列表进行排序。 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如下方式sorted的内置函数:

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. 这里key参数指定在进行比较之前在每个列表元素上调用的函数。 A reversed function can be called if you want a reversed version of the sorted list. 如果您想要排序列表的反转版本,可以调用reversed函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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