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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With