Skip to content

Commit

Permalink
cache lab calculation for color
Browse files Browse the repository at this point in the history
  • Loading branch information
Tony Crisci committed May 24, 2018
1 parent 63f4d99 commit cf81b09
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub fn color_from_triplet(name: &'static str, t: (u8, u8, u8)) -> Color {

impl Color {
/// http://www.easyrgb.com/en/math.php
fn to_lab(&self) -> (f32, f32, f32) {
pub fn to_lab(&self) -> (f32, f32, f32) {
let xyz_normalize = |c: f32| {
let c_normal = c / 255.0;
if c_normal > 0.04045 {
Expand Down Expand Up @@ -119,9 +119,9 @@ impl Color {
(l, a, b)
}

pub fn distance(&self, other: &Self) -> f32 {
pub fn distance(&self, lab: (f32, f32, f32)) -> f32 {
let (sl, sa, sb) = self.to_lab();
let (ol, oa, ob) = other.to_lab();
let (ol, oa, ob) = lab;

let dl = sl - ol;
let da = sa - oa;
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,13 @@ impl ColorNamer {

pub fn name_hex_color(&self, hex: &str) -> Result<String, ColorError> {
let color = color::color_from_hex("", &hex)?;
let lab = color.to_lab();

let mut min_distance: f32 = std::f32::MAX;
let mut closest_color = color;

for c in &self.colors {
let distance = color.distance(c);
let distance = c.distance(lab);
if distance < min_distance {
min_distance = distance;
closest_color = *c;
Expand Down

0 comments on commit cf81b09

Please sign in to comment.