Win8MetroC#数字图像处理--2.1图像灰度化
原文:Win8MetroC#数字图像处理--2.1图像灰度化
[函数说明]
图像灰度化函数GrayProcess(WriteableBitmap src)
[算法说明]
图像灰度化就是去掉彩色图像的彩色信息。对于一张图像,其中的每一个像素都
存在B,G,R三个颜色分量(这里不考虑透明度分量),这三个分量在C#中是按照B→G
→R的顺序进行存储的,这三个分量的值分别取在0-255范围之内,对于不同取值,
相应的也就产生了不同的颜色信息。如果以X,Y,Z轴分别取代R,G,B分量构建三维坐
标系,则颜色分布如图2.1所示。
公式2-(1)是根据我们人眼对颜色感知的特点以及人眼对色彩分辨的范围计算得到
的一个比较适于人眼感官的公式。
这里我们采用公式2-(1),对每个像素运用该公式,得到的值即为像素的灰度值。
[函数代码]
/// <summary>
/// Gray process.
/// </summary>
/// <param name="src">Source image.</param>
/// <returns></returns>
public static WriteableBitmap GrayProcess(WriteableBitmap src) ////1 灰度化处理
{
if(src!=null )
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap grayImage = new WriteableBitmap(w, h);
byte[] temp = src.PixelBuffer.ToArray();
for (int i = 0; i < temp.Length; i += 4)
{
byte tempByte = (byte)((int)(temp[i] * 0.114 + temp[i + 1] * 0.587 + temp[i + 2] * 0.299));
temp[i] = tempByte;
temp[i + 1] = tempByte;
temp[i + 2] = tempByte;
}
Stream sTemp = grayImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return grayImage;
}
else
{
return null;
}
}
[图像效果]
[函数说明]
图像灰度化函数GrayProcess(WriteableBitmap src)
[算法说明]
图像灰度化就是去掉彩色图像的彩色信息。对于一张图像,其中的每一个像素都
存在B,G,R三个颜色分量(这里不考虑透明度分量),这三个分量在C#中是按照B→G
→R的顺序进行存储的,这三个分量的值分别取在0-255范围之内,对于不同取值,
相应的也就产生了不同的颜色信息。如果以X,Y,Z轴分别取代R,G,B分量构建三维坐
标系,则颜色分布如图2.1所示。
公式2-(1)是根据我们人眼对颜色感知的特点以及人眼对色彩分辨的范围计算得到
的一个比较适于人眼感官的公式。
这里我们采用公式2-(1),对每个像素运用该公式,得到的值即为像素的灰度值。
[函数代码]
/// <summary>
/// Gray process.
/// </summary>
/// <param name="src">Source image.</param>
/// <returns></returns>
public static WriteableBitmap GrayProcess(WriteableBitmap src) ////1 灰度化处理
{
if(src!=null )
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap grayImage = new WriteableBitmap(w, h);
byte[] temp = src.PixelBuffer.ToArray();
for (int i = 0; i < temp.Length; i += 4)
{
byte tempByte = (byte)((int)(temp[i] * 0.114 + temp[i + 1] * 0.587 + temp[i + 2] * 0.299));
temp[i] = tempByte;
temp[i + 1] = tempByte;
temp[i + 2] = tempByte;
}
Stream sTemp = grayImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return grayImage;
}
else
{
return null;
}
}
[图像效果]