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

前端 未结 9 2188

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

    A performance-enhance for fast results: since many images have black or white border, you'd expect faster termination by sampling a few random i,j-points from im and test them? Or use modulo arithmetic to traverse the image rows. First we sample(-without-replacement) say 100 random i,j-points; in the unlikely event that isn't conclusive, then we scan it linearly.

    Using a custom iterator iterpixels(im). I don't have PIL installed so I can't test this, here's the outline:

    import Image
    
    def isColor(r,g,b): # use tuple-unpacking to unpack pixel -> r,g,b
        return (r != g != b)
    
    class Image_(Image):
        def __init__(pathname):
            self.im = Image.open(pathname)
            self.w, self.h = self.im.size
        def iterpixels(nrand=100, randseed=None):
            if randseed:
                random.seed(randseed) # For deterministic behavior in test
            # First, generate a few random pixels from entire image
            for randpix in random.choice(im, n_rand)
                yield randpix
            # Now traverse entire image (yes we will unwantedly revisit the nrand points once)
            #for pixel in im.getpixel(...): # you could traverse rows linearly, or modulo (say) (im.height * 2./3) -1
            #    yield pixel
    
        def is_grey_scale(img_path="lena.jpg"):
            im = Image_.(img_path)
            return (any(isColor(*pixel)) for pixel in im.iterpixels())
    

    (Also my original remark stands, first you check the JPEG header, offset 6: number of components (1 = grayscale, 3 = RGB). If it's 1=grayscale, you know the answer already without needing to inspect individual pixels.)

提交回复
热议问题