How to get average pixel color around defined polygon

Any ideas on how to average the pixel colors found within a predefined boundary? For example, I'd be trying to achieve a kind of stained-glass effect on a bitmap image, given a grid pattern that I've already drawn in Processing.

Answers

  • edited November 2016 Answer ✓

    Here is an algorithm for getting the average color of a PImage that was previously posted to the forums:

    color getAverageColor(PImage img) {
      img.loadPixels();
      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);
    }
    

    Here is one approach to extend this to polygons or arbitrary patterns:

    Step 1. Adapt this function to take two images -- an image, and a mask.

    color getAverageColor(PImage img, PImage mask) { }
    

    The image and the mask are the same size. If the mask pixel is white, include the image pixel color in the average. If not, skip the image pixel.

    https://processing.org/reference/PImage_mask_.html

    Step 2. Then you need a second function, setAverageColor:

    void setAverageColor(PImage img, PImage mask) {
       color c = getAverageColor(img, mask);
       // now loop through and if mask pixel is white change img pixel to c
    }
    

    Now you just have to draw masks (stained glass, whatever) and then use setAverageColor(img,mask) to apply them to your image as color regions.

  • This worked splendidly, thanks jeremy!

  • Very glad to hear it, @cicero38cicero38 .

    Do share the demo sketch (and / or upload an image of the output) if you want others to see how your stained glass worked out. I know I'm curious!

Sign In or Register to comment.