CImg :此构造函数需要什么样的值?

CImg : what kind of values are required on this constructor?

在文档 (http://cimg.eu/reference/structcimg__library_1_1CImg.html#a24f3b43daa4444b94a973c2c3fff82c5) 中,您可以读到 N°7 构造函数需要一个值数组来填充图像:

values = Pointer to the input memory buffer.

你一定知道我正在处理 RGB 二维图像(所以,"normal"/"common" 图像)。

因此,我用 Nx3 个值填充了一个向量(= 或多或少是一个数组)。 N 是像素数,数字“3”是因为我使用了红色、绿色和蓝色。我将第一个值设置为 0,第二个设置为 0,第三个设置为 255,这 3 个操作重复 N 次。 这就是为什么我的矢量名为 w,看起来像这样:{0, 0, 255 ; 0, 0, 255 ; etc.}

我写了这个构造函数:cimg_library::CImg<unsigned char>(&w[0], width, height, 2, 3); 表示有 3 个通道,深度为 2(因为我使用 2D),并给出我的值(宽度、高度和像素)。

我应该得到一个完全蓝色的图像。但它是黄色的。为什么 ?我是不是用错了向量?

与存储 "band interleaved by pixel" 的大多数格式不同,即 RGBRGBRGB...,CImg 中的数据存储 "band-interleaved by plane",即先是所有红色成分,然后是所有绿色成分,然后是所有蓝色成分,所以看起来像 RRRGGGBBB。这是描述 here.

因此,您的代码需要如下所示:

#include <vector>
#include "CImg.h"

using namespace std;
using namespace cimg_library;

int main()
{
    const int width=3;
    const int height=2;
    // 1. row - red, green, blue
    // 2. row - cyan, magenta, yellow

    // 6 pixels
    // Red plane first - red, green, blue, cyan, magenta, yellow
    // 255,0,0,0,255,255
    // Green plane next - red, green, blue, cyan, magenta, yellow
    // 0,255,0,255,0,255
    // Blue plane - red, green, blue, cyan, magenta, yellow
    // 0,0,255,255,255,0

    vector<unsigned char> w{
       255,0,0,0,255,255,
       0,255,0,255,0,255,
       0,0,255,255,255,0
    };

    CImg<unsigned char> image((unsigned char*)&w[0],width,height,1,3);
    image.save_pnm("result.pnm");
}


或者,如果您只想要一个纯蓝色图像,最简单的方法可能是使用一个像素的初始化程序实例化一个简单的 1x1 蓝色图像,然后调整它的大小:

    // Instantiate a 1x1 RGB image initialised to blue (last three values)
    CImg<unsigned char> blue(1,1,1,3,0,0,255);
    // Resize to larger image
    blue.resize(width,height);

另一种方法可能是:

// Create RGB image and fill with Blue
CImg<unsigned char> image(width,height,1,3);
image.get_shared_channel(0).fill(0);
image.get_shared_channel(1).fill(0);
image.get_shared_channel(2).fill(255);

另一种方法可能是:

CImg<unsigned char> image(256,256,1,3);

// for all pixels x,y in image
cimg_forXY(image,x,y) {
    image(x,y,0,0)=0;
    image(x,y,0,1)=0;
    image(x,y,0,2)=255;
}