Numpy: how to convert (256, 256) value image into (256, 256, 1) array of data points and back?

Viewed 1537

Numpy: how to convert (256, 256) value image into (256, 256, 1) array of data points and back?

I have tried and what I want:

tX = np.random.rand(100, 256,256)
tXnew = np.empty((tX.shape) + (1,))
tXnew[:, :, :, 0] = tX
assert(tXnew[1,5,55,0] == tX[1,5, 55])

#tXrestored = ? from tXnew
#assert(tXrestored [1,5,55] == tX[1,5, 55])
3 Answers

I think you should be fine using np.reshape

>>tX = np.random.rand(100, 256,256)
>>tX.shape
(100, 256, 256)
>>txNew = np.reshape(tX, (100,256,256,1))
>>txNew.shape
(100, 256, 256, 1)
>>txOld = np.reshape(txNew, (100,256,256))
(100, 256, 256)

Furthermore, you can check their equalities as well just to ensure that the original and restored numpy array have same values.

>>(tX==txOld).sum()
6553600
>>100*256*256
6553600

Besides the reshape method, an alternative approach to quickly add or remove dimensions with length 1 is using the methods expand_dims (adding dimensions) and squeeze (removing dimensions).

Example code:

>>> import numpy as np
>>> tX = np.random.rand(100, 256, 256)
>>> tX.shape
(100, 256, 256)
>>> tX_expanded = np.expand_dims(tX, axis=3)
>>> tX_expanded.shape
(100, 256, 256, 1)
>>> tX_squeezed = np.squeeze(tX_expanded)
>>> tX_squeezed.shape
(100, 256, 256)

An advantage of using this method over reshape is that you don't have to provide the size of the new arrays, making the code cleaner and easier to work with if you want to change the size of your original array later (you don't have to go through all of the reshape calls and update the size there).

Ok, time to add third (and the best, ;)) answer

you could literally add new axis where do you want it, visually it looks very conscious

Code

import numpy as np

t = np.random.rand(100, 256,256)

print(t.shape) # prints (100, 256, 256)

q = t[..., np.newaxis]

print(q.shape) # prints (100, 256, 256, 1)

you could add it in the middle if you want, along the lines

q = t[:, np.newaxis, :, :]

or

q = t[:, :, np.newaxis, :]
Related