2

我正在使用 GetPixel 来获取图像每个像素的颜色。图像包含不同的纯色不规则形状,我想找到最大宽度与最大高度匹配的点(或像素)(见下图)。

替代文字
(来源:fuskbugg.se

(无视边界)

我正在使用它来遍历捕获的位图:

        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                Color clr = bmp.GetPixel(x, y);

                // Hit
                if (TestColour(clr)) // See if we're within the shape. I'm just comparing a bunch of colours here.
                {
                    // Stuff I don't know
                }
            }
        }

我通过使用哈希表让它工作,但我知道这是一个糟糕的解决方案。我在考虑只有两个整数(一个用于 X,一个用于 Y)递增并保存每次迭代的最大值,然后将其与前一个进行比较,如果它更高则替换该值。

我不知道如何在我的 for 循环中使用这种方法。

有输入吗?

4

2 回答 2

1

使用两个循环找到这一点应该很简单,类似于您拥有的循环。首先,定义变量:

//from http://www.artofproblemsolving.com/Wiki/images/a/a3/Convex_polygon.png
Image image = Image.FromFile(@"C:\Users\Jacob\Desktop\Convex_polygon.png");
Bitmap bitmap = new Bitmap(image);
Point maxPoint = new Point(0, 0);
Size maxSize = new Size(0, 0);

接下来,我建议GetPixel每个像素只调用一次,并将结果缓存在一个数组中(这可能是我不得不使用 API 调用来获取像素的偏差,但事实证明更容易使用):

Color[,] colors = new Color[bitmap.Width, bitmap.Height];
for (int x = 0; x < bitmap.Width; x++)
{
    for (int y = 0; y < bitmap.Height; y++)
    {
        colors[x, y] = bitmap.GetPixel(x, y);
    }
}

接下来,这是一个获取最大高度的简单代码,以及具有该高度的第一个点的 X:

Color shapeColor = Color.FromArgb(245, 234, 229);

for (int x = 0; x < bitmap.Width; x++)
{
    int lineHeight = 0;
    for (int y = 0; y < bitmap.Height; y++)
    {
        if (colors[x, y] == shapeColor) // or TestColour(colors[x, y])
            lineHeight++;
    }
    if (lineHeight > maxSize.Height)
    {
        maxSize.Height = lineHeight;
        maxPoint.X = x;
    }
}

您可以为每个 y 创建一个类似的循环以找到最大宽度。

这里有一个重点:您的问题不是针对凹形定义的 - 在凹形上,您将拥有每个 x 的高度列表,并且最大高度线可能不会与最大宽度相交。即使在凸形上,您也可能有不止一个答案:一个简单的例子是矩形。

于 2010-07-24T21:03:12.347 回答
-1

其他解决方案;

 Bitmap bmp = new Bitmap(pictureBox1.Image);
        int width = bmp.Width;
        int height = bmp.Height;
        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                Color color = bmp.GetPixel(x, y);

                if (color.R == 0)
                {
                    textBox4.Text = x.ToString();
                    textBox5.Text = y.ToString();
                    return; //Starting Point.If canceled endpoint.
                }
于 2014-04-21T15:25:41.823 回答