C#图像灰度级拉伸的方法


本文实例讲述了C#图像灰度级拉伸的方法。分享给大家供大家参考。具体如下:

//定义图像灰度拉伸函数
private static Bitmap GrayLP (Bitmap a)
{
  Rectangle rect = new Rectangle(0, 0, a.Width, a.Height);
  System.Drawing.Imaging.BitmapData srcData = a.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, a.PixelFormat);
  IntPtr ptr = srcData.Scan0;
  int bytes = 0;
  if (a.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
  { bytes = a.Width * a.Height; }
  else { bytes = a.Width * a.Height * 3; }
  byte[] grayValues = new byte[bytes];
  System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
  byte n = 255, m = 0;
  double p;
  //计算最大和最小灰度级
  for (int i = 0; i < bytes; i++)
  {
   //计算最小灰度级
   if (n > grayValues[i])
   {
     n = grayValues[i];
   }        
   //计算最大灰度级
   if (m < grayValues[i])
   {
     m = grayValues[i];
   }
  }
  //得到斜率
  p = 255.0 / (m - n);
  //灰度拉伸
  for (int i = 0; i < bytes; i++)
  {
   grayValues[i] = (byte)(p * (grayValues[i] - n) + 0.5);
  }
  System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
  a.UnlockBits(srcData);
  return a;
}

希望本文所述对大家的C#程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3