简体   繁体   中英

Convert numpy ndarray to tuple of tuples in optimize method

I have numpy ndarray, result of opencv findContours().
I want to convert each element of the result from numpy array to tuple of tuples efficiently.
Tried tolist(), asarray() etc but none of them give me the exact result.

example

numpy array:

    [[[191 307]]

     [[190 308]]

     [[181 308]]]

to tuple of tuples:

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

update
tuple(elements[0]) return

(array([[191 ,307]], dtype=int32),array([[190, 308]], dtype=int32),array([[181,308]], dtype=int32))
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))

Your array is 3d:

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

If you remove the middle dimension, it's easy to iterate on the rest:

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

If it doesn't have to be tuples, tolist is enough:

In [358]: a[:,0,:].tolist()
Out[358]: [[191, 307], [190, 308], [181, 308]]

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