Combining image channels in CImg

169 Views Asked by At

In CImg, I have split an RGBA image apart into multiple single-channel images, with code like:

CImg<unsigned char> input("foo.png");
CImg<unsigned char> r = input.get_channel(0), g = input.get_channel(1), b = input.get_channel(2), a = input.get_channel(3);

Then I try to swizzle the channel order:

CImg<unsigned char> output(input.width(), input.height(), 1, input.channels());
output.channel(0) = g;
output.channel(1) = b;
output.channel(2) = r;
output.channel(3) = a;

When I save the image out, however, it turns out grayscale, apparently based on the alpha channel value; for example, this input:

input image

becomes this output:

output image

How do I specify the image color format so that CImg saves into the correct color space?

1

There are 1 best solutions below

0
fluffy On

Simply copying a channel does not work like that; a better approach is to copy the pixel data with std::copy:

std::copy(g.begin(), g.end(), &output.atX(0, 0, 0, 0));
std::copy(b.begin(), b.end(), &output.atX(0, 0, 0, 1));
std::copy(r.begin(), r.end(), &output.atX(0, 0, 0, 2));
std::copy(a.begin(), a.end(), &output.atX(0, 0, 0, 3));

This results in an output image like:

enter image description here