【问题标题】:Count red pixel in a given image计算给定图像中的红色像素
【发布时间】:2017-09-12 14:08:04
【问题描述】:

我是 Java 新手,想计算给定图像中的红色像素。到目前为止,我有以下代码,但不确定要添加什么条件来检查像素是否为红色。到目前为止,我有以下代码。提前致谢。

public static int countRedPixels(Picture v){

    BufferedImage image = (v.getBufferedImage());
    int width = image.getWidth();
    int height = image.getHeight();

    int redCount = 0;
    int pixelCount = 0;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height ; y++) {

            int rgb = image.getRGB(x, y);

            //get rgbs
            //int alpha = (rgb >>> 24) & 0xFF;
            int red   = (rgb >>> 16) & 0xFF;
            int green = (rgb >>>  8) & 0xFF;
            int blue  = (rgb >>>  0) & 0xFF;

            if (red == 255 && green == 0 && blue == 0 || image.getRGB(x, y) == 0xFFFF0000) {
                redCount++;
            }

            pixelCount++;
        }
    }

    System.out.println("Red Pixel Count:" + redCount);
    System.out.println("Pixel Count:" + pixelCount);
    return redCount;
}

【问题讨论】:

  • 我猜这取决于你对red的定义?会是 rgb(255,0,0) 吗?
  • 是的,应该是 (255,0,0)。
  • 好吧,那么...if (red == 255 &amp;&amp; green == 0 &amp;&amp; blue == 0) { ++redCount; }?甚至if (rgb == 0xFFFF0000) ...
  • 啊!这就说得通了。但是我不确定到目前为止我编写的代码是否正确。我使用示例图片运行它,我得到的所有值都是 255。
  • 我们在这里看到的代码对我来说看起来不错。

标签: java image-processing pixel rgba


【解决方案1】:

不确定是我遗漏了什么,还是您真的只见树木不见森林。无论如何,评论变成了答案:

鉴于 red 表示 (255, 0, 0),您可以这样做:

if (image.getRGB(x, y) == 0xFFFF0000) {
    ++redCount;
}

或者,如果您不关心 alpha:

if (red == 255 && green == 0 && blue == 0) {
    ++redCount;
}

【讨论】:

  • 我的计数在函数结束时为 0。这就是为什么如果我在上面粘贴的代码中做错了什么,我会感到困惑。
  • 这两种方法都以0 结尾吗?
  • 是的。我只是用 png 1 更改了图像并且它有效。奇怪的是它不适用于 jpeg。
  • 这确实让我吃惊,因为应该内置 jpg 支持(假设您使用的是 ImageIOBufferedImage)。哦,好吧,至少它现在可以工作了。
  • @MilanShah JPEG 是一种有损压缩,您的红色不会是 (255,0,0),您必须查看该区域。
猜你喜欢
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 2017-10-22
  • 2023-03-26
  • 2019-06-01
  • 2022-12-19
相关资源
最近更新 更多