In [117]: arr = np.array([[[0,0]],[[0,479]],[[639,479]],[[639,0]]])
In [118]: arr
Out[118]:
array([[[ 0, 0]],
[[ 0, 479]],
[[639, 479]],
[[639, 0]]])
In [119]: arr.shape
Out[119]: (4, 1, 2)
你显然想要structured array,https://numpy.org/devdocs/user/basics.rec.html#
有一个方便的工具可以将数值数组转换为结构化数组:
In [120]: import numpy.lib.recfunctions as rf
In [121]: rf.unstructured_to_structured(arr,names=['x','y'])
Out[121]:
array([[( 0, 0)],
[( 0, 479)],
[(639, 479)],
[(639, 0)]], dtype=[('x', '<i8'), ('y', '<i8')])
In [122]: _.shape
Out[122]: (4, 1)
或使用您想要的数据类型:
In [126]: rf.unstructured_to_structured(arr,dtype=np.dtype([('x', '<i2'), ('y', '<i2')]))
Out[126]:
array([[( 0, 0)],
[( 0, 479)],
[(639, 479)],
[(639, 0)]], dtype=[('x', '<i2'), ('y', '<i2')])
或创建一个具有所需数据类型和形状的“空白”数组,并分配字段:
In [127]: res = np.zeros((4,1), dtype=np.dtype([('x', '<i2'), ('y', '<i2')]))
In [128]: res
Out[128]:
array([[(0, 0)],
[(0, 0)],
[(0, 0)],
[(0, 0)]], dtype=[('x', '<i2'), ('y', '<i2')])
In [129]: res['x'] = arr[:,:,0]
In [130]: res['y'] = arr[:,:,1]
In [131]: res
Out[131]:
array([[( 0, 0)],
[( 0, 479)],
[(639, 479)],
[(639, 0)]], dtype=[('x', '<i2'), ('y', '<i2')])
或来自元组列表(在您的情况下为元组列表):
In [132]: arr.tolist()
Out[132]: [[[0, 0]], [[0, 479]], [[639, 479]], [[639, 0]]]
In [134]: [[tuple(i) for i in x] for x in arr.tolist()]
Out[134]: [[(0, 0)], [(0, 479)], [(639, 479)], [(639, 0)]]
In [135]: np.array([[tuple(i) for i in x] for x in arr.tolist()], dtype=[('x', '<i2'), ('y', '<i2')])
...:
Out[135]:
array([[( 0, 0)],
[( 0, 479)],
[(639, 479)],
[(639, 0)]], dtype=[('x', '<i2'), ('y', '<i2')])