altered_perception/color_spaces/luma.rs
1use crate::Luma;
2use num_traits::cast::AsPrimitive;
3use rgb::RGB;
4
5impl<T> Luma<T> {
6 /// Converts an RGB pixel into a Luma pixel
7 ///
8 /// ```
9 /// use altered_perception::Luma;
10 /// use rgb::RGB;
11 ///
12 /// let rgb_pixel = RGB::new(1,2,3);
13 /// let luma_pixel: Luma<u8> = Luma::from_rgb::<u8>(rgb_pixel);
14 /// ```
15 pub fn from_rgb<N: std::convert::Into<f64>>(rgb_pixel: RGB<N>) -> Luma<T>
16 where
17 T: std::convert::Into<f64> + std::marker::Copy + 'static,
18 f64: AsPrimitive<T>,
19 {
20 Luma {
21 luminance: ((0.299 * (rgb_pixel.r.into()).powi(2)
22 + 0.587 * (rgb_pixel.g.into()).powi(2)
23 + 0.114 * (rgb_pixel.b.into()).powi(2))
24 .sqrt()
25 .round())
26 .as_(),
27 }
28 }
29
30 /// Creates a Luma pixel
31 pub fn new(luminance: T) -> Luma<T> {
32 Luma { luminance }
33 }
34
35 /// Converts a luma pixel into an RGB pixel
36 ///
37 /// ```
38 /// use altered_perception::Luma;
39 /// use rgb::RGB;
40 ///
41 /// let luma_pixel = Luma::new(155);
42 /// let rgb_pixel = Luma::to_rgb::<u8>(luma_pixel);
43 /// ```
44 pub fn to_rgb<N: std::convert::From<T>>(luma_pixel: Luma<T>) -> RGB<N>
45 where
46 T: Copy,
47 {
48 RGB {
49 r: luma_pixel.luminance.into(),
50 g: luma_pixel.luminance.into(),
51 b: luma_pixel.luminance.into(),
52 }
53 }
54}