1.创建一个对话框类CHistogramdlg,并在类定义一个指向int指针(Imagedata),用于传入统计好的灰度分布数据,一般存储在256的数组中。
2.重载对话框类的OnPaint,并添加代码如下:
void CHistogramdlg::OnPaint()
{
CPaintDC dc(this);
CPen* pPenBlue = new CPen; //创建画笔对象
pPenBlue->CreatePen(PS_SOLID, 2, RGB(0,0,255)); //蓝色画笔
CPen* pPenBlack = new CPen; //创建画笔对象
pPenBlack->CreatePen(PS_SOLID, 1, RGB(0,0,0)); //黑色画笔
//选中黑色画笔,并保存当前画笔
CGdiObject* pOldPen = dc.SelectObject(pPenBlack);
int i = 0;
CString str;
//绘制坐标系
CPoint OPos(40,500),NowPos;
//绘制x坐标轴
dc.MoveTo(OPos);
NowPos.x = 565;
NowPos.y = 500;
dc.LineTo(NowPos);
//绘制箭头
dc.LineTo(560,495);
dc.MoveTo(NowPos);
dc.LineTo(560,505);
//绘制x轴坐标系数
for (i = 0;i != 257;i++)
{
if (i % 10 == 0)
{
dc.MoveTo(OPos.x + 2 * i,OPos.y);
dc.LineTo(CPoint(OPos.x + 2 * i,OPos.y - 5));
}
if (i % 20 == 0)
{
str.Format("%d",i);
dc.TextOut(OPos.x + 2 * i,OPos.y + 1,str);
}
}
//绘制y轴坐标系数
dc.MoveTo(OPos);
NowPos.x = OPos.x;
NowPos.y = 0;
dc.LineTo(NowPos);
//绘制箭头
dc.LineTo(NowPos.x - 5,NowPos.y + 5);
dc.MoveTo(NowPos);
dc.LineTo(NowPos.x + 5,NowPos.y + 5);
//寻找数据数组最大的数据
int max = 0;
for (i = 0;i != 256;i++)
{
if (max < ImagData[i])
{
max = ImagData[i];
}
}
//y轴坐标系数的数据步长
int Tstep = max / 10;
//y轴坐标系数的刻度步长
int Ystep = 500 / 21;
//显示y坐标的刻度和数据
for (i = 1;i != 22;i++)
{
dc.MoveTo(OPos.x,OPos.y - Ystep * i );
dc.LineTo(CPoint(OPos.x + 5,OPos.y - Ystep * i));
if (i % 2 == 0)
{
str.Format("%d",Tstep * i / 2);
dc.TextOut(0,OPos.y - Ystep * i - 10,str);
}
}
//绘制灰度图像的直方图
dc.SelectObject(pPenBlue); //选择蓝色画笔
for (i = 0;i != 256;i++)
{
NowPos.x = OPos.x + (2 * i);
NowPos.y = OPos.y;
dc.MoveTo(NowPos);
NowPos.y = 500 - 500.0f * 20.0f * ImagData[i] / (max * 21);
dc.LineTo(NowPos);
}
//恢复以前的画笔
dc.SelectObject(pOldPen);
delete pPenBlue;
delete pPenBlack;
}
3 把CHistogramdlg.h头文件加入单文档doc的头文件中
4在单文档中菜单中添加直方图菜单,并添加消息函数,具体代码如下:
//判断图像是否为灰度图像
if (GrayImage == NULL)
{
MessageBox(NULL,"请先把图像转换为灰度图像","操作提示",MB_OK);
return ;
}
int step = GrayImage->widthStep / sizeof(uchar);
uchar *data = (uchar *)GrayImage->imageData;
int HistData[256],i = 0,j = 0;
for (j = 0;j != 256;j++)
{
HistData[j] = 0;
}
for (i = 0;i != GrayImage->height;i++)
{
for (j = 0;j != GrayImage->width;j++)
{
HistData[data[i * step + j]]++;
}
}
CHistogramdlg dlg;
dlg.ImagData = HistData;
if (dlg.DoModal() != IDOK)
{
return;
}
delete dlg;
5运行结果: