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.
CodePudding user response:
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)