Functional Python Programming

(Wang) #1
Chapter 9

We've shown an overall tuple that consists of a number of four tuples. Each of the
four tuples contains the following contents:



  • The pixel's coordinates, for example, (0,0)

  • The pixel's original color, for example, (92, 139, 195)

  • A Color object from our set of seven colors, for example, Color(rgb=(239,
    222, 205),name='Almond')

  • The Euclidean distance between the original color and the given Color object


We can see that the smallest Euclidean distance is the closest match color. This kind
of reduction is done easily with the min() function. If the overall tuple is assigned to
a variable name, choices, the pixel-level reduction would look like this:


min(choices, key=lambda xypcd: xypcd[3]))])


We've called each four tuple an xypcd, that is, an xy coordinate, pixel, color, and
distance. The minimum distance calculation will then pick a single four tuple as the
optimal match between pixel and color.


Getting all pixels and all colors


How do we get to the structure that contains all pixels and all colors? The answer is
simple but, as we'll see, less than optimal.


One way to map pixels to colors is to enumerate all pixels and all colors using the
product() function:


xy = lambda xyp_c: xyp_c[0][0]


p = lambda xyp_c: xyp_c[0][1]


c = lambda xyp_c: xyp_c[1]


distances= (( = ((xy(item), p(item), c(item), euclidean(p(item),
c(item)))


for item in product(pixel_iter(img), colors)))))


The core of this is the product(pixel_iter(img), colors) method that creates all
pixels combined with all colors. We will do a bit of restructuring of the data to flatten
it out. We will apply the euclidean() function to compute distances between pixel
colors and Color objects.

Free download pdf