Frage

Its probably a silly mistake that ive done but for some reason my counter isnt incrementing, the output to the console is 0 for all print statements at the bottom of my code. Ive made sure that the colour is being read correctly which means there must be an issue with the incrementing code.

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);
    }

Ive debugged as much as possible as I said above, colours are values between 0 and 360 but the if statements and increments are clearly not working but I dont understand why?

Thanks in advance

War es hilfreich?

Lösung

You're mixing floating point division (which supports numbers like 0.75) and int division (which rounds numbers like 0.75 to 0). Change your numbers to double or float.

You can test this by adding print statements:

System.out.println("redCount: " + redCount);
System.out.println("totalPixels: " + totalPixels);
System.out.pirntln("redCount/totalPixels: " + (redCount/totalPixels) );

int totalRed = (redCount/totalPixels)*100;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top