C++读取bmp图片记录像素灰度画直方图

windsnowtree 2010-04-12 09:31:19
我现在读取了一个bmp图片,已经成功读取,现在我想统计各个像素的灰度信息,然后利用这些信息生成一幅bmp图片,显示直方图,我是这么写的
bool hist( char * histName , unsigned char *imgBuf , int width , int height , int BitCount )
{
int colorTablesize = 1024;
int bit = 8;
double percent = 0;
RGBQUAD * pColorTable = new RGBQUAD[256];

int lineByte_1 = (width * BitCount / 8 + 3)/4 * 4;
int lineByte_2 = (256* bit /8 + 3)/4 * 4;

//打开要存储的文件
FILE * pHist = fopen(histName , "wb");
if( pHist == 0)
return 0;
//统计每个灰度值的像素的个数
int grayCount[256];
for(int a = 0; a < 256 ;a++)
grayCount[a] = 0;
for( int i = 0; i < height ; i++)
{
for(int j = 0 ; j < width ; j++)
{
int grayValue = * (imgBuf + i * lineByte_1 + j);
grayCount[grayValue]++;
}
}



unsigned char * pHistBuf;
pHistBuf = new unsigned char[lineByte_2 * 100];
//将直方图所有像素置为白色
for(int d = 0 ; d<100 ;d ++)
{
for(int e = 0 ; e < 256 ; e++)
{
* (pHistBuf + lineByte_2 *d +e) = 0;
}
}
//绘制直方图
for( int k =0 ;k < 256 ; k++)
{
percent = double(grayCount[k]) / (width * height);

percent = percent * 10000;
int temp = percent;
cout<<temp<<endl;
for(int m = 0;(m<percent && m<100 );m++)
{
*( pHistBuf + lineByte_2 * m + k) = 100;
}

}

//写入文件头
BITMAPFILEHEADER histFileHead;
histFileHead.bfType = 0x4D42;
histFileHead.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTablesize + lineByte_2 *100;
histFileHead.bfReserved1 = 0;
histFileHead.bfReserved2 = 0;
histFileHead.bfOffBits = 54 + colorTablesize;

fwrite( &histFileHead , sizeof(BITMAPFILEHEADER) , 1 , pHist);
//写入信息头
BITMAPINFOHEADER histInfoHead;
histInfoHead.biBitCount = bit;
histInfoHead.biClrImportant = 0;
histInfoHead.biClrUsed = 0;
histInfoHead.biCompression = 0;
histInfoHead.biHeight =100;
histInfoHead.biPlanes = 1;
histInfoHead.biSize = 40;
histInfoHead.biSizeImage = lineByte_2 *100;
histInfoHead.biWidth = 256;
histInfoHead.biXPelsPerMeter = 0;
histInfoHead.biYPelsPerMeter = 0;

fwrite( &histInfoHead, sizeof(BITMAPINFOHEADER) , 1 , pHist);
//写入颜色表
fwrite( pColorTable , sizeof(RGBQUAD) , 256 , pHist);
//写入数据信息
fwrite(pHistBuf , 1 , 100 * lineByte_2 , pHist);

delete []pColorTable;
delete []pHistBuf;
fclose(pHist);

return 1;
}

但是不好使,就生成了一个100*256的空白图片,请问怎么回事,我该怎么改(//将直方图所有像素置为白色, //绘制直方图,就是这两步)


还有就是我申请的存储数据的变量是:unsigned char * pHistBuf;
pHistBuf = new unsigned char[lineByte_2 * 100];
我是看一本书上是这么申请的,用char,我想问问能不能用int啊,这个存储的不就是灰度值么
...全文
1174 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
windsnowtree 2010-04-13
  • 打赏
  • 举报
回复
有高手明白的么 ,麻烦解答一下,顶了
ameyume 2010-04-12
  • 打赏
  • 举报
回复
帮顶!期待高手

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧