c# - 给定一组点查找区域

标签 c# image-processing geometry

给定 x、y 坐标列表和已知的宽度和高度,如何确定封闭区域的 NUMBER(在 C# 中)?

例如:

enter image description here

在此图像中定义了 5 个封闭区域:

  1. 人脸 (1)
  2. 眼睛 (2)
  3. Nose (1)
  4. 右脸 (1)

x,y 点列表可以是任何黑色像素,包括嘴巴。

最佳答案

您可以使用这个简单的算法,基于使用辅助位图进行洪水填充的想法:

// backColor is an INT representation of color at fillPoint in the beginning.
// result in pixels of enclosed shape.
private int GetFillSize(Bitmap b, Point fillPoint)
{
   int count = 0;
   Point p;
   Stack pixels = new Stack();
   var backColor = b.GetPixel(fillPoint.X, fillPoint.Y);
   pixels.Push(fillPoint);
   while (pixels.Count != 0)
   {
       count++;

       p = (Point)pixels.Pop();
       b.SetPixel(p.X, p.Y, backColor);

       if (b.GetPixel(p.X - 1, p.Y).ToArgb() == backColor)
           pixels.Push(new Point(p.X - 1, p.Y));

       if (b.GetPixel(p.X, p.Y - 1).ToArgb() == backColor)
           pixels.Push(new Point(p.X, p.Y - 1));

       if (b.GetPixel(p.X + 1, p.Y).ToArgb() == backColor)
           pixels.Push(new Point(p.X + 1, p.Y));

       if (b.GetPixel(p.X, p.Y + 1).ToArgb() == backColor)
           pixels.Push(new Point(p.X, p.Y + 1));
   }

   return count;
}

更新

上面的代码只适用于这个四重链接的封闭区域。以下代码适用于八链封闭区域。

// offset points initialization.
Point[] Offsets = new Point[]
{
    new Point(-1, -1),
    new Point(-0, -1),
    new Point(+1, -1),
    new Point(+1, -0),
    new Point(+1, +1),
    new Point(+0, +1),
    new Point(-1, +1),
    new Point(-1, +0),
};

...

private int Fill(Bitmap b, Point fillPoint)
{
    int count = 0;
    Point p;
    Stack<Point> pixels = new Stack<Point>();
    var backColor = b.GetPixel(fillPoint.X, fillPoint.Y).ToArgb();
    pixels.Push(fillPoint);
    while (pixels.Count != 0)
    {
        count++;

        p = (Point)pixels.Pop();
        b.SetPixel(p.X, p.Y, Color.FromArgb(backColor));

        foreach (var offset in Offsets)
            if (b.GetPixel(p.X + offset.X, p.Y + offset.Y).ToArgb() == backColor)
                pixels.Push(new Point(p.X + offset.X, p.Y + offset.Y));
    }

    return count;
}

下图清楚地说明了我的意思。也可以向偏移阵列添加更多远点,以便能够填充有间隙的区域。

Connectedness

关于c# - 给定一组点查找区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12589214/

相关文章:

c# - 如何使用asp.net在下拉列表中绑定(bind)图像和名称

c# - 在 Android 上发现附近的智能手机设备

python - 可以使用什么算法来确定多个条纹的存在?

python - 有没有办法用白色填充图像的内部?

java - 在 Java 中组合区域时舍入不准确?

c# - 如何强制 Regex.Replace 匹配 '/s'(将字符串视为单行)正则表达式修饰符

c# - 定位到文件夹并执行应用程序 C#

java - 为图像编辑器快速、可靠地保存/加载文档状态

python - 如何在 matplotlib 中以毫米为单位设置轴尺寸和位置?

c# - 点在 3D 线上的投影