Functional Python Programming

(Wang) #1
Chapter 9

Once we have the palette of all 200,000 colors, we can apply the fast Manhattan
distance to locate the nearest color in an output, such as the Crayola colors. This will
use the algorithm for color matching shown earlier to compute the mapping instead
of a result image. The difference will center on using the palette.keys() function
instead of the pixel_iter() function.


We'll fold in yet another optimization: truncation. This will give us an even
faster algorithm.


Combining two transformations


When combining multiple transformations, we can build a more complex mapping
from source through intermediate targets to the result. To illustrate this, we'll
truncate the colors as well as apply a mapping.


In some problem contexts, truncation can be difficult. In other cases, it's often
quite simple. For example, truncating US postal ZIP codes from 9 to 5 characters is
common. Postal codes can be further truncated to three characters to determine a
regional facility that represents a larger geography.


For colors, we can use the bit-masking shown previously to truncate colors form
three 8-bit values (24 bits, 16 million colors) to three 3-bit values (9 bits, 512 colors).


Here is a way to build a color map that combines both distances to a given set of
colors and truncation of the source colors:


bit3 = range(0, 256, 0b100000)


best = (min(((((euclidean(rgb, c), rgb, c) for c in colors)


for rgb in product(bit3, bit3, bit3)))))


color_map = dict(((((b[1], b[2].rgb) for b in best)


We created a range object, bit3, that will iterate through all eight of the 3-bit
color values.


The range objects aren't like ordinary iterators; they can be used
multiple times. As a result of this, the product(bit3, bit3,
bit3) expression will produce all 512 color combinations that we'll
use as the output colors.

For each truncated RGB color, we created a three tuple that has (0) the distance from
all crayon colors, (1) the RGB color, and (2) the crayon Color object. When we ask for
the minimum value of this collection, we'll get the closest crayon Color object to the
truncated RGB color.

Free download pdf