Average color using spatial convolution
in
Programming Questions
•
10 months ago
Hi, it's me again Nkjao. I'm working on a photomosaic project, which requires me to divide a source image into grids of 25x25 pixel tiles. Then I average that area of color pixels and return it to fill that tile.
I'm not sure if my code did what I intended, or just simply fill each tile with the color picked up from the center (x, y) of the tile. I copied the convolution function from Daniel Shiffman's book.
Please see my code here:
- PImage mao;
- int cols = 20;
- int rows = 20;
- int cellwidth;
- int cellheight;
- int matrixsize;
- float[][] matrix;
- void setup() {
- size(500, 500);
- mao = loadImage("Mao_Bear_MoMA_517x517.png");
- matrixsize = 25;
- // fill up the convolution matrix
- matrix = new float[matrixsize][matrixsize];
- for (int i = 0; i < matrixsize; i++) {
- for (int j = 0; j < matrixsize; j++) {
- matrix[i][j] = 1/matrixsize;
- matrix[matrixsize/2][matrixsize/2] = 1; // for no reason, if I comment out this line, I get a dark background.
- }
- }
- }
- void draw() {
- mao.loadPixels();
- for (int i = 0; i < mao.width; i += matrixsize) {
- for (int j = 0; j < mao.height; j += matrixsize) {
- color c = convolution(i, j, matrix, matrixsize, mao);
- // fill the "tile" with its averaged color
- fill(c);
- noStroke();
- //strokeWeight(3);
- rectMode(CENTER);
- rect(i+matrixsize/2, j+matrixsize/2, matrixsize, matrixsize);
- }
- }
- }
- color convolution(int x, int y, float[][] matrix, int matrixsize, PImage img) {
- float rtotal = 0.0;
- float gtotal = 0.0;
- float btotal = 0.0;
- int offset = matrixsize / 2;
- // Loop through convolution matrix
- for (int i = 0; i < matrixsize; i++) {
- for (int j= 0; j < matrixsize; j++) {
- // What pixel are we testing
- int xloc = x+i-offset;
- int yloc = y+j-offset;
- int loc = xloc + img.width*yloc;
- // Prevent walking off the image's pixels array
- loc = constrain(loc, 0, img.pixels.length-1);
- // Calculate the convolution
- rtotal += (red(img.pixels[loc]) * matrix[i][j]);
- gtotal += (green(img.pixels[loc]) * matrix[i][j]);
- btotal += (blue(img.pixels[loc]) * matrix[i][j]);
- }
- }
- rtotal = constrain(rtotal, 0, 255);
- gtotal = constrain(gtotal, 0, 255);
- btotal = constrain(btotal, 0, 255);
- return color(rtotal, gtotal, btotal);
- }
1