Win8 Metro(C#)数字图像处理--2.40二值图像轮廓提取算法

时间:2023-03-09 16:41:29
Win8 Metro(C#)数字图像处理--2.40二值图像轮廓提取算法

原文:Win8 Metro(C#)数字图像处理--2.40二值图像轮廓提取算法



[函数名称]

  二值图像轮廓提取         ContourExtraction(WriteableBitmap src) 

[算法说明]

  二值图像的轮廓提取对于图像识别,图像分割有着重要意义。该算法的核心就是将图像目标的内部点消除。所谓内部点,我们要根据当前像素点的邻域来进行判断,假设邻域窗口为3*3窗口,如果当前像素P(x,y)的八个邻域像素满足如下条件,则该点即内部点:

  1,P(x,y)为目标像素,假设目标像素为黑色0,背景像素为白色255,那么P(x,y)=0;

  2,P(x,y)的八个邻域像素均为目标像素0;

  我们把满足条件的内部点删除,换为背景点255,即可得到图像轮廓。

  内部点如下图所示:

Win8 Metro(C#)数字图像处理--2.40二值图像轮廓提取算法

[函数代码]

        /// <summary>
/// Contour Extraction process.
/// </summary>
/// <param name="src">The source image.</param>
/// <returns></returns>
public static WriteableBitmap ContourExtraction(WriteableBitmap src)
{
if (src != null)
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap srcImage = new WriteableBitmap(w, h);
byte[] temp = src.PixelBuffer.ToArray();
byte[] tempMask = (byte[])temp.Clone();
for (int j = 1; j < h-1; j++)
{
for (int i = 4; i < w*4-4; i+=4)
{
if ((tempMask[i + j * w * 4] == 0) && (tempMask[i - 4 + j * w * 4] == 0) && (tempMask[i + 4 + j * w * 4] == 0) && (tempMask[i - 4 + (j - 1) * w * 4] == 0)
&& (tempMask[i - 4 + (j + 1) * w * 4] == 0) && (tempMask[i + (j - 1) * w * 4] == 0) && (tempMask[i + (j + 1) * w * 4] == 0)
&& (tempMask[i + 4 + (j - 1) * w * 4] == 0) && (tempMask[i + 4 + (j + 1) * w * 4] == 0))
{
temp[i + j * w * 4] = (byte)255;
temp[i + 1 + j * w * 4] = (byte)255;
temp[i + 2 + j * w * 4] = (byte)255;
}
}
}
Stream sTemp = srcImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return srcImage;
}
else
{
return null;
}
}

Win8 Metro(C#)数字图像处理--2.40二值图像轮廓提取算法