How to add a dimension in numpy array? (125, 125) to (125, 125, 1)

Viewed 2827

I am loading an image using OpenCV python as a greyscale image because of which the shape of the image is (125, 125). But, I need the shape to be (125, 125, 1) where 1 denotes the number of channels ( 1 since it's greyscale ).

img = cv2.imread('/path/to/image.png', 0)
print(img.shape)
# prints (125, 125)

Now, I need to convert img's shape to (125, 125, 1)

3 Answers

The easiest way is to use numpy indexing and np.newaxis:

img = np.ones((125, 125)) # img.shape: (125, 125)
img_3d = img[..., np.newaxis] # img_3d.shape: (125, 125, 1)

This is especially handy if you only need the extra dimensions to pass the data to another function, so you can just pass the fancy-indexed array.

Try np.expand_dims:

In [1]: import numpy as np

In [2]: img = np.ones((125, 125))

In [3]: img.shape
Out[3]: (125, 125)

In [4]: img = np.expand_dims(img, axis=-1)

In [5]: img.shape
Out[5]: (125, 125, 1)
import numpy as np
a = np.random.rand(5,5)
b = a.reshape(5,5,1) 
b = a.reshape(1,5,5)
b = a.reshape(1,5,5,1)

any shape you want

Related