如何在C中正确读取PGM图像

时间:2016-03-04 13:51:35

标签: c p2 pgm

我来这里问你一点帮助。我想编写一个读取PGM文件(P2,而不是二进制文件)的C代码,并且我已经找到了很多方法可以在Web上完成。问题是,每当我尝试读取我在PC上作为示例的一些PGM图像时,我甚至无法正确读取标题,因为它从未识别出正确的P2 PGM格式。我总是得到如下错误:"无效的pgm文件类型"或"格式不受支持"。这是我尝试的(最后)代码:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    typedef struct pgm {
      int w;
      int h;
      int max;
      int* pData;
    } pgm;


    int main(int argc, char * argv[]){

      char* filename = argv[0];
      pgm* pPgm;
      FILE* ifp;
      int word;
      int nRead = 0;
      char readChars[256];

      //open the file, check if successful
      ifp = fopen( filename, "r" );
      if (!ifp) {
        printf("Error: Unable to open file %s.\n\n", filename);
        exit(1);
      }

      pPgm = (pgm *) malloc (sizeof(pgm));

      //read headers from file
      printf ("Reading PGM file: %s...\n", filename);
      fscanf (ifp, "%s", readChars);

      if (strcmp(readChars, "P2") == 0) {
        //valid file type
        //get a word from the file
        printf("VALID TYPE.\n");
        fscanf (ifp, "%s", readChars);
        while (readChars[0] == '#') {
          //if a comment, get the rest of the line and a new word
          fgets (readChars, 255, ifp);
          fscanf (ifp, "%s", readChars);
        }

        //ok, comments are gone
        //get width, height, color depth
        sscanf (readChars, "%d", &pPgm->w);
        fscanf (ifp, "%d", &pPgm->h);
        fscanf (ifp, "%d", &pPgm->max);
        printf("WIDTH: %d, HEIGHT: %d\n", pPgm->w, pPgm->h);

        // allocate some memory, note that on the HandyBoard you want to 
        // use constant memory and NOT use calloc/malloc
        pPgm->pData = (int*)malloc(sizeof(int) * pPgm->w * pPgm->h);

        // now read in the image data itself    
        for (nRead = 0; nRead < pPgm->w * pPgm->h; nRead++) {
          fscanf(ifp, "%d" ,&word);
          pPgm->pData[nRead] = word;
          // printf("nRead = %d %d\n",nRead,pPgm->pData[nRead]);
        }

        printf ("Loaded PGM. Size: %dx%d, Greyscale: %d \n", 
        pPgm->w, pPgm->h, pPgm->max + 1);
      }
      else {
        printf ("Error: %s. Format unsupported.\n\n", readChars);
        exit(1);
      }
      fclose(ifp);

      return 0;
    }

1 个答案:

答案 0 :(得分:0)

似乎有些库可以执行此操作:来自netpbmPGMA_IO的libnetpbm。如果由于某种原因无法使用外部库,那么查看源代码可以帮助您弄清楚如何读取标头。顺便问一下,您是否已经看过这个问题的答案:how-to-read-a-pgm-image-file-in-a-2d-double-array-in-c