0

I want find the average red RGB-value of a MyImage (extending BufferedImage). I save the red value for each pixel in the image to an array red[]. At the end I want to sum these ut to find the average value of red. But when I run this code on a MyImage it only prints 0. How can i get this method to work properly? (The code not included here works just fine)

public class MyImage extends BufferedImage {

    public MyImage(int width, int height, int imageType) {
        super(width, height, imageType);
    }

    public void findAverageRedValue(){

        int height = this.getHeight();
        int width = this.getWidth();
        int[] red = new int[height*width];

        Map m = new HashMap();
        for(int i=0; i < width ; i++)
        {
            for(int j=0; j < height ; j++)
            {
                ColorModel colorModel = this.getColorModel();
                int rCol = colorModel.getRed(j*i);
                red[red.length - 1] = rCol;
            }               
        }

        int sum = 0;
        for(int i = 0; i < red.length; i++)
            sum += red[i];

        int averageRed = sum/red.length;
        System.out.println(averageRed);
    }        
}

1 Answer 1

1

You're assigning elements of your array as:

red[red.length - 1] = rCol;

This will, in every possible situation, only assign the last element of the array. The length property of an array isn't like the size() of a collection; it's a static value which is based on the initialised dimension of the array.

So all but one of the array entries will be zero. Thus at the end, the sum will be between 0 and 255 - and when divided by a (likely) larger number, this comes out as zero. (There's a possible issue here in that you're doing integer division, but this is perhaps not critical).

To fix this, you'll need to change which array index you assign to. You could either keep a separate counter for the array index - or, make use of the existing i and j to do:

red[i * width + j] = rCol;

Either way, this will put each pixel's red component into a separate array location, and thus enable you to sum them correctly.

Integer division is a potential gotcha in Java, and that's what you're doing here at the end. It may be better to get the fractional average via sum / (float)red.length, though as long as you know what's happening and you're happy to have truncation to the nearest integer, this may not be necessary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.