gpt4 book ai didi

c - 在 C 上读取二进制 PGM

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:33 25 4
gpt4 key购买 nike

我正在制作一个用于读取 PGM 文件的库,但我遇到了这个问题。

我的代码无法正确读取二进制 PGM 图像,看起来它读取了错误的值,从而生成了只有“噪声”的图像

代码非常简单:

void OpenPGM(PGMImage* pgm, const char* file){
FILE *pgmfile = fopen (file, "rb");

fscanf (pgmfile, "%s", pgm->magicNumber);
fscanf (pgmfile, "%d %d", &(pgm->width),&(pgm->height));
fscanf (pgmfile, "%d", &(pgm->maxValue));

pgm->data = malloc(pgm->height * sizeof(unsigned char*));

if (pgm->magicNumber[1] == '2')
{
for (int i = 0; i < pgm->height; ++i)
{
pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
for (int j = 0; j < pgm->width; ++j)
fscanf (pgmfile, "%d", &pgm->data[i][j]);
}
} else {
fgetc(pgmfile);// this should eat the last \n
for (int i = 0; i < pgm->height; ++i)
{
pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
fread(pgm->data[i],sizeof(unsigned char*),pgm->width,pgmfile);//reading line by line
}
}
}

PGMImage 看起来像这样

typedef struct PGMImage {
char magicNumber[2];
unsigned char** data;
unsigned int width;
unsigned int height;
unsigned int maxValue;
} PGMImage;

我做错了什么?

最佳答案

阅读图片时可能会出现问题:

pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
fread(pgm->data[i],sizeof(unsigned char*),pgm->width,pgmfile);//reading line by line

应该是:

pgm->data[i] = malloc(pgm->width * sizeof(unsigned char));
if(pgm->data[i]==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
fread(pgm->data[i],sizeof(unsigned char),pgm->width,pgmfile);//reading line by line

事实上,unsigned char* 是指向 unsigned char 的指针,而 sizeof(unsigned char*) 将是指针的大小(可能是 8 个字节)。因此,读取图像时,每次读取一行时都会读取 8 行。

关于c - 在 C 上读取二进制 PGM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39672372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com