Functional Python Programming

(Wang) #1
Chapter 9


  • We can see if caching intermediate results will reduce the amount of
    redundant calculation. The question arises of how many colors are the
    same and how many colors are unique.

  • We can look for a radical change in the algorithm.


We'll combine the last two points by computing all the possible comparisons between
source colors and target colors. In this case, as in many other contexts, we can easily
enumerate the entire mapping and avoid redundant calculation when done on a
pixel-by-pixel basis. We'll also change the algorithm from a series of comparisons
to a series of simple lookups in a mapping object.


When looking at this idea of precomputing all transformations for source color
to target color, we need some overall statistics for an arbitrary image. The code
associated with this book includes IMG_2705.jpg. Here is a basic algorithm to
collect some data from the specified image:


from collections import defaultdict, Counter


palette = defaultdict(list)


for xy_p in pixel_iter(img):


xy, p = xy_p


palette[p].append(xy)


w, h = img.size


print(""("Total pixels", w*h)


print(""("Total colors", len(palette)))))


We collected all pixels of a given color into a list organized by color. From this,
we'll learn the first of the following facts:



  • The total number of pixels is 9,980,928. This is not surprising for a 10
    megapixel image.

  • The total number of colors is 210,303. If we try to compute the Euclidean
    distance between actual colors and the 133 colors, we would merely do
    27,970,299 calculations, which might take about 76 seconds.

  • Using a 3-bit mask, 0b11100000, there are 214 colors used out of
    a possible 512.

  • Using a 4-bit mask, 0b11110000, there are 1,150 colors used out of 4,096.

  • Using a 5-bit mask, 0b11111000, there are 5,845 colors used out of 32,768.

  • Using a 6-bit mask, 0b11111100, there are 27,726 colors out of 262,144.

Free download pdf