gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:09:16 26 4
gpt4 key购买 nike

给定 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com