它可能是一个愚蠢的错误,但由于某些原因我的计数器没有递增,对于我的代码底部的所有打印语句,控制台的输出为0。 我确保正确读取颜色,这意味着增量代码一定存在问题。
public void countColours(BufferedImage colouredImage) {
int redCount = 0;
int greenCount = 0;
int blueCount = 0;
int totalPixels = (colouredImage.getWidth()*colouredImage.getHeight());
for (int x = 0; x < colouredImage.getWidth(); x++) {
for (int y = 0; y < colouredImage.getHeight(); y++) {
int red = ((colouredImage.getRGB(x, y)>>> 16) & 0xFF);
int green = ((colouredImage.getRGB(x, y)>>> 8) & 0xFF);
int blue = ((colouredImage.getRGB(x, y)) & 0xFF);
float[] hsb = Color.RGBtoHSB(red, green, blue, null);
float hue = hsb[0];
int colour = (int) (hue*360);
if (colour <= 60 & colour >= 300) {
redCount++;
}
if (colour >= 60 & colour <= 180) {
greenCount++;
}
if (colour >= 180 & colour <= 300) {
blueCount++;
}
}
}
int totalRed = (redCount/totalPixels)*100;
int totalGreen = (greenCount/totalPixels)*100;
int totalBlue = (blueCount/totalPixels)*100;
System.out.println(totalRed);
System.out.println(totalGreen);
System.out.println(totalBlue);
}
我已尽可能多地调试,如上所述,颜色是0到360之间的值,但if语句和增量显然不起作用,但我不明白为什么?
提前致谢
答案 0 :(得分:2)
你正在混合浮点除法(支持0.75之类的数字)和int除法(将数字舍入为0.75到0)。将您的数字更改为加倍或浮动。
您可以通过添加print语句对此进行测试:
System.out.println("redCount: " + redCount);
System.out.println("totalPixels: " + totalPixels);
System.out.pirntln("redCount/totalPixels: " + (redCount/totalPixels) );
int totalRed = (redCount/totalPixels)*100;
答案 1 :(得分:0)
我相信问题不在于你的增量或if语句,而是在这里:
int totalRed = (redCount/totalPixels)*100;
int totalGreen = (greenCount/totalPixels)*100;
int totalBlue = (blueCount/totalPixels)*100;
redCount
,greenCount
,blueCount
和totalPixels
都是int
,所以当你划分时,结果(应该在1之间)和0)将被截断为零。
要解决这个问题,请在分割之前将你的易行品投射到浮子上:
int totalRed = (int)((float)redCount/totalPixels)*100;
int totalGreen = (int)((float)greenCount/totalPixels)*100;
int totalBlue = (int)((float)blueCount/totalPixels)*100;