如何在 CImg 中测试图像中的像素是否具有某种颜色?

How to test if a pixel in an image is of a certain color in CImg?

我正在用 CImg 编写一个程序,我想在其中测试图像中的像素是否是颜色 #00FF00。我该怎么做?

您可以通过调用 CImage::GetPixel(int xPos, int yPos);

获得 COLORREF

使用 COLORREF,您可以创建一个新的 COLORREF 并比较两者:

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!
}

要测试第 c 列的像素,第 r 行为绿色:

if((img(c,r,0,0)==0) &&
   (img(c,r,0,1)==255) &&
   (img(c,r,0,2)==0)) ...

这是一张 5x1 像素的图像,在一行中有红色、绿色、蓝色、白色和黑色像素,您可以使用它进行测试。另存为 image.ppm.

P3
5 1
255
255 0 0 0 255 0 0 0 255 255 255 255 0 0 0

放大外观:


这是一个完整的例子:

////////////////////////////////////////////////////////////////////////////////
// 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;
          }
       }
    }
}

示例输出

当 运行 使用上面的示例 ppm 文件时,程序会生成此文件:

Dimensions: 5x1 3 channels
0,0 #ff0000
0,1 #00ff00
This pixel is green
0,2 #0000ff
0,3 #ffffff
0,4 #000000