【发布时间】:2014-12-26 07:40:48
【问题描述】:
我一直致力于在 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");
}
【问题讨论】:
-
对于初学者,请检查
fread返回的内容。请编辑问题以包含预期和实际输出。 -
BMP 以相反的方式将像素存储为 BGR。您正在计算蓝色像素。此外,BMP 文件在行数据之后有填充,因此每行都有许多可以被 4 整除的像素。根据您的图像宽度,这可能是个问题。
-
@omar 请格式化您的代码。真是一团糟。
-
您好,感谢您的回复,并为凌乱的代码感到抱歉,但我想我解决了我的问题。
-
祈祷没有遇到任何24位色深以外的位图:)
标签: c image-processing bmp