如何将Numpy数组(Rows x Cols)转换为XYZ坐标数组?

时间:2016-12-19 09:41:17

标签: numpy data-conversion

我有一个来自相机的输入数组(灰度图像),如下所示:

[
[0.5, 0.75, 0.1, 0.6], 
[0.3, 0.75, 1.0, 0.9] 
]

实际尺寸= 434x512

我需要一个输出,它是一个XYZ坐标列表:

即。 [[X,Y,Z],[X,Y,Z],...]

[[0,0,0.5],[1,0,0.75],[2,0,0.1],[3,0,0.6],[0,1,0.3],[1,1,0.75],[2,1,1.0],[3,1,0.9]]

使用Numpy有没有有效的方法呢?

1 个答案:

答案 0 :(得分:3)

这是一种方法 -

m,n = a.shape
R,C = np.mgrid[:m,:n]
out = np.column_stack((C.ravel(),R.ravel(), a.ravel()))

示例运行 -

In [45]: a
Out[45]: 
array([[ 0.5 ,  0.75,  0.1 ,  0.6 ],
       [ 0.3 ,  0.75,  1.  ,  0.9 ]])

In [46]: m,n = a.shape
    ...: R,C = np.mgrid[:m,:n]
    ...: out = np.column_stack((C.ravel(),R.ravel(), a.ravel()))
    ...: 

In [47]: out
Out[47]: 
array([[ 0.  ,  0.  ,  0.5 ],
       [ 1.  ,  0.  ,  0.75],
       [ 2.  ,  0.  ,  0.1 ],
       [ 3.  ,  0.  ,  0.6 ],
       [ 0.  ,  1.  ,  0.3 ],
       [ 1.  ,  1.  ,  0.75],
       [ 2.  ,  1.  ,  1.  ],
       [ 3.  ,  1.  ,  0.9 ]])

In [48]: out.tolist() # Convert to list of lists if needed
Out[48]: 
[[0.0, 0.0, 0.5],
 [1.0, 0.0, 0.75],
 [2.0, 0.0, 0.1],
 [3.0, 0.0, 0.6],
 [0.0, 1.0, 0.3],
 [1.0, 1.0, 0.75],
 [2.0, 1.0, 1.0],
 [3.0, 1.0, 0.9]]