Adam
Adam

Reputation: 485

NumPy Array to List Conversion

In OpenCV 3 the function goodFeaturesToTrack returns an array of the following form

[[[1, 2]]
 [[3, 4]]
 [[5, 6]]
 [[7, 8]]]

After converting that array into a Python list I get

[[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]]

Although this is a list, if you see it has one more pair of brackets than it should and when I try to access an element via A[0][1] I get an error. Why the array and the list have that form? How should I fix it?

Upvotes: 1

Views: 436

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Because you have a 3d array with one element in second axis:

In [26]: A = [[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]]

In [27]: A[0]
Out[27]: [[1, 2]]

And when you want to access the second item by A[0][1] it raises an IndexError:

In [28]: A[0][1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-28-99c47bb3f368> in <module>()
----> 1 A[0][1]

IndexError: list index out of range

You can use np.squeeze() in order to reduce the dimension, and convert the array to a 2D array:

In [21]: import numpy as np

In [22]: A = np.array([[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]])

In [33]: A = np.squeeze(A)

In [34]: A
Out[34]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

Upvotes: 1

Related Questions