[英]NumPy Array to List Conversion
In OpenCV 3 the function goodFeaturesToTrack
returns an array of the following form在 OpenCV 3 中,函数goodFeaturesToTrack
返回以下形式的数组
[[[1, 2]]
[[3, 4]]
[[5, 6]]
[[7, 8]]]
After converting that array into a Python list I get将该数组转换为 Python 列表后,我得到
[[[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.虽然这是一个列表,但如果您看到它比它应该多出一对括号,并且当我尝试通过 A[0][1] 访问元素时,我会收到错误消息。 Why the array and the list have that form?为什么数组和列表具有这种形式? How should I fix it?我该如何解决?
Because you have a 3d array with one element in second axis:因为你有一个 3d 数组,第二个轴有一个元素:
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:当你想通过A[0][1]
访问第二个项目时,它会引发一个 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:您可以使用np.squeeze()
来减少维度,并将数组转换为二维数组:
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.