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

前端 未结 9 2145

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 e

9条回答
  •  粉色の甜心
    2020-12-24 13:33

    For faster processing, it is better to avoid loops on every pixel, using ImageChops, (but also to be sure that the image is truly grayscale, we need to compare colors on every pixel and cannot just use the sum):

    from PIL import Image,ImageChops
    
    def is_greyscale(im):
        """
        Check if image is monochrome (1 channel or 3 identical channels)
        """
        if im.mode not in ("L", "RGB"):
            raise ValueError("Unsuported image mode")
    
        if im.mode == "RGB":
            rgb = im.split()
            if ImageChops.difference(rgb[0],rgb[1]).getextrema()[1]!=0: 
                return False
            if ImageChops.difference(rgb[0],rgb[2]).getextrema()[1]!=0: 
                return False
        return True
    

提交回复
热议问题