java c 图像_用C读取PGM图像

博客中描述了在C语言中读取PGM图像时遇到的问题,代码未能正确解析图像数据,导致所有像素值显示为205。作者提供了正确的代码实现,修正了文件读取和图像数据解析的错误,使得代码能够正确读取和显示图像的原始像素值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在尝试使用以下功能读取PGM图像:

typedef struct PGMImage{

int w;

int h;

unsigned char* data;

}GrayImage;

void ReadPGMImage(char* filename,GrayImage* image)

{

int width,height,size,binary,i,j;

FILE *fp = fopen(filename, "r");

if(!fp){

fprintf(stderr,"Unable to open file in 'r' mode");

exit(errno);

}

readPNMHeader(fp, &width, &height,&binary);

size = width * height;

*image = CreateGrayImage(width,height);

if (!(image->data)){

fprintf(stderr,"Memory not allocated");

exit(errno);

}

fread((void *)image->data, sizeof(unsigned char), (size_t) size, fp);

fclose(fp);

return;

}

我试图读取的图像有这些 Headers :P2 640 480 255

当我打印出某些像素的值(行:400-410,列:300-310)时,将为所有像素打印“205”,而根据Matlab的实际值为:

>248 255 255 250 254 254 254 252 252 255

>255 255 255 255 255 255 255 255 255 255

>255 255 255 255 255 255 255 255 255 255

>255 255 255 255 255 255 255 255 255 255

>255 255 255 255 255 255 255 255 255 255

>248 247 249 245 251 252 253 252 245 251

>241 240 243 237 240 244 239 242 243 244

>235 238 238 237 239 238 239 238 240 242

>236 233 241 235 236 234 236 239 235 237

>231 239 231 239 234 234 230 233 233 234

当我读取PPM图像时,类似的代码也有效 . 有人能告诉我哪里出错了吗?

编辑:有效的最终代码:

void ReadPGMImage(char * fileName, GrayImage* image) {

FILE * fp = NULL;

char version[100];

int levels = 0;

unsigned int w = 0, h = 0;

unsigned int i = 0;

int pixdat = 0;

if( fileName == NULL ) {

fprintf(stderr,"Bad file name=%s\n", fileName );

return;

}

fp = fopen(fileName,"rb");

if( fp == NULL ) {

fprintf(stderr,"Cannot open file = %s\n", fileName );

return;

}

fscanf(fp,"%s",version);

SkipComments(fp);

fscanf(fp, "%d", &w);

SkipComments(fp);

fscanf(fp, "%d", &h);

SkipComments(fp);

fscanf(fp, "%d", &levels);

CreateGrayImage(image,w,h);

image->w = w;

image->h = h;

for(i=0;i

fscanf(fp, "%d", &pixdat);

image->data[i] = pixdat;

}

fclose(fp);

return;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值