2

I'm trying to ordered dither images in HTML5 canvas down or close to 256 colours every time. I have the dither algorithm working which you can see on my test page (Check the browser console for the colour counts).

But I'm having trouble understanding how I can select or generate the optimal depth and threshold map for different images, the results vary massively depending on how many colours the original image has.

I have one of these functions for 2x2,3x3,4x4,8x8 maps so far,

    function ditherImageData4x4(imageDataToDither){
    var depth = $('#depth').val();
    var threshold_map = [
        [  1,  9,  3, 11 ],
        [ 13,  5, 15,  7 ],
        [  4, 12,  2, 10 ],
        [ 16,  8, 14,  6 ]
    ];
    var dataWidth  = imageDataToDither.width;
    var dataHeight = imageDataToDither.height;
    var pixel  = imageDataToDither.data;
    var x, y, a, b;
    for ( x=0; x<dataWidth; x++ ){
        for ( y=0; y<dataHeight; y++ ){
            a    = ( x * dataHeight + y ) * 4;
            b    = threshold_map[ 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;
        }
    }
    return pixel;
};
neue
  • 93
  • 1
  • 7
  • What do you mean by "algorithm working"? For the most part, the number of colours increases after the 'dither'. – enhzflep Mar 01 '13 at 02:31
  • I mean it dithers the image, but you have to choose the correct map and depth to get the image below 256. 64 an 8x8 are optimal for the 'spectrum' image. But 24 and 4x4 are best the 'lena'. There must be some way of working it out. – neue Mar 01 '13 at 03:05
  • 2
    Ah yes, of course - I see now. Never tried dithering before (well not in over half a lifetime, anyway) This page looks to be quite informative and a good reference(but I don't know if it addresses your question): http://bisqwit.iki.fi/story/howto/dither/jy/ – enhzflep Mar 01 '13 at 04:09
  • Yeah I've seen that and most other pages from Google about it. That one is mostly about dithering to a fixed predefined palette, I'm hoping to get a decent dither with a palette suitable to the image. – neue Mar 01 '13 at 12:51

0 Answers0