我正在尝试在 C 程序中编写 PGM 文件,但是一旦编写完毕,如果我尝试打开它来查看图像,我会被告知无法确定图像文件格式。

但是,如果我在 geany 中创建一个新文件,复制数据,然后将其另存为新的 PGM,它就可以工作。

知道为什么会这样吗?

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");
}

我正在将彩色图像转换为灰度图像。

有帮助吗?

解决方案

我认为你不应该使用 \r\n 作为行分隔符,但仅 \n. 。另外,请检查所有行的长度是否超过 70 个字符。由于每个像素最多需要 4 个字符(3 个加上空格)插入 \n 每 17 个像素之后。您可以用注释分隔实际行(例如:

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

其他提示

查看您的代码,我看一下,我看到了每个世代odicetagcode元素的new line。根据PGM文件格式,标题之后,请按照

  • 栅格的高度行,从上到下。每行由宽度灰度值组成,按左向右排列。

    但是你正在写一行高度元素。因此,您可能以错误的方式访问数据。实际上,尝试调试(用铅笔)3列(宽度)和4行(高度)的图像。

    表示,更改循环以在行主要订单中写入数据:

    // 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");
    }
    
    .

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top