1

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?

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! That is exactly what I wanted. One question out of curiosity. Why the function created a 3D array anyway?
@Adam I think that's the functionality of goodFeaturesToTrack, you can find more details in documentation.
I will do. Thank you again for the detailed answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.