C#图像灰度级拉伸的方法
本文实例讲述了C#图像灰度级拉伸的方法。分享给大家供大家参考。具体如下:
//定义图像灰度拉伸函数 privatestaticBitmapGrayLP(Bitmapa) { Rectanglerect=newRectangle(0,0,a.Width,a.Height); System.Drawing.Imaging.BitmapDatasrcData=a.LockBits(rect,System.Drawing.Imaging.ImageLockMode.ReadWrite,a.PixelFormat); IntPtrptr=srcData.Scan0; intbytes=0; if(a.PixelFormat==System.Drawing.Imaging.PixelFormat.Format8bppIndexed) {bytes=a.Width*a.Height;} else{bytes=a.Width*a.Height*3;} byte[]grayValues=newbyte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr,grayValues,0,bytes); byten=255,m=0; doublep; //计算最大和最小灰度级 for(inti=0;i<bytes;i++) { //计算最小灰度级 if(n>grayValues[i]) { n=grayValues[i]; } //计算最大灰度级 if(m<grayValues[i]) { m=grayValues[i]; } } //得到斜率 p=255.0/(m-n); //灰度拉伸 for(inti=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); returna; }
希望本文所述对大家的C#程序设计有所帮助。