Quantisation

Is where a value from a large or continuous set is mapped into smaller discrete values. An example is reducing the Bit Depth of an image.

You now have an 8-bit-per-channel image, meaning each channel can hold any of 256 distinct values. Suppose your target output device, or your target file format, can only represent N distinct values per channel, where N is much smaller than 256, for example N = 2 (true black and white) or N = 4. You need a function that maps every one of the 256 input values onto one of the N allowed output values.

For N = 2, step = 255, and this reduces to: output 0 if value < 128, output 255 otherwise. This special case is called Thresholding

The most direct such function divides the input range into N equal-width buckets and rounds each input to the center, or in the simplest implementation, to the nearest representable output level:

function quantize_channel(value, levels):
    # levels is N, the number of allowed output values, evenly
    # spaced across the 0-255 range inclusive of both endpoints
    step = 255 / (levels - 1)
    level_index = round(value / step)
    return round(level_index * step)
function quantize_image(image, width, height, levels):
    for each pixel in image:
        pixel.r = quantize_channel(pixel.r, levels)
        pixel.g = quantize_channel(pixel.g, levels)
        pixel.b = quantize_channel(pixel.b, levels)

Doing this produces a Quantisation Error which is used by Dithering algorithms to produce better images.

This is an image with a gradient

gradient.png

This is the same image quantised to 8 levels and 3 levels. Note the tiny stripe of pure red on the right

quantised-8.png

quantised-3.png