0

我正在开发一个程序,该程序使用 Java 中的 Color 方法从图像中提取像素。然而,这并不重要。

我需要将 X 和 Y 变量分别增加到它们的图像宽度和高度。我曾尝试嵌套 for 循环,但它只会在满足另一个条件时触发另一个循环。

代码

    for (int x = 0; x<ScreenWidth; x++)
    {
        for (int y = 0; y<ScreenHeight; y++)
        {

        Color c = new Color(DesktopCapture.getRGB(x,y));
        int r = c.getRed();
        int g = c.getGreen();
        int b = c.getBlue();
        System.out.println("Colour at location of screen is " + r + " " + g + " " + b + " Position is " + x + " " + y);

        Thread.sleep(40);

输出

Colour at location of screen is 151 184 216 Position is 0 0
Colour at location of screen is 151 186 218 Position is 0 1
Colour at location of screen is 151 188 220 Position is 0 2
Colour at location of screen is 151 190 222 Position is 0 3
Colour at location of screen is 152 192 224 Position is 0 4
Colour at location of screen is 152 194 226 Position is 0 5
Colour at location of screen is 152 195 227 Position is 0 6
Colour at location of screen is 153 196 228 Position is 0 7
Colour at location of screen is 153 197 229 Position is 0 8
Colour at location of screen is 154 197 229 Position is 0 9
Colour at location of screen is 154 196 228 Position is 0 10
Colour at location of screen is 154 195 227 Position is 0 11
Colour at location of screen is 154 194 225 Position is 0 12
Colour at location of screen is 154 192 223 Position is 0 13
Colour at location of screen is 154 190 221 Position is 0 14
Colour at location of screen is 154 188 219 Position is 0 15
Colour at location of screen is 153 186 216 Position is 0 16
Colour at location of screen is 152 184 214 Position is 0 17
Colour at location of screen is 152 182 212 Position is 0 18
Colour at location of screen is 153 181 210 Position is 0 19
Colour at location of screen is 210 222 234 Position is 0 20
4

1 回答 1

2

您的解决方案的运行时间复杂度将是可怕的:O(N^2)。您可以通过执行以下操作递归地解决此问题:

int height = 0;
int width = 0;

public void returnPixels(int height, int width)
     Color c = new Color(DesktopCapture.getRGB(width,height));
        int r = c.getRed();
        int g = c.getGreen();
        int b = c.getBlue();
        System.out.println("Colour at location of screen is " + r + " " + g + " " + b + " Position is " + x + " " + y);
      if(height < screenHeight){
        if(width < screenwidth){
           width++;
           returnPixels(height, width);
        } else if(width > screenWidth){
          width=0;
          height++;
          returnPixels(height, width);
          }
       }
    }

或类似的东西。这将读取每一行,然后当它到达末尾时,它会移动到下一个高度线

于 2013-05-25T05:00:46.547 回答