Python – PIL Image mode I is grayscale

pythonpython-imaging-library

I'm trying to specify the colours of my image in Integer format instead of (R,G,B) format. I assumed that I had to create an image in mode "I" since according to the documentation:

The mode of an image defines the type and depth of a pixel in the
image. The current release supports the following standard modes:

  • 1 (1-bit pixels, black and white, stored with one pixel per byte)
  • L (8-bit pixels, black and white)
  • P (8-bit pixels, mapped to any other mode using a colour palette)
  • RGB (3×8-bit pixels, true colour)
  • RGBA (4×8-bit pixels, true colour with transparency mask)
  • CMYK (4×8-bit pixels, colour separation)
  • YCbCr (3×8-bit pixels, colour video format)
  • I (32-bit signed integer pixels)
  • F (32-bit floating point pixels)

However this seems to be a grayscale image. Is this expected? Is there a way of specifying a coloured image based on a 32-bit integer? In my MWE I even let PIL decide how to convert "red" to the "I" format.


MWE

from PIL import Image

ImgRGB=Image.new('RGB', (200,200),"red") # create a new blank image
ImgI=Image.new('I', (200,200),"red") # create a new blank image
ImgRGB.show()
ImgI.show()

Best Answer

Is there a way of specifying a coloured image based on a 32-bit integer?

Yes, use the RGB format for that, but instead use an integer instead of "red" as the color argument:

from PIL import Image

r, g, b = 255, 240, 227
intcolor = (b << 16 ) | (g << 8 ) | r                                       
print intcolor # 14938367
ImgRGB = Image.new("RGB", (200, 200), intcolor)
ImgRGB.show()
Related Topic