c - 在c中读取bmp图像

标签 c image-processing bmp

我一直致力于用 c 创建我自己的 BMP 阅读器,并且我设法读取了 Header 和 HeaderInfo,但是当我将图像数据读取到我的结构数组时,我得到了错误的输出。 预期输出是 10,我得到的是 20。 这是我的代码:

#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");

}  

最佳答案

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

关于c - 在c中读取bmp图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26650047/

相关文章:

python - OpenCV:检测区域是直的还是弯曲的

图像相似度检测

c++ - 我尝试用 C++ 编写一个 bmp 文件,但是 bmp 文件的宽度和高度似乎会影响结果,有时我会得到一个错误的 bmp 文件

c++ - 读取 BMP 文件 - 从 C/C++ 中获取数据

java - #define 中的 JNA 宏函数

c - 为什么当声明一个动态变量时,保留的比指定的多

c++ - 在 C++ 中调整卷文件的长度和宽度

c - bmp 文件处理

c++ - 为什么要比较 Unsigned Int >= 0 a "Pointless Comparison"?

C错误寻找最大素数