gpt4 book ai didi

c# - 使用 GetPixel() 查找彩色区域的最大宽度和最大高度相交的像素

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:52 24 4
gpt4 key购买 nike

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

alt text
(来源: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 循环。

有什么意见吗?

最佳答案

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

//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 都有一个高度列表,并且最大高度线可能不会与最大宽度相交。即使在凸形上,您也可能有不止一个答案:矩形就是一个简单的例子。

关于c# - 使用 GetPixel() 查找彩色区域的最大宽度和最大高度相交的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3325723/

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