简体   繁体   English

用C编写PGM文件不起作用

[英]Writing PGM file in C doesn't work

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. 我正在尝试在C程序中编写PGM文件,但是一旦写入,如果我尝试打开它来查看图像,我被告知图像文件格式无法确定。

However, if I create a new file in geany, copy the data over, and then save THAT as a new PGM, it works. 但是,如果我在geany中创建一个新文件,复制数据,然后将其保存为新的PGM,它就可以工作。

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. 我正在将彩色图像转换为灰度图像。

Looking at your code, I see that you insert a new line every height elements. 查看代码,我看到每个height元素都插入一个new line According with the PGM file format, after the header, follows 根据PGM文件格式,在标题之后,如下

  • 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). 实际上,尝试调试(使用铅笔)3列(宽度)和4行(高度)的图像。

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

I think you should not use \\r\\n as a line delimiter, but only \\n . 我认为你不应该使用\\r\\n作为行分隔符,而只能使用\\n Also, check that no line has above 70 characters in length. 另外,检查没有行的长度超过70个字符。 Since each pixel needs at most 4 characters (3 plus space) insert \\n after every 17 pixels. 由于每个像素最多需要4个字符(3个空格),因此每17个像素后插入\\n You can separate real lines with comments (for example: 您可以使用注释分隔实际行(例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM