How to convert a Numpy array (Rows x Cols) to an array of XYZ coordinates?

6.5k views Asked by At

I have an input array from a camera (greyscale image) that looks like:

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

actual size = 434x512

I need an output which is a list of XYZ coordinates:

i.e. [[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]]

Are there any efficient ways to do this using Numpy?

1

There are 1 answers

0
Divakar On BEST ANSWER

Here's an approach -

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

Sample run -

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]]