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

后端 未结 5 717
青春惊慌失措
青春惊慌失措 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:52

    I personally prefer the answer of TomB. This is not a new answer, I just want to post the Java version:

    private Mat calculateChannelDifference(Mat mat) {   
    
        // Create channel list:
        List channels = new ArrayList<>();
    
        for (int i = 0; i < 3; i++) {
            channels.add(new Mat());
        }
    
        // Split the channels of the input matrix:
        Core.split(mat, channels);
    
        Mat temp = new Mat();
    
        Mat result = Mat.zeros(mat.size(), CvType.CV_8UC1);
    
        for (int i = 0; i < channels.size(); i++) {
    
            // Calculate difference between 2 successive channels:
            Core.absdiff(channels.get(i), channels.get((i + 1) % channels.size()), temp);
    
            // Add the difference to the result:
            Core.add(temp, result, result);
        }
    
        return result;
    }
    

    The result is the difference as an matrix, this way you could apply some threshold and even detect shapes. If you want the result as a single number, you will just have to calculate the average value. This can be done using Core.mean()

提交回复
热议问题