My projects library #4! Gallery Megathread

#55 Simple posterization filter

Posterization filter sets the maximum amount of colors used. All colors on the screen get converted into those. explanation by josephh

Code
int clrs = 3; //end has clrs^3 colors, (1-1, 2-8, 3-27, 4-64, 5-125, 6-216,...)
color clr[];
PImage img;
void setup() {
  size(640,642);
  clr = generateColors(clrs);
  img = loadImage("house2.jpg");
  println(img.width,img.height);
}
void draw() {
  image(img,0,0); noLoop();
  loadPixels();
  for(int i = 0; i < width; i++) for(int j = 0; j < height*0.5; j++) {
    int in = i+j*width, off = floor(width*height*0.5);
    color base = pixels[in], chan = closest(base);
    pixels[in+off] = chan;
  }
  updatePixels();
}
color closest(color input) {
  int id=0;
  float d = -1;
  for(int i = 0; i < clr.length; i++) {
    float dis = dist(red(input),green(input),blue(input),red(clr[i]),green(clr[i]),blue(clr[i]));
    if(dis < d || d == -1) {
      id = i;
      d = dis;
    }
  }
  return clr[id];
}

color[] generateColors(int c) {
  float a = 255/c;
  color nclr[] = new color[c*c*c];
  for(int i = 0; i < c; i++) for(int j = 0; j < c; j++) for(int k = 0; k < c; k++) {
    nclr[i+j*c+k*c*c] = color(i*a, j*a, k*a);
  }
  return nclr;
}

It is a simple project (if you are using the simple color cube solution). It can be upgraded at any time by changing the generateColors() function.