C#图像灰度级拉伸的方法
程序员文章站
2023-01-22 12:27:24
本文实例讲述了c#图像灰度级拉伸的方法。分享给大家供大家参考。具体如下:
//定义图像灰度拉伸函数
private static bitmap graylp (...
本文实例讲述了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#程序设计有所帮助。