使用 GetPixel() 查找彩色区域的最大宽度和最大高度相交的像素
我正在使用 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 循环中使用这种方法。
有什么意见吗?
I'm using GetPixel to get the colour of each pixel of an image. The images contain different plain-coloured irregular shapes, and I'd like to find the point (or pixel) where the maximum width matches the maximum height (see figure below).
(source: fuskbugg.se)
(disregard the border)
I'm using this to iterate through the captured bitmap:
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
}
}
}
I got it to work by using a hashTable, but I understand that it's an dawful solution. I was thinking in the lines of just having two integers (one for X, one for Y) increment and save the maximum value for each iteration, then compare this to the previous one and replace the value if it's higher.
I don't see how I'd be able to use that approach with my for-loops nested like that.
Any input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其他解决方案;
other solutions;
使用两个循环找到这一点应该很简单,类似于您的循环。
首先,定义变量:
接下来,我建议每个像素仅调用一次
GetPixel
,并将结果缓存在数组中(这可能是我必须使用 API 调用来获取结果时的偏差)像素,但会更容易使用):接下来,这里有一个简单的代码来获取最大高度,以及具有该高度的第一个点的 X:
您可以为每个 y 进行类似的循环以找到最大宽度。
这里重要的一点是:您的问题不是针对凹形形状定义的 - 在凹形形状上,您将有每个 x 的高度列表,并且最大高度线可能不会与最大宽度相交。即使对于凸形状,您也可能有多个答案:一个简单的例子是矩形。
It should be simple to find this point using two loops, similar to the loop you have.
First, define your variables:
Next, I would recommend calling
GetPixel
only once per pixel, and cache the results in an array (this may be a bias from when I had to use an API call to get the pixel, but will prove easier to work with):Next, here's a simple code to get the maximum height, and the X of the first point with that height:
You can make a similar loop for each y to find the maximal width.
An important point here: your question isn't defined for concave shapes - on concave shapes you will have a list of heights for every x, and the maximal height line may not intersect the maximal width. Even on convex shapes you may have more than a single answer: a simple example of it is a rectangle.