2014-10-30 76 views
0

我一直在创建我自己的BMP阅读器在c和我设法读取头和HeaderInfo但当我读取图像数据到我的数组结构我得到错误的输出。 预期输出是10,我所得到的是20 这里是我的代码:阅读c中的BMP图像

#include<stdio.h> 
typedef struct 
{ 
    unsigned char Red; 
    unsigned char Green; 
    unsigned char Blue; 

} pixel; 
#pragma pack(2) /*2 byte packing */ 
typedef struct 
{ 
unsigned short int type; 
unsigned int size; 
unsigned short int reserved1,reserved2; 
unsigned int offset; 


}header; 


typedef struct 
{ 
    unsigned int size; 
    int width,height; 
    unsigned short int bits; 

    unsigned int compression; 
    unsigned int pixelsize; 
    int xresolution,yresolution; 
    unsigned int ncolors; 
    unsigned int importantcolors; 

}headerInfo; 

void main() 
{ 

    header head; 
    headerInfo headInfo; 
int counter=0; 
    FILE *leftpixel; 
    leftpixel = fopen("left.bmp","rb+"); 
    if(leftpixel==NULL) 
    { 
     printf("Error opening first file"); 

    } 


fread(&head,1,sizeof(head),leftpixel); 
printf("%x ",head.type); 
printf("%u ",head.size); 
printf("%u ",head.offset); 
printf("\n"); 
fread(&headInfo,1,sizeof(headInfo),leftpixel); 
printf("%d ",headInfo.width); 
printf("%d ",headInfo.height); 
printf("\n"); 

fseek(leftpixel,54,SEEK_SET); 
pixel im[480][640]; 

int i,j; 

      for (i = 0; i < 480; i++) { 
     for (j = 0; j < 640; j++) { 

      fread(&im[i][j], sizeof(unsigned char),headInfo.pixelsize, leftpixel); 
if(im[i][j].Red>(im[i][j].Green+im[i][j].Blue)) 
     { 
counter++; 

     }  
} 
} 




    printf("counter =%d ", counter); 

    printf("\n"); 

} 
+0

对于初学者,请检查'fread'返回的结果。请编辑问题以包含预期和实际输出。 – 2014-10-30 10:09:06

+3

BMP以BGR的方式存储像素。你正在计算蓝色像素。此外,BMP文件还会填充行数据,以便每行都具有可被4整除的像素数量。根据图像宽度的不同,这可能是个问题。 – 2014-10-30 10:11:12

+1

@omar请格式化您的代码。一团糟。 – 2014-10-30 10:23:05

回答

1

你永远不应该使用硬编码常数为fseek(leftpixel,54,SEEK_SET);从标题的bfOffBits字段提取对像素图的偏移量,在其他情况下使用文件头中的信息而不是猜测。在这个问题下,请阅读@ V-X的评论。