Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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)

like image 632
Parthapratim Neog Avatar asked Oct 24 '25 20:10

Parthapratim Neog


1 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.

like image 82
Jan Christoph Terasa Avatar answered Oct 26 '25 11:10

Jan Christoph Terasa