Ask Your Question

Detecting the image if it is clored or black and white!?

asked 2015-10-28 06:27:25 -0600

thexnightmare gravatar image

updated 2015-10-28 10:10:27 -0600

Dear, I am trying to make a simple program detect the image if it is colored or black and white, any idea of how to achieve thgat? Thanks

edit retag flag offensive close merge delete


you may find this answer useful

Balaji R gravatar imageBalaji R ( 2015-10-28 08:50:27 -0600 )edit

2 answers

Sort by ยป oldest newest most voted

answered 2015-10-28 09:09:50 -0600

updated 2015-10-28 10:07:52 -0600

here is the implemention of second step of @theodore 's answer

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "iostream"

using namespace cv;

bool isGrayImage( Mat img ) // returns true if the given 3 channel image is B = G = R
    Mat dst;
    Mat bgr[3];
    split( img, bgr );
    absdiff( bgr[0], bgr[1], dst );

    if(countNonZero( dst ))
        return false;

    absdiff( bgr[0], bgr[2], dst );
    return !countNonZero( dst );

int main(int argc, char** argv)
    static const char* str[] = {" is a COLOR image"," is a GRAY image"};
    char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg";
    Mat src = imread(filename);

        std::cout << filename << str[isGrayImage( src )] << std::endl;
        imshow(filename, src );
    return 0;
edit flag offensive delete link more

answered 2015-10-28 07:33:59 -0600

theodore gravatar image

A first approach would be to check the numbers of channels of the loaded image. However, that would not work in case of where a grayscale/binary image is transformed to a 3-channel image. However, here you could apply another check, since in a grayscale/binary image the pixel values are gonna have the same value in all channels i.e. R=G=B. But still that might not be enough, therefore lastly you could just loop over the histogram of channel/channels of the image and take the average of pixel color weighed by the pixel count. I think combining all these three checks would give you what you want.

edit flag offensive delete link more


The number of channels and the negative value for the flag in imread should be enough...

thdrksdfthmn gravatar imagethdrksdfthmn ( 2015-10-28 07:41:32 -0600 )edit

can you give me a code on that please?

thexnightmare gravatar imagethexnightmare ( 2015-10-28 16:54:31 -0600 )edit

Question Tools

1 follower


Asked: 2015-10-28 06:27:25 -0600

Seen: 6,494 times

Last updated: Oct 28 '15