Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 993
Logic1 Avatar asked Feb 05 '23 12:02

Logic1


1 Answers

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]]
like image 190
Divakar Avatar answered Feb 08 '23 14:02

Divakar