Created
March 14, 2014 00:20
-
-
Save becojo/9539879 to your computer and use it in GitHub Desktop.
Convolution matrix script in Processing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PImage img; | |
void setup() { | |
img = loadImage("img.jpg"); | |
size(img.width, img.height); | |
} | |
void keyPressed() { | |
if(key == ' ') saveFrame("frame-" + minute() + "-" + second() + "-#########" + ".png"); | |
} | |
float[][] randMatrix() { | |
int s = 3; | |
float b = 0.00002; | |
float[][] matrix = new float[s][s]; | |
int i, j; | |
for(i = 0; i < s; i++) { | |
for(j = 0; j < s; j++) { | |
matrix[i][j] = random(-b, b); | |
} | |
} | |
return matrix; | |
} | |
float[][] matrix = randMatrix(); | |
void draw() { | |
loadPixels(); | |
apply(matrix); | |
updatePixels(); | |
} | |
void mousePressed() { | |
image(img, 0, 0, width, height); | |
matrix = randMatrix(); | |
} | |
color get(int x, int y) { | |
int pos = y * width + x; | |
if(pos > 0 && pos < pixels.length) { | |
return pixels[pos]; | |
} else { | |
return 0; | |
} | |
} | |
void apply(float[][] matrix) { | |
int mi, mj; | |
int pi, pj; | |
int c = matrix.length / 2; | |
float sum; | |
int b; | |
int[] newPixels = new int[pixels.length]; | |
for(pi = 0; pi < width; pi++) { | |
for(pj = 0; pj < height; pj++) { | |
sum = 0; | |
for(mi = 0; mi < matrix.length; mi++) { | |
for(mj = 0; mj < matrix.length; mj++) { | |
sum += get(pi + mi - c, pj + mj - c) * matrix[mi][mj]; | |
} | |
} | |
newPixels[pj * width + pi] = int(sum) | 0xff000000; | |
} | |
} | |
for(pi = 0; pi < pixels.length; pi++) { | |
pixels[pi] = newPixels[pi]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment