How to check the channel order of an image?

13,984

Since you use PIL and you don't specify any other mode to load the Image with, you get R G B.

You could verify that by checking the "mode" attribute on the Image instance:

image_pil.mode   # should return the string 'RGB'

Pillow supports the array interface, via image_pil.__array_interface__ magic method, so when when you create the ndarray numpy just uses that. i.e., it doesn't know anything about the colour channel order. If you have an image file stored as BGR, and you load it like this, you will get blue data in the red channel and vice-versa, and it would look wrong when you display it.

Share:
13,984

Related videos on Youtube

Matt Kleinsmith
Author by

Matt Kleinsmith

Updated on June 07, 2022

Comments

  • Matt Kleinsmith
    Matt Kleinsmith almost 2 years

    Question

    With an image loaded into Python as shown below, how do I know which order the channels are in? (e.g. BGR or RGB)

    Code

    from PIL import Image
    import numpy as np
    
    image_pil = Image.open("Stonehenge.jpg")
    image_np = np.array(image_pil)
    image_np[0][0]
    

    Result

    array([ 52, 123, 155], dtype=uint8)
    

    Specific question

    How do I know whether the 52 corresponds to the red channel, the blue channel, or a different channel? Or does this question not make sense on a conceptual level?


    Notes

    In a similar question for Java instead of Python, one person claims:

    If you are reading in the image file, or you have access to the code that reads in the file, know it is:

    • BGR order if you used cv2.imread(),
    • RGB order if you used mpimg.imread(), (assuming import matplotlib.image as mpimg)

    If you don't know how the file was opened, the accepted answer BufferedImage is great for Java.

    • Mark Ransom
      Mark Ransom over 6 years
      PIL/Pillow will always use R,G,B order. P.S. that's not color space - color space is which pixel values correspond to which physical colors, and will usually have names like sRGB, Adobe RGB, etc.
    • martineau
      martineau over 6 years
      Pixels are often composed of data from multiple color channels all being display together, so your question doesn't make much sense in that regard. Data in a given image file can be stored in one or more formats, which is image file format specific. You may need a third party module that provides you with that information for a specific file in question.
    • Matt Kleinsmith
      Matt Kleinsmith over 6 years
      It seems one needs to know the default order used for each package with respect to a file format, with some packages (e.g. PIL) defaulting to one order for all file formats. I removed "color space" from the question.