Skip to content

Instantly share code, notes, and snippets.

@ramayac
Created August 13, 2013 21:18
Show Gist options
  • Save ramayac/6225803 to your computer and use it in GitHub Desktop.
Save ramayac/6225803 to your computer and use it in GitHub Desktop.
Image Dither algorithm
//Image Dithering
//http://www.processing.org/discourse/beta/num_1203512880.html
PImage ditherImage(PImage img) {
PImage ditheredImg = img.get(0, 0, img.width, img.height);
// tile = 2*2 pixels
int[] tilePixelColors = new int[4];
float[] bias = new float[] {
0.25, .75, 0.5, 0.0
};
int pixelPosition;
float valScale = 1.0 / 255.0;
// rows
for (int i=0; i<img.height/2.0; i++) {
// coloumns
for (int j=0; j<img.width/2.0; j++) {
pixelPosition = i*2*img.width + j*2;
tilePixelColors[0] = (int) (bias[0] + valScale*greyValue(img.pixels[pixelPosition]));
tilePixelColors[1] = (int) (bias[1] + valScale*greyValue(img.pixels[pixelPosition+1]));
tilePixelColors[2] = (int) (bias[2] + valScale*greyValue(img.pixels[pixelPosition+img.width]));
tilePixelColors[2] = (int) (bias[3] + valScale*greyValue(img.pixels[pixelPosition+img.width+1]));
ditheredImg.pixels[pixelPosition] = color(255*tilePixelColors[0]);
ditheredImg.pixels[pixelPosition+1] = color(255*tilePixelColors[1]);
ditheredImg.pixels[pixelPosition+img.width] = color(255*tilePixelColors[2]);
ditheredImg.pixels[pixelPosition+img.width+1] = color(255*tilePixelColors[3]);
}
}
return ditheredImg;
}
int greyValue(int _color) {
return (int)((red(_color) + green(_color) + blue(_color)) / 3.0) ;
}
PImage imgO, imgD;
void setup(){
size(800, 600);
imgO = loadImage("Water lilies.jpg");
imgD = ditherImage(imgO);
}
void draw(){
image(imgD, 0, 0, width, height);
noLoop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment