1

下面的代码需要几秒钟,我想更快地通过颜色检测对象,以便可以实时显示。

grayImg = input.InRange(new Bgr(selectionRangeSlider1.SelectedMin,
                                selectionRangeSlider2.SelectedMin,
                                selectionRangeSlider3.SelectedMin),
                                new Bgr(selectionRangeSlider1.SelectedMax,
                                        selectionRangeSlider2.SelectedMax,
                                        selectionRangeSlider3.SelectedMax));  

selectionRangeSlider 是一个自定义控件,在 1 个值线上有 2 个滑块

Rectangle roi; //this rectangle is the product of rectangle recognition, now I want to check if the color of this recangle is at least 50% yellow

int whitePixels = 0;

for (int i = roi.X; (i < (roi.X + roi.Width)); i++)
{
    for (int j = roi.Y; (j < (roi.Y + roi.Height)); j++)
    {
        Byte currentVal = g.Data[i, j, 0];

        if (currentVal == 255) //255 means true: this pixel is yellow
        {
            Console.WriteLine(i + "," + j + " is yellow");
            whitePixels++;
        }
    }
}

if (whitePixels > ((roi.Width * roi.Height) / 2))
{
    // "more that half is yellow";
}
4

1 回答 1

3

首先,如果你想找到一种颜色,我建议你在 HSV 模式下分割你的图像。以这种方式跟踪颜色更容易。

然后,不用做这个双 for/loop,而是使用这个简单的函数:CountNonZero

永远不要在循环中向控制台写东西,除非是为了调试,因为它非常慢。

所以这是最终的管道,应该是实时的

  1. 将图像转换为 HSV 模式
  2. 分成 3 个通道
  3. 根据您要跟踪的颜色执行 InRange(使用您的 UI)
  4. 做投资回报率
  5. 计数非零。
于 2013-10-15T17:20:14.080 回答