graph_based_image_segmentation/segmentation/
manhattan_distance.rs

1use crate::graph::ImageNodeColor;
2use crate::segmentation::Distance;
3
4/// Manhattan (i.e. L1) distance.
5///
6/// ## Example
7/// ```
8/// use graph_based_image_segmentation::{Distance, ImageNodeColor, ManhattanRGB};
9/// let a = ImageNodeColor::new_bgr(0, 0, 0);
10/// let b = ImageNodeColor::new_bgr(0, 255, 255);
11/// let distance = ManhattanRGB::default();
12/// assert_eq!(distance.distance(&a, &b), 0.6666667);
13/// ```
14pub struct ManhattanRGB {}
15
16unsafe impl Sync for ManhattanRGB {}
17unsafe impl Send for ManhattanRGB {}
18
19const NORMALIZATION_TERM: f32 = 255f32 + 255f32 + 255f32;
20
21impl Default for ManhattanRGB {
22    fn default() -> Self {
23        Self {}
24    }
25}
26
27impl Distance for ManhattanRGB {
28    #[inline(always)]
29    fn distance(&self, n: &ImageNodeColor, m: &ImageNodeColor) -> f32 {
30        let dr = n.r as f32 - m.r as f32;
31        let dg = n.g as f32 - m.g as f32;
32        let db = n.b as f32 - m.b as f32;
33        (dr.abs() + dg.abs() + db.abs()) / NORMALIZATION_TERM
34    }
35}