c++image-processingpbm

Generating .pfm image in c++


I have a small program that outputs an rgb image. And I need it to be in .pfm format.

So, I have some data in the range [0, 255].

float * data;
data = new float[PixelWidth * PixelHeight * 3];
for (int i = 0; i < PixelWidth * PixelHeight * 3; i += 3) {
    int idx = i / 3;
    data[i] = img[idx].x;
    data[i + 1] = img[idx].y;
    data[i + 2] = img[idx].z;
}

(img[] here is Vec3[] of unsigned char)

Now I generate the image.

char sizes[256];
f = fopen("outputimage.pfm", "wb");
double scale = -1.0;
fprintf(f, "PF\n%d %d\n%lf\n", PixelWidth, PixelHeight, scale);
for (int i = 0; i < PixelWidth*PixelHeight*3; i++) {
    float d = data[i];
    fwrite((void *)&d, 1, 4, f);
}
fclose(f);

But somehow I get a grayscale image instead of RGB.

The data is fine. I tried to output it as .ppm and it works fine.

I guess the problem is with scaling, but I am not really sure how it should be done correctly.


Solution

  • To close the question.

    I just had to convert all the values from [0-255] range to [0.0-1.0]. So, I divided each rgb value by 255.