Get-the-average-rgb-from-pixels (revisited)

@GoToLoop answered this but which of the two methods is better? Is there a reason to change the int for each of the three RGB channels to color???

Both methods work, I just want to understand.


Hello @paulstgeorge

I threw this rough code together the other day:

// Average colour within area of a circle
// v1.0.0
// GLV 2021-08-08

// This is a very rough first pass at this.
// Alpha component 0xFF000000 is added to the final color.

// References:

void setup() 
  size(600, 300);

void draw() 

  fill(255, 0, 0);
  circle(width/4, height/3, 80);
  fill(0, 255, 0);
  circle(2*width/4, height/3, 80);
  fill(0, 0, 255);
  circle(3*width/4, height/3, 80);
  int sqW = 10;
  int xMin = mouseX - sqW;
  int xMax = mouseX + sqW;
  int yMin = mouseY - sqW;
  int yMax = mouseY + sqW;
  int redAve = 0;
  int greenAve = 0;
  int blueAve = 0;
  int count = 0;
  int colAve = color(128);
  for (int x = xMin; x < xMax; x++) 
    // Loop through every pixel row
    for (int y = yMin; y < yMax; y++) 
      // Use the formula to find the 1D location
      int loc = x + y * width;
      if (loc>0 && loc<pixels.length)
        if((x-mouseX)*(x-mouseX) + (y-mouseY)*(y-mouseY) < sqW*sqW)
          //print(hex(pixels[loc]), " ");
          redAve += red(pixels[loc]);
          greenAve += green(pixels[loc]);
          blueAve += blue(pixels[loc]);
          colAve = 0xFF000000 | (redAve/count)<<16 | (greenAve/count)<<8 | (blueAve/(count+1))&0xFF;
          //println( hex(int(red(pixels[loc]))), hex(int(green(pixels[loc]))), hex(int(blue(pixels[loc]))) );
          //println(hex(redAve), hex(greenAve), hex(blueAve));
          println(hex(redAve/count), hex(greenAve/count), hex(blueAve/count));
          set(x, y+height/3, colAve);
  circle(width/2, 3*height/4, 80);  

The topic inspired me.

Have fun!


Wow, I have so many questions! First a simple one while I play with your code. Is the radius of the sample sqW (10)? What does println() on its own do???

Processing source:

static public void println() {

Which is this in Java:

I believe so… I started with a square originally and got carried away.

All those println() were for debugging along the way; not a good place for them in the loop.
See reference for a comment on this:

Keep in mind that this is just me having fun with code and its a mix of things.

I used pixels[] array instead of get():



I had some fun with this an have a related gallery topic:


1 Like