Functional Python Programming

(Wang) #1

More Itertools Techniques


Computing distances


A number of decision-making problems require that we find a close-enough match.
We might not be able to use a simple equality test. Instead, we have to use a distance
metric and locate items with the shortest distance to our target. For text, we might
use the Levenshtein distance; this shows how many changes are required to get from
a given block of text to our target.


We'll use a slightly simpler example. This will involve very simple math. However,
even though it's simple, it doesn't work out well if we approach it naively.


When doing color matching, we won't have a simple equality test. We're rarely able
to check for the exact equality of pixel colors. We're often forced to define a minimal
distance function to determine whether two colors are close enough, without
being the same three values of R, G, and B. There are several common approaches,
including the Euclidean distance, Manhattan distance, and yet other complex
weightings based on visual preferences.


Here are the Euclidean and Manhattan distance functions:


def euclidean(pixel, color):
return math.sqrt(sum(map(lambda x, y: (x-y)**2, pixel,
color.rgb)))))))
def manhattan(pixel, color):
return sum(map(lambda x, y: abs(x-y), pixel, color.rgb)))))


The Euclidean distance measures the hypotenuse of a right-angled triangle among
the three points in an RGB space. The Manhattan distance sums the edges of each
leg of the right-angled triangle among the three points. The Euclidean distance offers
precision where the Manhattan distance offers calculation speed.


Looking forward, we're aiming for a structure that looks like this. For each
individual pixel, we can compute the distance from that pixel's color to the available
colors in a limited color set. The results of this calculation for a single pixel might
look like this:


(((0, 0), (92, 139, 195), Color(rgb=(239, 222, 205), name='Almond'),
169.10943202553784), ((0, 0), (92, 139, 195),
Color(rgb=(255, 255, 153), name='Canary'), 204.42357985320578),
((0, 0), (92, 139, 195), Color(rgb=(28, 172, 120), name='Green'),
103.97114984456024), ((0, 0), (92, 139, 195),
Color(rgb=(48, 186, 143), name='Mountain Meadow'),
82.75868534480233), ((0, 0), (92, 139, 195),
Color(rgb=(255, 73, 108), name='Radical Red'), 196.19887869200477),
((0, 0), (92, 139, 195), Color(rgb=(253, 94, 83),
name='Sunset Orange'), 201.2212712413874), ((0, 0), (92, 139, 195),
Color(rgb=(255, 174, 66), name='Yellow Orange'), 210.7961100210343))

Free download pdf