【发布时间】: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 && green == 0 && blue == 0) { ++redCount; }?甚至if (rgb == 0xFFFF0000) ... -
啊!这就说得通了。但是我不确定到目前为止我编写的代码是否正确。我使用示例图片运行它,我得到的所有值都是 255。
-
我们在这里看到的代码对我来说看起来不错。
标签: java image-processing pixel rgba