Function image_go_nord::utils::delta [−][src]
pub fn delta(a: &[u8], b: &[u8]) -> i32
Expand description
Euclidian distance squared between colors
Uses the 3-dimensional euclidian distance formula to get the distance
between two colors. This function returns an i32 because the
intermediate calculations would overflow u8. It is guaranteed to not
overflow for slices with a length at most 33,025, but if you reach this
limit, I guarantee you’re doing something wrong.
let a = [173, 87, 119, 255]; // a pinkish color let b = [0, 255, 255]; // cyan, my favorite color // `a` is rbga, but it doesn't matter. `delta` will only take components up to the length of //the smallest slice assert_eq!(delta(&a, &b), 76649);
delta takes two slices and zips them to calculate their component-wise
distance. This is safe because it will only take elements up to the last of
the shortest slice, which usually comes from a palette color (which is an
array).
This function can be proven not to overflow with some simple set theory. If
$d$ is the function delta, $B \subset \Z^+$ is the set of unsigned 8-bit
integers (u8), and $I \subset \Z$ is the set of signed 32-bit integers,
and we know $B \subset I$, then we can prove, for two arbitrary 8-bit
subpixel colors $x = (r_1, g_1, b_1)$ and $y = (r_2, g_2, b_2)$ (where $r
\in B \and g \in B \and b \in B$), that $\forall x \forall y, d(x, y) \in
I$.
$d$ can be defined as follows (where $n = min(|x|, |y|)$).
$$ d(x, y) = \sum_{i=1}^n (x_i - y_i)^2 $$
Since $d : B \rightarrow I$ and $min(A) < min(B) < max(B) < max(A)$, we just need to prove the range of $d$ does not exceed the minimum or maximum of its codomain.