原文:Win8Metro(C#)数字图像处理--2.31灰度拉伸算法
[函数名称]
灰度拉伸函数GrayStretchProcess(WriteableBitmap src)
[算法说明]
直方图灰度拉伸也叫做对比度拉伸,是一种特殊的线性点运算,使用的是分段线性变换函数,它的主要思想是提高图像灰度级的动态范围;它的作用是扩展图像的直方图,使其充满整个灰度等级的范围内,从而改善输出图像。
如图Fig.1所示,变换函数的运算结果是将原图在a-b之间的灰度级拉伸到c-d之间。如果一幅图像的灰度级集中在较暗的区域从而导致图像偏暗,或者一幅图像的灰度级集中在较亮的区域从而导致图像偏亮,则可以使用灰度拉伸来改善图像质量。
[函数代码]
/// <summary>
/// Gray stretch process.
/// </summary>
/// <param name="src">The source image.</param>
/// <returns></returns>
public static WriteableBitmap GrayStretchProcess(WriteableBitmap src)////31图像灰度拉伸
{
if (src != null)
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap grayStretchImage = new WriteableBitmap(w, h);
byte[] temp = src.PixelBuffer.ToArray();
int min = 0;
int max = 0;
int gray = 0;
int res = 0;
for (int i = 0; i < temp.Length; i += 4)
{
gray = (int)(temp[i] * 0.114 + temp[i + 1] * 0.587 + temp[i + 2] * 0.299);
min = min < gray ? min : gray;
max = max > gray ? max : gray;
}
for (int i = 0; i < temp.Length; i += 4)
{
gray = (int)(temp[i] * 0.114 + temp[i + 1] * 0.587 + temp[i + 2] * 0.299);
res = (255 / (max - min)) * (gray - min);
temp[i] = (byte)res;
temp[i + 1] = (byte)res;
temp[i + 2] = (byte)res;
}
Stream sTemp = grayStretchImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return grayStretchImage;
}
else
{
return null;
}
}