0

the question is, how to stack that r value in array so i can sum all of it and find the average value

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {

        int p = img.getRGB(x, y);

        int a = (p >> 24) & 0xff; 
        * * int r = (p >> 16) & 0xff; * * //this red
        int g = (p >> 8) & 0xff;
        int b = (p >> 0) & 0xff;


        mainform1.pixelValueTextArea.append("height: " + y + " width:  " + x + " red: " + r + " green: " + g + " blue: " + b + "\n");
        jlab.setIcon(new ImageIcon(f.toString()));
        jlab.setHorizontalAlignment(JLabel.CENTER);
        mianform1.captureImageScrollPane.getViewport().add(jlab);

    }
}

(all i want to do is get average RGB and show it in my mainform)

any suggestion?

2 Answers 2

1

You can declare an ArrayList outside the for-loops. and in every for-loop you could list.add(r). Then after your for-loop, you can sum them up and devide through the list.size()

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

Comments

1

This looks like a homework problem so I'm not going to solve the whole thing for you, but here's an example of one way you could calculate the average 'red' value. This gets the Integer average, but keep in mind that you could get a more accurate floating point value if that's what you need.

// we'll calculate the sum by counting upward from zero
int rSum = 0;

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {

        int p = img.getRGB(x, y);

        int a = (p >> 24) & 0xff; 
        int r = (p >> 16) & 0xff; //this red
        int g = (p >> 8) & 0xff;
        int b = (p >> 0) & 0xff;

        // add the current red value to the total
        rSum += r;

        mainform1.pixelValueTextArea.append("height: " + y + " width:  " + x + " red: " + r + " green: " + g + " blue: " + b + "\n");
        jlab.setIcon(new ImageIcon(f.toString()));
        jlab.setHorizontalAlignment(JLabel.CENTER);
        mianform1.captureImageScrollPane.getViewport().add(jlab);
    }
}

// calculate the average by dividing the sum by the total number of values
int rAverage = rSum / (width * height);

/* code for displaying rAverage */

1 Comment

@2r83 I'm glad my answer is helpful! I think there's a way that you can mark it as the accepted answer...

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.