Getting ready

We will illustrate the image-scanning process by accomplishing a simple task—reducing the number of colors in an image.

Color images are composed of three-channel pixels. Each of these channels corresponds to the intensity value of one of the three primary colors: red, green, and blue. Since each of these values is an 8-bit unsigned character, the total number of colors is 256 x 256 x 256, which is more than 16 million colors. Consequently, to reduce the complexity of analysis, it is sometimes useful to reduce the number of colors in an image. One way to achieve this goal is simply to subdivide the RGB space into cubes of equal sizes. For example, if you reduce the number of colors in each dimension by 8, then you would obtain a total of 32 x 32 x 32 colors. Each color in the original image is then assigned a new color value in the color-reduced image that corresponds to the value in the center of the cube to which it belongs.

Therefore, the basic color reduction algorithm is simple. If N is the reduction factor, then divide the value by N (the integer division, therefore, the remainder is lost) for each pixel in the image and for each channel of this pixel. Then, multiply the result by N; this will give you the multiple of N just below the input pixel value. Just add N/2 and you obtain the central position of the interval between two adjacent multiples of N. If you repeat this process for each 8-bit channel value, then you will obtain a total of 256/N x 256/N x 256/N possible color values.