Skip to content

Instantly share code, notes, and snippets.

@ramayac
Created August 14, 2013 16:40
Show Gist options
  • Save ramayac/6232898 to your computer and use it in GitHub Desktop.
Save ramayac/6232898 to your computer and use it in GitHub Desktop.
/*
Algoritmo de implementación de dither de Floyd-Steinberg
http://en.wikipedia.org/wiki/Dither
http://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering
http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT
http://processing.org/discourse/beta/num_1264007943.html
*/
PImage b, source;
int levels = 1;
void setup() {
size(400, 300);
//colorMode(RGB, 255);
b = loadImage("appleII.jpg");
b.filter(GRAY);
b.resize(width, height);
//source = createImage(b.width, b.height);
source = b;
noLoop();
}
void draw () {
float lNorm = 255/levels;
// FS Kernal
float d1 = 7.0 / 16;
float d2 = 3.0 / 16;
float d3 = 5.0 / 16;
float d4 = 1.0 / 16;
//println(d1 + ", " + d2 + ", " + d3 + ", " + d4);
int c, nc, lc, rc;
float r, g, b;
float nr, ng, nb;
float er, eg, eb;
float lr, lg, lb;
int x = 0, y = 0;
// Ordered Dithering Implementation
for (y = 0; y < source.height; y++) {
for (x = 0; x <= source.width; x++) {
// Retrieve current RGB value
c = source.get(x, y);
r = (c >> 16) & 0xFF;
g = (c >> 8) & 0xFF;
b = c & 0xFF;
// Normalize and scale to number of levels
// basically a cheap but crappy form of color quantization
nr = round((r/255) * levels) * lNorm;
ng = round((g/255) * levels) * lNorm;
nb = round((b/255) * levels) * lNorm;
// Set the current pixel
nc = color(nr, ng, nb);
source.set(x, y, nc);
// Quantization Error
er = r-nr;
eg = g-ng;
eb = b-nb;
// Apply the kernel
// +1, 0
lc = source.get(x + 1, y);
lr = (lc >> 16 & 0xFF) + d1 * er;
lg = (lc >> 8 & 0xFF) + d1 * eg;
lb = (lc & 0xFF) + d1 * eb;
source.set(x + 1, y, color(lr, lg, lb));
// -1, +1
lc = source.get(x - 1, y + 1);
lr = (lc >> 16 & 0xFF) + (d2*er);
lg = (lc >> 8 & 0xFF) + (d2*eg);
lb = (lc & 0xFF) + (d2*eb);
source.set(x - 1, y + 1, color(lr, lg, lb));
// 0, +1
lc = source.get(x, y + 1);
lr = (lc >> 16 & 0xFF) + (d3*er);
lg = (lc >> 8 & 0xFF) + (d3*eg);
lb = (lc & 0xFF) + (d3*eb);
source.set(x, y + 1, color(lr, lg, lb));
// +1, +1
lc = source.get(x+1, y+1);
lr = (lc >> 16 & 0xFF) + (d4*er);
lg = (lc >> 8 & 0xFF) + (d4*eg);
lb = (lc & 0xFF) + (d4*eb);
source.set(x+1, y+1, color(lr, lg, lb));
}
}
println("done");
image(source, 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment