Reputation: 123
I am writing a program with CImg where I want to test if a pixel in an image is the color #00FF00
. How do I do this?
Upvotes: 2
Views: 1889
Reputation: 207873
To test pixel at column c
, row r
is green:
if((img(c,r,0,0)==0) &&
(img(c,r,0,1)==255) &&
(img(c,r,0,2)==0)) ...
Here is a 5x1 pixel image, with red, green, blue, white and black pixels in a single row that you can test with. Save it as image.ppm
.
P3
5 1
255
255 0 0 0 255 0 0 0 255 255 255 255 0 0 0
Enlarged appearance:
Here is a full example:
////////////////////////////////////////////////////////////////////////////////
// main.cpp
//
// CImg example of accessing pixels
//
// Build with: g++-6 -std=c++11 main.cpp -o main
// or: clang++ main.cpp -o main
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>
#define cimg_display 0
#include "CImg.h"
using namespace cimg_library;
using namespace std;
int main() {
// Load image
CImg<unsigned char> img("image.ppm");
// Get width, height, number of channels
int w=img.width();
int h=img.height();
int n=img.spectrum();
cout << "Dimensions: " << w << "x" << h << " " << n << " channels" <<endl;
// Dump all pixels
for(int r=0;r<h;r++){
for(int c=0;c<w;c++){
char hex[16];
sprintf(hex,"#%02x%02x%02x",img(c,r,0),img(c,r,1),img(c,r,2));
cout << r << "," << c << " " << hex << endl;
if((img(c,r,0,0)==0) &&
(img(c,r,0,1)==255) &&
(img(c,r,0,2)==0)){
cout << "This pixel is green" << endl;
}
}
}
}
Sample Output
The program produces this when run with the sample ppm
file above:
Dimensions: 5x1 3 channels
0,0 #ff0000
0,1 #00ff00
This pixel is green
0,2 #0000ff
0,3 #ffffff
0,4 #000000
Upvotes: 2
Reputation: 708
You can get a COLORREF
by calling CImage::GetPixel(int xPos, int yPos);
With the COLORREF
you can than create a new COLORREF
and compare the two:
CImage image;
COLORREF pixelColor = image.getPixel(451, 524); // this gets the color at (451,524) as a COLORREF
COLORREF greenColor = RGB(0, 255, 0);
if(pixelColor == greenColor)
{
// THE COLORS ARE THE SAME!
}
Upvotes: -1