2

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))
rety
  • 59
  • 1
  • 6

2 Answers2

2
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))
kuppern87
  • 1,125
  • 9
  • 14
1

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]]
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • I've just asked [Convert any multi-dimensional numpy array to tuple of tuples of tuples… agnostic of number of dimensions](https://stackoverflow.com/q/68361779/3904031) – uhoh Jul 13 '21 at 11:46