monochrome dithering in JavaScript (Bayer, Atkinson, Floyd–Steinberg)
Here are all of my monochrome dither functions, usable as a web worker: https://github.com/meemoo/meemooapp/blob/master/src/nodes/image-monochrome-worker.js
Live demo with webcam: http://meemoo.org/iframework/#gist/3721129
I do this as a debug code:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = "http://i.stack.imgur.com/tHDY8.png";
img.onload = function() {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage( this, 0, 0, this.width, this.height );
var imageData = ctx.getImageData( 0, 0, this.width, this.height);
var depth = 32;
// Matrix
var threshold_map_4x4 = [
[ 1, 9, 3, 11 ],
[ 13, 5, 15, 7 ],
[ 4, 12, 2, 10 ],
[ 16, 8, 14, 6 ]
];
// imageData
var width = imageData.width;
var height = imageData.height;
var pixel = imageData.data;
var x, y, a, b;
// filter
for ( x=0; x<width; x++ )
{
for ( y=0; y<height; y++ )
{
a = ( x * height + y ) * 4;
b = threshold_map_4x4[ x%4 ][ y%4 ];
pixel[ a + 0 ] = ( (pixel[ a + 0 ]+ b) / depth | 0 ) * depth;
pixel[ a + 1 ] = ( (pixel[ a + 1 ]+ b) / depth | 0 ) * depth;
pixel[ a + 2 ] = ( (pixel[ a + 2 ]+ b) / depth | 0 ) * depth;
//pixel[ a + 3 ] = ( (pixel[ a + 3 ]+ b) / depth | 3 ) * depth;
}
}
ctx.putImageData( imageData, 0, 0);
};
document.body.appendChild(canvas);
And it seems to work fine, you can change the depth variable to change the posterization.