Search Unity

Dithering algorithms

Discussion in 'Scripting' started by Agent_007, Sep 5, 2015.

  1. Agent_007

    Agent_007

    Joined:
    Dec 18, 2011
    Posts:
    899
    Dithering algorithms

    This post contains source code and sample images of dithering algorithms that can be used in Unity3d. There are total of 8 different dithering algorithms. You can find more info about the algorithms from blog post made by Tanner Helland.

    Definition
    "Dither is an intentionally applied form of noise used to randomize quantization error, preventing large-scale patterns such as color banding in images." Wikipedia

    What can I do with it
    With Unity you can use dithering e.g. to convert 32 bit textures to 16/8 bit textures in such way that new image doesn't look so bad to the human eye than it would if just color reduction was done to it.

    You can do this on Editor or on Device.

    How do I use it
    It is very simple. Just follow following example
    Code (CSharp):
    1. private static Color32 TrueColorToWebSafeColor(Color32 inputColor)
    2. {
    3.         Color32 returnColor = new Color32( (byte)(Mathf.RoundToInt(inputColor.r / 51.0f) * 51),
    4.                                             (byte)(Mathf.RoundToInt(inputColor.g / 51.0f) * 51),
    5.                                             (byte)(Mathf.RoundToInt(inputColor.b / 51.0f) * 51),
    6.                                             byte.MaxValue);
    7.         return returnColor;
    8. }
    9.  
    10. DitheringBase method = new FloydSteinbergDithering(TrueColorToWebSafeColor);
    11. Texture2D dithered = method.DoDithering(input);
    First you have to have a color reduction function (in this case TrueColorToWebSafeColor). Then you create new instance of chosen algorithm (in this case FloydSteinbergDithering) and finally call DoDithering of dithering instance with chosen input Texture2D. It then returns the dithered Texture2D.


    Source code
    GitHub
    Zip file

    License
    Source code files are released into the public domain.

    Parrot image is made from image that comes from Kodak Lossless True Color Image Suite and it doesn't have any specific license.


    Sample image
    I took the famous parrot image and reduced its size to 384x256. Then I ran the image (which has 64655 different colors) with all dithering methods and using Web safe colors as palette. I also calculated PSNR and SSIM values for dithered images.

    Resized image has filesize of 244 kB as PNG. All dithered files have filesize between 63-70 kB.

     

    Attached Files: