Detect if image is color, grayscale or black and white with Python/PIL

后端 未结 5 724
青春惊慌失措
青春惊慌失措 2020-12-24 09:06

I extract pages images from a PDF file in jpeg format and I need to determine if each image is much more grayscale, color ou black and white (with a tolerance factor).

5条回答
  •  抹茶落季
    2020-12-24 09:36

    We use this simple function to determine the color-factor of an image.

    # Iterate over all Pixels in the image (width * height times) and do this for every pixel:
    {
        int rg = Math.abs(r - g);
        int rb = Math.abs(r - b);
        int gb = Math.abs(g - b);
        diff += rg + rb + gb;
    }
    
    return diff / (height * width) / (255f * 3f);
    

    As gray values have r-g = 0 and r-b = 0 and g-b = 0 diff will be near 0 for grayscale images and > 0 for colored images.

提交回复
热议问题