gpt4 book ai didi

c - 在 C 中读取 PGM 图像(未正确读取文件)

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:49 25 4
gpt4 key购买 nike

我正在使用文件,pgm.cpgm.h读取 PGM 图像文件,然后我的程序将处理该文件(灰度、旋转等)。

但是,我无法正确读取文件。当我使用时:

   PGMImage* img = (PGMImage*)malloc(sizeof(PGMImage));
char iName1[256];
printf("Enter the filename of your PGM image:\n");
scanf("%s", iName1);
getPGMfile(iName1, &img);

控制台返回图片的类型、宽高和最大值。但是,宽度永远不会正确。无论我使用的是在网上找到的 .pgm 文件还是我自己制作的文件,它通常为 0(有一次是 56,距离很远)。我什至尝试过对图像的宽度进行硬编码,但即便如此,它也会导致程序崩溃。宽度应在 pgm.c 中的 getPGMfile 函数下读取:

void getPGMfile (char filename[], PGMImage *img)
{
FILE *in_file;
char ch;
int row, col, type;
int ch_int;

in_file = fopen(filename, "r");
if (in_file == NULL)
{
fprintf(stderr, "Error: Unable to open file %s\n\n", filename);
exit(8);
}

printf("\nReading image file: %s\n", filename);

/*determine pgm image type (only type three can be used)*/
ch = getc(in_file);
if(ch != 'P')
{
printf("ERROR(1): Not valid pgm/ppm file type\n");
exit(1);
}
ch = getc(in_file);
/*convert the one digit integer currently represented as a character to
an integer(48 == '0')*/
type = ch - 48;
printf("Type: %d", type);
if((type != 2) && (type != 3) && (type != 5) && (type != 6))
{
printf("ERROR(2): Not valid pgm/ppm file type\n");
exit(1);
}

while(getc(in_file) != '\n'); /* skip to end of line*/

while (getc(in_file) == '#') /* skip comment lines */
{
while (getc(in_file) != '\n'); /* skip to end of comment line */
}

/*there seems to be a difference between color and b/w. This line is needed
by b/w but doesn't effect color reading...*/
fseek(in_file, -1, SEEK_CUR); /* backup one character*/

fscanf(in_file,"%d", &((*img).width));
fscanf(in_file,"%d", &((*img).height));
fscanf(in_file,"%d", &((*img).maxVal));

//I omitted the rest, but it can be seen in the link above

我不知道是什么导致了这些错误。我在 Windows 7(64 位)上使用 Eclipse 和 MinGW GCC。我的导师无法帮助我解决这个问题,所以我希望你能! :)

总结:PGM 图像的宽度总是被错误读取,之后对该文件所做的任何操作都会导致可执行文件停止工作。对宽度进行硬编码还会导致可执行文件停止工作。

最佳答案

getpgm 不应传递指针的地址,而应仅传递根据头文件的指针:getPGMfile(iName1, img)

关于c - 在 C 中读取 PGM 图像(未正确读取文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843899/

25 4 0
文章推荐: c++ - 链表结构推送和弹出
文章推荐: c - 如何跟踪这个堆栈和指针
文章推荐: c - i2c_msg.buf 的大小可以有多大?
文章推荐: html - 使用单指手势滚动 元素 - IPAD 不工作