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

前端 未结 9 2189

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:10

    Why wouldn't we use ImageStat module?

    from PIL import Image, ImageStat
    
    def is_grayscale(path="image.jpg")
    
        im = Image.open(path).convert("RGB")
        stat = ImageStat.Stat(im)
    
        if sum(stat.sum)/3 == stat.sum[0]:
            return True
        else:
            return False
    

    stat.sum gives us a sum of all pixels in list view = [R, G, B] for example [568283302.0, 565746890.0, 559724236.0]. For grayscale image all elements of list are equal.

提交回复
热议问题