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

前端 未结 9 2187

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

    I faced a similar situation, where I tried the following approaches:

    1. Reading using IMREAD_UNCHANGEDand checking for image.shape
    2. Splitting B,G,R channels and checking if they are equal

    Both of these approaches got me only like 53% accuracy in my dataset. I had to relax the condition for checking pixels in different channels and create a ratio to classify it as grey or color. With this approach, I was able to get 87.3% accuracy on my dataset.

    Here is the logic which worked for me:

    import cv2
    import numpy as np
    
    ###test image
    img=cv2.imread('test.jpg')
    
    ### splitting b,g,r channels
    b,g,r=cv2.split(img)
    
    ### getting differences between (b,g), (r,g), (b,r) channel pixels
    r_g=np.count_nonzero(abs(r-g))
    r_b=np.count_nonzero(abs(r-b))
    g_b=np.count_nonzero(abs(g-b))
    
    ### sum of differences
    diff_sum=float(r_g+r_b+g_b)
    
    ### finding ratio of diff_sum with respect to size of image
    ratio=diff_sum/img.size
    
    if ratio>0.005:
        print("image is color")
    else:
        print("image is greyscale")
    

提交回复
热议问题