[英]How to read a PGM image properly in C
我在這里問你一點幫助。 我想編寫一個讀取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;
}
似乎有些庫可以執行此操作: netpbm或PGMA_IO的libnetpbm 。 如果由於某種原因無法使用外部庫,那么查看源代碼可能會幫助您弄清楚如何讀取標頭。 順便說一句,您是否已經看過以下問題的答案: 如何在c中讀取一個pgm圖像文件在2d雙數組中 ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.