Numpy array not displaying color dimension of greyscale image after converting from PIL image

Viewed 123

I'm trying to convert an RGB image to a greyscale image, then to a numpy array using the following code snippet:

img = Image.open("image1.png")
img = img.convert('L')
img = np.array(img, dtype='f')
print(img.shape)

The result is a numpy array of shape (128, 128). Is there anyway that I could convert a greyscale image to a numpy array so that it would have the color channel as well, i.e. the shape would be (128, 128, 1)?

1 Answers

Like @Mark mentioned in comments, add a dimension to the end if your array using newaxis:

img=img[...,None]

None will do similar as np.newaxis. It does not create a color, but adds a dimension similar to a single channel image.

Related