【问题标题】:How do I make the for loops for this code? (I need to check a region of an image for a certain color.)如何为这段代码制作 for 循环? (我需要检查图像的某个区域是否有某种颜色。)
【发布时间】:2018-06-17 20:07:11
【问题描述】:

根据Get color of each pixel of an image using BufferedImages,以下代码需要 for 循环才能达到预期目的。

public class GetPixelColor
{
  public static void main(String args[]) throws IOException{
  File file= new File("your_file.jpg");
  BufferedImage image = ImageIO.read(file);
  // Getting pixel color by position x and y 
  int clr=  image.getRGB(x,y); 
  int  red   = (clr & 0x00ff0000) >> 16;
  int  green = (clr & 0x0000ff00) >> 8;
  int  blue  =  clr & 0x000000ff;
  System.out.println("Red Color value = "+ red);
  System.out.println("Green Color value = "+ green);
  System.out.println("Blue Color value = "+ blue);
  }
}

如何定义我想用 for 循环检查其颜色的图像区域?

【问题讨论】:

标签: java


【解决方案1】:

您要读取它的颜色的区域是两点之间的矩形 p1(x1,y1), p2(x2,y2) 然后你用两个嵌套的 for 循环扫描那个矩形

for(int x=x1; x<=x2; x++)
   for(int y=y1; y<=y2; y++){
        // Getting pixel color by position x and y 
        int clr=  image.getRGB(x,y); 
        int  red   = (clr & 0x00ff0000) >> 16;
        int  green = (clr & 0x0000ff00) >> 8;
        int  blue  =  clr & 0x000000ff;
        System.out.println("Red Color value = "+ red);
        System.out.println("Green Color value = "+ green);
        System.out.println("Blue Color value = "+ blue);
   }

【讨论】:

  • 我知道这不是原始问题的一部分,但你能帮我理解“int red = (clr & 0x00ff0000) >> 16;”中发生了什么吗?如果我理解正确,“clr & 0x00ff0000”是一个布尔值。它甚至被移动“>>16”。如何将其分配给整数?
  • &amp; 是逻辑AND 操作,布尔运算符是&amp;&amp;,代码剂量是从clr 中屏蔽red 值,然后将其移位&gt;&gt; 16
【解决方案2】:

您可以简单地使用两个嵌套的 for 循环来遍历图像,如下所示:

public static void printPixelColors(BufferedImage img) {
        int imageWidth = img.getWidth();
        int imageHeight = img.getHeight();
        for (int y = 0; y < imageHeight; y++) {
            for (int x = 0; x < imageWidth; x++) {
                // Getting pixel color by position x and y 
                int clr = img.getRGB(x, y);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                System.out.println("Red Color value = " + red);
                System.out.println("Green Color value = " + green);
                System.out.println("Blue Color value = " + blue);
            }
        }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 2013-02-28
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多