1

I'm trying to load a single color PNG file into a numpy array. With most PNG files, the code below works fine. However, if the PNG file contains only a single color, the RGBA values of each pixel in the numpy array is [0, 0, 0, 255] which results in a black image. In the case of the color "red", how can I access the correct RGBA values? e.g. [255, 0, 0, 255]

from PIL import image
import numpy as np

red_image = Image.open("red.png")
arr = np.asarray(red_image)

When calling red_image.getBands(), I expected to see a tuple of ("R",) as per the documentation. Instead, I'm seeing ("P",). I have not idea yet what a "P" channel is but I think it's related to my question.

1 Answer 1

2

The 'P' mean the PIL mode is in "palettised". More info here: What is the difference between images in 'P' and 'L' mode in PIL?.

converting from "P" to "RGBA" fixed my issue.

from PIL import image
import numpy as np

red_image = Image.open("red.png")
red_image = red_image.convert("RGBA") # added this line
arr = np.asarray(red_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.