Conversion Of Images Of Different Color Depths Using Pillow

Overview:

  • Convert method of Image class in Pillow supports conversion between RGB, CMYK, grey scale, black & white images and images whose color depth is defined by a color palette.

 

  • Convert method supports adaptive palette - a customized palette based on the mostly used colors of the image and a web palette of 216 colors.

 

  • Though today's display devices and software have capability to render images with color depth of 24 bit and 32 bit, in several scenarios it is required to optimize the image representation using indexed pixel values.

 

  • An image with indexed pixel values or indexed color, will have each of its pixel value referring to an index of an array which is known as color palette.

 

  • Pillow allows using color palettes through the palette parameter of the convert method.

 

Example:

# import the image module

from PIL import Image

 

# Read a color image

colorImage = Image.open("./chameleon.jpg")

colorImage.show()

 

# Convert the color image to grey scale image

greyScaleImage = colorImage.convert("L")

 

# display the grey scale image

greyScaleImage.show()

 

# convert the color image to black and white image

blackAndWhiteImage = colorImage.convert("1")

blackAndWhiteImage.show()

 

# Convert using adaptive palette of color depth 8

imageWithColorPalette = colorImage.convert("P", palette=Image.ADAPTIVE, colors=8)

imageWithColorPalette.show()

 

Output:

Original image in RGB:

Original image in RGB

Original RGB image converted to grey scale:

RGB image converted to grey scale image

Original RGB image converted to a black & white image:

RGB image converted to black&white image

Original RGB image converted to an image of color depth 8 using a color palette:

RGB image converted to an image of color depth 8 using color palette


Copyright 2023 © pythontic.com