【问题标题】:Convert numpy ndarray to tuple of tuples in optimize method在优化方法中将numpy ndarray转换为元组的元组
【发布时间】:2018-08-16 12:56:26
【问题描述】:

我有 numpy ndarray,opencv findContours() 的结果。
我想有效地将​​结果的每个元素从 numpy 数组转换为元组的元组。
尝试了 tolist()、asarray() 等,但它们都没有给我确切的结果。

示例

numpy 数组:

    [[[191 307]]

     [[190 308]]

     [[181 308]]]

到元组的元组:

((191,307),(190,308),(181,308))

更新
tuple(elements[0])返回

(array([[191 ,307]], dtype=int32),array([[190, 308]], dtype=int32),array([[181,308]], dtype=int32))

【问题讨论】:

  • 元组列表还是元组的元组?
  • 我不确定。假设我写了这行 x=((0,0),(1,1))。 x 是元组列表对吗? @MatinaG
  • 先尝试my_list = numpy.ndarray.tolist(my_array),然后再尝试tuple(my_list)
  • 对不起,这是一个元组的元组
  • tuple(tuple(ai) for ai in my_array) 怎么样?

标签: python numpy


【解决方案1】:
In [9]: a = numpy.array([[[191, 307]],
   ...:                  [[190, 308]],
   ...:                  [[181, 308]]])

In [10]: tuple(tuple(row[0]) for row in a)
Out[10]: ((191, 307), (190, 308), (181, 308))

【讨论】:

    【解决方案2】:

    你的数组是 3d:

    In [356]: a.shape
    Out[356]: (3, 1, 2)
    

    如果去掉中间维度,剩下的就很容易迭代了:

    In [357]: tuple(tuple(i) for i in a[:,0,:])
    Out[357]: ((191, 307), (190, 308), (181, 308))
    

    如果不必是元组,tolist 就足够了:

    In [358]: a[:,0,:].tolist()
    Out[358]: [[191, 307], [190, 308], [181, 308]]
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2017-10-05
    • 1970-01-01
    • 2016-07-09
    • 2021-12-18
    • 2018-05-03
    • 2018-04-19
    相关资源
    最近更新 更多