Question

I am trying to write a PGM file in a C program, but once it is written, if I try to open it to view the image I am told the image file format can't be determined.

However, if I create a new file in geany, copy the data over, and then save THAT as a new PGM, it works.

Any idea why this could be?

FILE * grey = fopen("greyscale.pgm", "w");

fprintf(grey, "P2 \r\n%d %d \r\n255 \r\n", width, height);

for (i = 0; i < width; i++) {
    for (j = 0; j < height; j++) {
        fprintf(grey, "%d ", ((imageArray[i][j].red + imageArray[i][j].green + imageArray[i][j].blue)/3));
    }
    fprintf(grey, "\r\n");
}

I am converting a colour image to greyscale.

Was it helpful?

Solution

I think you should not use \r\n as a line delimiter, but only \n. Also, check that no line has above 70 characters in length. Since each pixel needs at most 4 characters (3 plus space) insert \n after every 17 pixels. You can separate real lines with comments (for example:

pixel11 pixel12 pixel13
pixel14 pixel15
# switch to next row
pixel21 pixel22 pixel23
pixel24 pixel25
# etc.

OTHER TIPS

Looking at your code, I see that you insert a new line every height elements. According with the PGM file format, after the header, follows

  • A raster of Height rows, in order from top to bottom. Each row consists of Width gray values, in order from left to right.

But your are writing a row of height element. So, your are probably accessing data in a wrong way. In fact, try to debug (with a pencil) an image of 3 columns (width) and 4 rows (height).

Said that, change your loop to write data in row-major order:

// write data to file
int row, col;
for (row = 0; row < height; ++row)
{
    for (col = 0; col < width; ++col)
    {
        fprintf(grey, "%d ", (imageArray[row][col].red + imageArray[row][col].green + imageArray[row][col].blue)/3));
    }
    fprintf(grey, "\n\r");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top