Basic Image Operations

Python Pillow Color Conversions

Image Manipulation

Image Filtering

Image Enhancement and Correction

Image Analysis

Advanced Topics

  • Image Module
  • Python Pillow Useful Resources

    Python Pillow - Changing Image Modes



    What is Changing Image Modes?

    In Pillow changing image modes refers to the process of converting an image from one color representation to another. Each mode represents a different way of encoding and interpreting color information in an image.

    Changing image modes is useful for various purposes such as preparing images for specific applications like printing, display or analysis. It allows us to adapt the color representation of an image to better suit our needs.

    In Pillow the Image class provides a method called convert() that allows us to change the mode of an image. The mode of an image determines the type and depth of pixel values it can contain.

    The following is the syntax and parameters of the convert() method of the Image class.

    original_image.convert(mode)
    

    Where,

    • original_image This is the source image whose mode we want to change.

    • mode This is a string specifying the desired mode for the new image.

    The below are the common changing Image modes.

    • L − 8-bit pixels represent black and white

    • RGB − 3x8-bit pixels represent true color

    • RGBA − 4x8-bit pixels represent true color with transparency

    • CMYK − 4x8-bit pixels represent color separation

    • HSV − Hue, saturation, value color space

    • 1 − 1-bit pixels, black and white which stored with one pixel per byte

    Following is the input image used in all the examples of this chapter.

    Rose

    Example - Changing Image to Black and White

    In this example we are changing the image mode into black and white by passing the mode argument as L to the convert() method.

    main.py

    from PIL import Image
    
    #Open an image
    original_image = Image.open("Images/rose.jpg")
    
    #Convert the image to grayscale (mode 'L')
    grayscale_image = original_image.convert("L")
    
    #Save the resulting image
    grayscale_image.save("Output_Images/output_grayscale.jpg")
    grayscale_image.show()
    

    Output

    output grayscale

    Example - Changing Image to 1 mode

    Here is the another example of changing the image mode to 1 by using the convert() method.

    main.py

    from PIL import Image
    
    #Open an image
    original_image = Image.open("Images/rose.jpg")
    
    #Convert the image to RGBA mode
    single_image = original_image.convert("1")
    
    #Save the resulting image
    single_image.save("Output_Images/output_single_image.jpg")
    single_image.show()
    

    Output

    output_single_image
    Advertisements