Search code examples
pythonimage-processingpython-2.6

How to check whether a JPEG image is color or gray scale using only Python stdlib


I have to write a test case in Python to check whether a jpg image is in color or grayscale. Can anyone please let me know if there is any way to do it with out installing extra libraries like OpenCV?


Solution

  • You can check every pixel to see if it is grayscale (R == G == B)

    from PIL import Image
    
    def is_grey_scale(img_path):
        img = Image.open(img_path).convert('RGB')
        w, h = img.size
        for i in range(w):
            for j in range(h):
                r, g, b = img.getpixel((i,j))
                if r != g != b: 
                    return False
        return True