灰度直方图是灰度的函数,描述的是图像中具有该灰度级的像素的个数。如果用直角坐标系来表示,则它的横坐标是灰度级,纵坐标是该灰度出现的概率(像素的个数)。

c#数字图像处理(三)灰度直方图-LMLPHP

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace histogram
{
public partial class histForm : Form
{
//利用构造函数实现窗体之间的数据传递
public histForm(Bitmap bmp)
{
InitializeComponent(); //把主窗体的图像数据传递给从窗体
bmpHist = bmp;
//灰度级计数
countPixel = new int[]; //8位可表示256个灰度级
} private void close_Click(object sender, EventArgs e)
{
this.Close();
} //图像数据
private System.Drawing.Bitmap bmpHist;
//灰度等级
private int[] countPixel;
//记录最大的灰度级个数
private int maxPixel; /// <summary>
/// 计算各个灰度级所具有的像素个数
/// </summary>
private void histForm_Load(object sender, EventArgs e)
{
//锁定8位灰度位图
Rectangle rect = new Rectangle(, , bmpHist.Width, bmpHist.Height);
System.Drawing.Imaging.BitmapData bmpData = bmpHist.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpHist.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpHist.Width * bmpHist.Height;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, , bytes);//灰度值数据存入grayValues中 byte temp = ;
maxPixel = ;
//灰度等级数组清零
Array.Clear(countPixel, , );
//计算各个灰度级的像素个数
for (int i = ; i < bytes; i++)
{
//灰度级
temp = grayValues[i];
//计数加1
countPixel[temp]++;
if (countPixel[temp] > maxPixel)
{
//找到灰度频率最大的像素数,用于绘制直方图
maxPixel = countPixel[temp];
}
} //解锁
System.Runtime.InteropServices.Marshal.Copy(grayValues, , ptr, bytes);
bmpHist.UnlockBits(bmpData);
} /// <summary>
/// 绘制直方图
/// </summary>
private void histForm_Paint(object sender, PaintEventArgs e)
{
//获取Graphics对象
Graphics g = e.Graphics; //创建一个宽度为1的黑色钢笔
Pen curPen = new Pen(Brushes.Black, ); //绘制坐标轴
g.DrawLine(curPen, , , , );//横坐标
g.DrawLine(curPen, , , , );//纵坐标 //绘制并标识坐标刻度
g.DrawLine(curPen, , , , );
g.DrawLine(curPen, , , , );
g.DrawLine(curPen, , , , );
g.DrawLine(curPen, , , , );
g.DrawLine(curPen, , , , );
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(,));
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawLine(curPen, , , , );
g.DrawString("", new Font("New Timer", ), Brushes.Black, new PointF(, ));
g.DrawString(maxPixel.ToString(), new Font("New Timer", ), Brushes.Black, new PointF(, )); //绘制直方图
double temp = ;
for (int i = ; i < ; i++)
{
//纵坐标长度
temp = 200.0 * countPixel[i] / maxPixel;
g.DrawLine(curPen, + i, , + i, - (int)temp);
}
//释放对象
curPen.Dispose();
}
}
}

c#数字图像处理(三)灰度直方图-LMLPHP

05-11 19:46