Kek Mckek
Kek Mckek

Reputation: 31

Java - Loop to average rgb values should be breaking things....but isn't

So I've got a school project and we have to work with a couple classes our prof gave us and make our own to make an image organizer.

The first part consists of making a set of static methods to edit the images themselves as 2D arrays of Color arrays(ColorImage type).

The first first problem is making a tool to downscale an image by a factor of f(f sided square of pixels in the original becomes 1 pixel in the output), and mine works, but I think it shouldn't and I can't figure why it works, so any help is appreciated. Specifically I'm taking about the loop that averages the colours of each position in the buffer array(avgArr[][]) (line 16). I'm thinking: the value of reds blues and greens would just be overwritten for each iteration and avgColor would just get the vlaue of the last pixel it got the rgb values off of avgArr.

    static ColorImage downscaleImg(ColorImage img, int f) {

    ColorImage dsi = new ColorImage(img.getWidth()/f, img.getHeight()/f);
    Color[][] avgArr = new Color[f][f];
    int reds = 0;
    int greens = 0;
    int blues = 0;

    for(int i = 0; i < dsi.getWidth(); i++) {
        for(int j = 0; j < dsi.getHeight(); j++) {
            for(int x = i*f, xc = 0; x < i*f + (f-1); x++, xc++){
                for(int y = j*f, yc = 0; y < j*f + (f-1); y++, yc++) {
                    avgArr[xc][yc] = img.getColor(x, y);
                }
            }
            for(int k = 0; k < f - 1; k++){
                for(int w = 0; w < f - 1; w++) {
                    reds += avgArr[k][w].getR();
                    greens += avgArr[k][w].getG();
                    blues += avgArr[k][w].getB();
                }
            }
            int count = f*f;
            Color avgColor = new Color(reds/count, greens/count, blues/count);
            dsi.setColor(i, j, avgColor);
            reds = 0;
            greens = 0;
            blues = 0;
        }
    }
    return dsi;
}

Thanks,

EDIT: Turns out, it was in fact just taking the colour of, the last position of avgArr that it looked at. Any suggestions to correct are welcome.

Upvotes: 2

Views: 87

Answers (1)

Alex Wittig
Alex Wittig

Reputation: 2900

I think you can solve your problem by summing the reds/greens/blues and then dividing them by the total pixels at the end to find the average:

int reds = 0;
int greens = 0;
int blues = 0;

...

        for(int k = 0; k < f - 1; k++){
            for(int w = 0; w < f - 1; w++) {
                reds += avgArr[k][w].getR();    // <-- note the +=
                greens += avgArr[k][w].getG();
                blues += avgArr[k][w].getB();
            }
        }

        int count = (f-1)*(f-1);
        Color avgColor = new Color(reds/count, greens/count, blues/count);

Upvotes: 1

Related Questions