[编辑] 现在我可以分配像素数组来获取BMP图片的二维数组。
但我不知道如何计算该图片的红绿色或蓝色像素,因为它们需要3位来存储彩色RGB。
我正在尝试使用C来计算我的图片中有多少灰色像素。 我已经使用结构打开了BMP文件,可以读取bmp文件的所有细节,比如高度,宽度......
[编辑过的代码]
#include <stdio.h>
#include <stdlib.h>
#pragma pack(push) // push current alignment to stack
#pragma pack(1) // set alignment to 1 byte boundary
typedef struct
{
unsigned short int Type; /* Magic identifier */
unsigned int Size; /* File size in bytes */
unsigned short int Reserved1;
unsigned short int Reserved2;
unsigned int Offset; /* Offset to data (in B)*/
}HEADER; /* -- 14 Bytes -- */
typedef struct
{
unsigned int Size; /* Header size in bytes */
int Width;
int Height; /* Width / Height of image */
unsigned short int Planes; /* Number of colour planes */
unsigned short int Bits; /* Bits per pixel */
unsigned int Compression; /* Compression type */
unsigned int ImageSize; /* Image size in bytes */
int xResolution;
int yResolution;/* Pixels per meter */
unsigned int Colors; /* Number of colors */
unsigned int ImportantColors;/* Important colors */
}INFOHEADER; /* -- 40 Bytes -- */
typedef struct
{
unsigned char Red;
unsigned char Green;
unsigned char Blue;
}PIXEL;
#pragma pack(pop) // restore original alignment from stack
int main()
{
HEADER data;
INFOHEADER data2;
PIXEL pixel;
FILE *file;
file = fopen("lena512.bmp","rb");
fread(&data,sizeof(HEADER),1,file);
//read IB+NFOHEADER data into data2
fread(&data2,sizeof(INFOHEADER),1,file);
printf("Height: %d\n",data2.Height);
printf("Witdh: %d\n" ,data2.Width);
//Allocate space for pixelarray
PIXEL **pixelarray;
int r=0,c=0,rows=data2.Height,columns=data2.Width;
pixelarray= malloc(rows*sizeof(PIXEL *));
for(r=0; r<rows; r++)
{
pixelarray[r]=malloc(columns*sizeof(PIXEL));
}
//fill pixel array with pixel structs
int pixelnum=0;
for( r=0; r<rows; r++ )
{
for( c=0; c<columns; c++ ) // read pixel data from image
{
fread(&pixelarray[r][c].Red , 1, sizeof(PIXEL), file);
fread(&pixelarray[r][c].Green , 1, sizeof(PIXEL), file);
fread(&pixelarray[r][c].Blue , 1, sizeof(PIXEL), file);
if(pixelarray[r][c].Red=pixelarray[r][c].Green=pixelarray[r][c].Blue)
pixelnum++;
}
}
printf("Gray num: %d\n",pixelnum);
fclose(file); //close the files prior to exiting
}
[编辑] 这部分我在网上找到了,为什么他们把.Red放在二维阵列之后?
fread(&pixelarray[r][c].Red , 1, sizeof(PIXEL), file);
fread(&pixelarray[r][c].Green , 1, sizeof(PIXEL), file);
fread(&pixelarray[r][c].Blue , 1, sizeof(PIXEL), file);
但后来我不知道如何访问我的图像的颜色像素级别了。任何人都可以帮助我吗? 我想我应该再为像素制作一个结构,但正如我在论坛上发现的只有红色,绿色和蓝色但没有灰色值。很抱歉不知道任何事情......