我正在建立一个用于阅读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;
我做错了什么?
答案 0 :(得分:1)
阅读图片时可能存在问题:
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*
是指向无符号字符的指针,sizeof(unsigned char*)
将是指针的大小(可能是8个字节)。因此,读取图像,每次读取一行时都会读取8行。