/* * We create a mosaic form of the original image, by * creating k-by-k squares having color equal to * the average of all original pixels in within that square. * * The user can adjust the value of k with the up/down arrows. */ PImage slu; int k = 8; int w, h; // dimensions of original image void setup() { // Can either load an image stored locally or from a URL: slu = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/SLU_portals.jpg/1024px-SLU_portals.jpg"); w = slu.width; h = slu.height; noStroke(); size(1024, 768); createMosaic(); } void draw() { } // recreate the necessary mosaic based on current k value void createMosaic() { for (int x=0; x < w; x += k) { for (int y=0; y < h; y += k) { fill(averageColor(x,y)); rect(x, y, k, k); } } } // determine the average color of the k-by-k squared anchored at (x,y) color averageColor(int x, int y) { float r=0, g=0, b=0; int t=0; // number of pixels within range (may be partial square) for (int i=x; i < min(w,x+k); i++) { for (int j=y; j < min(h,y+k); j++) { color c = slu.get(i,j); r += red(c); g += green(c); b += blue(c); t++; } } return color(r/t, g/t, b/t); } void keyPressed() { if (keyCode == UP) { k++; createMosaic(); } else if (k > 1 && keyCode == DOWN) { k--; createMosaic(); } }