【问题标题】:Reading binary PGM on C在 C 上读取二进制 PGM
【发布时间】:2016-09-24 04:06:47
【问题描述】:

我正在制作一个用于读取 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;

我做错了什么?

【问题讨论】:

    标签: c binary pgm


    【解决方案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 行。

    【讨论】:

    • 哇,你完全正确。该死的,指针很棘手。但即使进行了此修复,它仍然无法正常工作,图像仍然很嘈杂。我将用更多信息编辑我的帖子。
    • 好的,现在问题很容易找到。我在图片上打印了原始的幻数,但读取后的信息总是以 ASCII 格式打印,所以它总是应该是 P2。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2011-09-03
    • 2016-01-15
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多