c++matlabimage-processingtextpgm

How are these PGM files encoded?


I exported a grayscale image as PGM using MATLAB (and OpenCV) and got this file as an output.

    im = imread(src);
    im = rgb2gray(im);
    imwrite(im, dst);

According to the PGM Specification the header contains the "magic number", the width, the height, and the max value of the image.

But below the header, there should be a matrix of grayscale intensity values written in plaintext. But as you can see in the pasted file, I just get some kind of junk out (although it's a completely valid, viewable image)

I want to be able to read in the PGM files and access the individual intensity values as integers using a C/C++ program but I don't know how to interpret this output since it doesn't follow the spec. Perhaps the text encoding is different?

Thanks for any assistance.


Solution

  • You're misreading the spec.

    Each gray value is represented in pure binary by either 1 or 2 bytes. If the Maxval is less than 256, it is 1 byte. Otherwise, it is 2 bytes. The most significant byte is first.

    So each pixel is either one or two bytes (depending on the Maxval) and in binary, not ASCII.