Search code examples
c++imagedevil

C++, how to load images and count pixels of certain colours


here's my problem:

I'm looking for a way to import an image into C++ then traverse its pixels, incrementing a counter every time a pixel of a certain colour is found.

I've done some research, but I haven't found anything particularly useful. DevIL looks like a good option, but I'm not sure where to start.

Here's a bit of C++/python pseudo-code hopefully illustrating what I'm trying to do:

for image in folder:

    A = 0;
    B = 0;

    for pixel in image:

        if (pixel == colourA) {A++}
        if (pixel == colourB) {B++}

    //Output the count of colours for each image
    outputToFile(A, B);

Does anyone have some tips on where to start?

Thanks

EDIT Some extra information: I'm using Windows 7 and all the images are .pngs

EDIT2 I've got everything working, except actually finding out the colour of the current pixel. Currently I'm using this:

int blue = ((uchar *)(img->imageData + pixelX*img->widthStep))[pixelY*img->nChannels + 0];

But it doesn't work, and I have no idea how it works. I haven't been able to find anything about this that I could understand. Could anyone point me in the right direction on how to find the RGB values of a certain pixel?

Edit3 Done! For anyone who finds this trying to do a similar thing, most of my remaining questions and a fair bit of code can be found here. Thanks for the help!


Solution

  • Definiately take a look at OpenCV because when you begin to need more room to move then OpenCV will let you do many more computer vision tasks. And use boost::filesystem to do the 'for each image in dir' code.

    Note that the cv::compare function basically does half the work for you already...I'll let you read that and enjoy leveraging the OpenCV API.