Created
March 6, 2022 15:57
-
-
Save kettle11/666edd2645088392582950a8e471c7be to your computer and use it in GitHub Desktop.
Code for approximating color names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn get_approximate_color_name(color: koi::Color) -> String { | |
let considered_exact = 0.1; | |
let hues = [ | |
(0.0, "Pink"), | |
((29.0 / 360.), "Red"), | |
((53.0 / 360.), "Orange"), | |
((110.0 / 360.), "Yellow"), | |
((142.0 / 360.0), "Green"), | |
((195.0 / 360.0), "Cyan"), | |
((264.0 / 360.0), "Blue"), | |
((328.0 / 360.0), "Purple"), | |
(1.0, "Pink"), | |
]; | |
let (lightness, chroma, hue) = color.get_lightness_chroma_hue(); | |
// println!("LIGHTNESS: {:?}", lightness); | |
// println!("CHROMA: {:?}", chroma); | |
// println!("HUE: {:?}", hue); | |
if lightness > 0.98 && chroma < 0.05 { | |
return "White".into(); | |
} else if lightness == 0.0 { | |
return "Black".into(); | |
} else if lightness < 0.24 { | |
return "Near Black".into(); | |
} | |
let lightness_descriptor = if lightness > 0.8 { | |
"Light " | |
} else if lightness > 0.5 { | |
"" | |
} else { | |
"Dark " | |
}; | |
let chroma_descriptor = if chroma > 0.08 { | |
"" | |
} else if chroma > 0.05 { | |
"Grey-ish " | |
} else { | |
"Grey " | |
}; | |
for window in hues.windows(2) { | |
let left = window[0]; | |
let right = window[1]; | |
let window_size = right.0 - left.0; | |
if hue >= left.0 && hue <= right.0 { | |
let distance_to_left = hue - left.0; | |
let percent_to_left = distance_to_left / window_size; | |
let (first_name, second_name) = if percent_to_left < considered_exact { | |
(left.1, "") | |
} else if percent_to_left > (1.0 - considered_exact) { | |
(right.1, "") | |
} else if distance_to_left < 0.5 { | |
(left.1, right.1) | |
} else { | |
(right.1, left.1) | |
}; | |
return format!( | |
"{}{}{} {}", | |
chroma_descriptor, lightness_descriptor, first_name, second_name | |
); | |
} | |
} | |
// This should be unreachable, but return an empty String. | |
String::new() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment