Quantizing colors

In ancient times, computer games were practically monochromatic. Many years later, the Internet allowed us to download images, but the Web was slow, so compact images with few colors were preferred. We can conclude that restricting the number of colors is traditional. Color is a dimension of images, so we can speak of dimensionality reduction if we remove colors from an image. The actual process is called color quantization.

Usually, we represent RGB (red, green, and blue) values in three-dimensional space for each pixel and then cluster the points. For each cluster, we are left with a corresponding average color. In this recipe, we will use k-means clustering (refer to the Clustering streaming data with Spark recipe), although this is not necessarily the best algorithm.

Getting ready

Follow the instructions in the Setting up OpenCV recipe.

How to do it...

The code is in the quantizing_colors.ipynb file in this book's code bundle:

  1. The imports are as follows:
    import numpy as np
    import cv2
    import matplotlib.pyplot as plt
    import dautil as dl
    from scipy.misc import face
  2. Plot the original image as follows:
    sp = dl.plotting.Subplotter(2, 2, context)
    img = face()
    dl.plotting.img_show(sp.ax, img)
    sp.label()
    Z = img.reshape((-1, 3))
    
    Z = np.float32(Z)
  3. Apply k-means clustering and plot the result:
    criteria = (cv2.TERM_CRITERIA_MAX_ITER, 7, 1.0)
    
    for k in [2, 4, 8]:
        _, label, center = cv2.kmeans(Z, k, None, criteria, 7,
                                      cv2.KMEANS_RANDOM_CENTERS)
    
        center = np.uint8(center)
        res = center[label.flatten()]
        res2 = res.reshape((img.shape))
    
        dl.plotting.img_show(sp.next_ax(), res2)
        sp.label()

Refer to the following screenshot for the end result:

How to do it...

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset