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.
The code is in the quantizing_colors.ipynb
file in this book's code bundle:
import numpy as np import cv2 import matplotlib.pyplot as plt import dautil as dl from scipy.misc import face
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)
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()
kmeans()
function documented at http://docs.opencv.org/3.0.0/d5/d38/group__core__cluster.html#ga9a34dc06c6ec9460e90860f15bcd2f88 (retrieved December 2015)