2014-10-30 77 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的評論。