#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# Get the average RGB from pixels

edited March 2016

Hi to all.

I am using the following code to draw one pixel colour for every 10x10 pixel area.

``````size(700, 450);
//noStroke();
int detail = 10;

for (int i=0; i<width; i+=detail) {
for (int j=0; j<height; j+=detail) {
color c = img.get(i, j);
fill(c);
rect(i, j, detail, detail);
}
}
``````

My question is, how can I instead of reading one pixel's value and draw it in the area of 10x10, to get the average of all pixels from the 10x10 area of the original image, and draw the value on the same 10x10 rect?

Thanks - I also attach a sketch, maybe is helps!

Tagged:

• edited March 2016

Thank you GoToLoop.

In this code I can see the averaging of the values, but how can I get the average for each area of the image - and not from the whole image?

As in the attached picture above, I need some help to configure the first 10x10 area and get the average value, then proceed to the next 10x10 area and get the average value, and so on....

Thanks

``````color extractColorFromImage(PImage img) {
int r = 0, g = 0, b = 0;
for (int i=0; i<img.pixels.length; i++) {
color c = img.pixels[i];
r += c>>16&0xFF;
g += c>>8&0xFF;
b += c&0xFF;
}
r /= img.pixels.length;
g /= img.pixels.length;
b /= img.pixels.length;

return color(r, g, b);
}
``````

We can clone a whole PImage invoking its method get().
And if we pass 4 arguments to it, we get a cloned rectangular section of it: *-:)
https://Processing.org/reference/PImage_get_.html

• Great!

I merged the two parts here:

``````void setup() {
size(700, 450);
int detail = 30;

for (int i=0; i<width; i+=detail) {
for (int j=0; j<height; j+=detail) {
PImage newImg = img.get(i, j, detail, detail);
fill(extractColorFromImage(newImg));
rect(i, j, detail, detail);
}
}
}

color extractColorFromImage(PImage img) {
int r = 0, g = 0, b = 0;
for (int i=0; i<img.pixels.length; i++) {
color c = img.pixels[i];
r += c>>16&0xFF;
g += c>>8&0xFF;
b += c&0xFF;
}
r /= img.pixels.length;
g /= img.pixels.length;
b /= img.pixels.length;

return color(r, g, b);
}
``````
• Nice you did it! As a bonus a slightly tweaked extractColorFromImage(): B-)

``````color extractColorFromImage(final PImage img) {
color r = 0, g = 0, b = 0;

for (final color c : img.pixels) {
r += c >> 020 & 0xFF;
g += c >> 010 & 0xFF;
b += c        & 0xFF;
}

r /= img.pixels.length;
g /= img.pixels.length;
b /= img.pixels.length;

return color(r, g, b);
}
``````