程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 如何使用C#繪制數字圖像灰度直方圖

如何使用C#繪制數字圖像灰度直方圖

編輯:關於C#

灰度直方圖是灰度的函數,描述的是圖像中具有該灰度級的像素的個數。如果用直角坐標系來表示 ,則它的橫坐標是灰度級,縱坐標是該灰度出現的概率(像素的個數)。

灰度直方圖的分布函數:

其中,K是指第k個灰度級,如果是8位灰度圖像,k=0、1、 ……、255。

處理圖像生成直方圖數據

//將圖像數據復制到byte中
Rectangle rect = new Rectangle(0, 0, 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 * 3;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
     
//統計直方圖信息
byte temp = 0;
maxPixel = 0;
Array.Clear(countPixel, 0, 256);
for (int i = 0; i < bytes; i++)
{
    temp = grayValues[i];
    countPixel[temp]++;
    if (countPixel[temp] > maxPixel)
    {
        maxPixel = countPixel[temp];
    }
}
     
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
bmpHist.UnlockBits(bmpdata);

繪制直方圖信息

//畫出坐標系
Graphics g = e.Graphics;
Pen curPen = new Pen(Brushes.Black, 1);
     
g.DrawLine(curPen, 50, 240, 320, 240);
g.DrawLine(curPen, 50, 240, 50, 30);
g.DrawLine(curPen, 100, 240, 100, 242);
g.DrawLine(curPen, 150, 240, 150, 242);
g.DrawLine(curPen, 200, 240, 200, 242);
g.DrawLine(curPen, 250, 240, 250, 242);
g.DrawLine(curPen, 300, 240, 300, 242);
g.DrawString("0", new Font("New Timer", 8), Brushes.Black, new PointF(46, 242));
g.DrawString("50", new Font("New Timer", 8), Brushes.Black, new PointF(92, 242));
g.DrawString("100", new Font("New Timer", 8), Brushes.Black, new PointF(139, 242));
g.DrawString("150", new Font("New Timer", 8), Brushes.Black, new PointF(189, 242));
g.DrawString("200", new Font("New Timer", 8), Brushes.Black, new PointF(239, 242));
g.DrawString("250", new Font("New Timer", 8), Brushes.Black, new PointF(289, 242));
g.DrawLine(curPen, 48, 40, 50, 40);
g.DrawString("0", new Font("New Timer", 8), Brushes.Black, new PointF(34, 234));
g.DrawString(maxPixel.ToString(), new Font("New Timer", 8), Brushes.Black, new PointF(18, 34));
     
double temp = 0;
for (int i = 0; i < 256; i++)
{
    temp = 200.0 * countPixel[i] / maxPixel;
    g.DrawLine(curPen, 50 + i, 240, 50 + i, 240 - (int)temp);
}
     
curPen.Dispose();

全局變量定義及賦值

private System.Drawing.Bitmap bmpHist;
private int[] countPixel;
private int maxPixel;
     
public Grey_ScaleMapForm(Bitmap bmp)
{
    InitializeComponent();
    bmpHist = bmp;
    countPixel = new int[256];
}

下載:DEMO

http://files.cnblogs.com/zxlovenet/Grey-ScaleMap.rar

查看本欄目

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved