2

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)?

2
  • 3
    You can do img = img[..., np.newaxis] to get that shape but I don't see how that gives you colour. Commented Oct 28, 2020 at 7:36
  • 2
    To expand on Mark's comment, this is a somewhat confusing question because the values of the (128, 128) array are the "colors" here. Sometimes you need to have a singleton dimension, but it's usually because you are using numpy broadcasting or something similar. Adding a singleton dimension changes nothing about the underlying data. So you have a good answer now from @crazycoder, but I am not sure you have a solution to your actual problem. Commented Oct 28, 2020 at 9:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.