【问题标题】:Looping through all RGB combinations within a limit在限制内循环遍历所有 RGB 组合
【发布时间】:2015-04-04 20:42:43
【问题描述】:

我目前正在使用以下代码循环遍历图像中的像素,并返回像素的坐标,其 RGB 值与 if 语句中定义的相同:

outerloop:
        for (int y = 0; y < image.getHeight(); y = y + 1) {
            for (int x = 0; x < image.getWidth(); x = x + 1) {
                Color mycolor = new Color(image.getRGB(x, y));
                int red = mycolor.getRed();
                int green = mycolor.getGreen();
                int blue = mycolor.getBlue();               

                if (red == 183 & green == 86 & blue == 182){
                    System.out.println(x,y);                    
                    break outerloop;
                }
            }
        }

现在的问题是 RGB 值在应用程序中每次变化都非常轻微,所以我试图为当前恒定的 RGB 值添加一种“容差”。例如,在一种情况下,红色可能是 185,绿色可能是 89,而蓝色可能是相同的 (182)。

我知道我可以在 if 语句中使用 OR (||) 函数定义所有条件,但由于这需要大量代码,有没有更简单的解决方案?例如,将正公差定义为常数并循环遍历此公差内的所有 RGB 值组合?

【问题讨论】:

  • if (Math.abs(red - 183) &lt; tolerance &amp;&amp; Math.abs(green - 86) &lt; tolerance &amp;&amp; ... 等?
  • 转换为 HSV 是否更有意义?饱和度大致相同,或者至少可以忽略不计。我猜转换会很慢。

标签: java for-loop colors combinations rgb


【解决方案1】:

在容差范围内循环遍历所有颜色排列会非常慢:假设您的容差为+/- 5,这将需要检查 1331 种不同的颜色 (11 reds * 11 greens * 11 blues)。

将您的条件red == 183 更改为Math.abs(red - 183) &lt; tolerance 或(red &gt;= 183 - tolerance || red &lt;= 183 + tolerance) 之类的东西要快得多(对于其他频道也是如此)。

【讨论】:

    【解决方案2】:

    与其检查您的值是否明确等于数字列表,不如检查它们是否在特定范围内。您可以使用 (180&lt;x &amp; x&lt;185) 之类的方法来执行此操作,但使用绝对值会更简洁:

    int TOLERANCE = 3;
    boolean in_range(int value, int setpt) {
        return abs(value-setpt) <= TOLERANCE;
    }
    

    然后在您的循环中,您的条件将如下所示:

    int R_SETPT = 183;
    int G_SETPT = 86;
    int B_SETPT = 182;
    
    if (in_range(red, R_SETPT) &
        in_range(green, G_SETPT) &
        in_range(blue, B_SETPT)) {
        // etc.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 2014-07-14
      • 2012-11-03
      • 1970-01-01
      • 2017-02-03
      相关资源
      最近更新 更多