lib_jsl_dsp/discrete/image/segmentation/
otsu.rs1use crate::discrete::image::filters::histogram_equalization::histogram;
17use lib_jsl_core::ErrorsJSL;
18use ndarray::Array2;
19
20#[derive(Clone, Debug, PartialEq)]
22#[non_exhaustive]
23pub struct OtsuResult {
24 pub threshold: u8,
26 pub binary: Array2<u8>,
28 pub between_class_variance: f64,
30 pub separability: f64,
32}
33
34pub fn otsu_threshold(image: &Array2<u8>) -> Result<u8, ErrorsJSL> {
36 Ok(otsu(image)?.threshold)
37}
38
39#[allow(clippy::needless_range_loop)]
40pub fn otsu(image: &Array2<u8>) -> Result<OtsuResult, ErrorsJSL> {
42 if image.is_empty() {
43 return Err(ErrorsJSL::InvalidInputRange("Image must be non-empty"));
44 }
45 let hist = histogram(image);
46 let total = image.len() as f64;
47 let sum_all: f64 = hist.iter().enumerate().map(|(i, &h)| i as f64 * h as f64).sum();
48 let mean_all = sum_all / total;
49 let variance_all: f64 = hist.iter().enumerate().map(|(i, &h)| (i as f64 - mean_all).powi(2) * h as f64).sum::<f64>() / total;
50
51 let (mut w0, mut sum0) = (0.0f64, 0.0f64);
52 let mut best = 0.0f64;
53 let mut best_range = (0usize, 0usize);
54 for t in 0..256 {
56 w0 += hist[t] as f64;
57 sum0 += t as f64 * hist[t] as f64;
58 let w1 = total - w0;
59 if w0 == 0.0 || w1 == 0.0 {
60 continue;
61 }
62 let (m0, m1) = (sum0 / w0, (sum_all - sum0) / w1);
63 let sb = (w0 / total) * (w1 / total) * (m0 - m1) * (m0 - m1);
64 if sb > best + 1e-12 * best.max(1.0) {
65 best = sb;
66 best_range = (t, t);
67 } else if (sb - best).abs() <= 1e-12 * best.max(1.0) && best > 0.0 {
68 best_range.1 = t;
69 }
70 }
71 let threshold = if best > 0.0 {
73 ((best_range.0 + best_range.1) / 2) as u8
74 } else {
75 image.iter().copied().max().unwrap()
77 };
78 Ok(OtsuResult {
79 threshold,
80 binary: image.mapv(|v| if v > threshold { 255 } else { 0 }),
81 between_class_variance: best,
82 separability: if variance_all > 0.0 { best / variance_all } else { 0.0 },
83 })
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 fn lcg(seed: &mut u64) -> f64 {
91 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
92 ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
93 }
94
95 fn gauss(seed: &mut u64) -> f64 {
96 (0..12).map(|_| lcg(seed)).sum::<f64>()
97 }
98
99 fn bimodal(sigma: f64, seed: &mut u64) -> (Array2<u8>, Array2<bool>) {
101 let truth = Array2::from_shape_fn((80, 80), |(r, c)| (20..60).contains(&r) && (25..70).contains(&c));
102 let img = Array2::from_shape_fn((80, 80), |i| {
103 let base = if truth[i] { 180.0 } else { 60.0 };
104 (base + sigma * gauss(seed)).round().clamp(0.0, 255.0) as u8
105 });
106 (img, truth)
107 }
108
109 #[test]
110 fn finds_the_valley_between_two_modes_and_segments_correctly() {
111 let mut seed = 3;
112 let (img, truth) = bimodal(12.0, &mut seed);
113 let r = otsu(&img).unwrap();
114 assert!((r.threshold as i32 - 120).abs() <= 8, "threshold {}", r.threshold);
115 let wrong = r.binary.indexed_iter().filter(|(i, v)| (**v == 255) != truth[*i]).count();
116 assert!(wrong < 20, "{wrong} misclassified pixels out of {}", img.len());
117 assert!(r.separability > 0.85, "{}", r.separability);
118 assert!(r.binary.iter().all(|v| *v == 0 || *v == 255));
119 assert_eq!(otsu_threshold(&img).unwrap(), r.threshold);
120 }
121
122 #[test]
123 fn two_gray_levels_give_a_threshold_between_them_and_perfect_separability() {
124 let img = Array2::from_shape_fn((10, 10), |(r, _)| if r < 3 { 50u8 } else { 200u8 });
125 let r = otsu(&img).unwrap();
126 assert!((50..200).contains(&r.threshold), "{}", r.threshold);
127 assert!(r.binary.row(0).iter().all(|v| *v == 0) && r.binary.row(9).iter().all(|v| *v == 255));
128 assert!((r.separability - 1.0).abs() < 1e-9);
129 }
130
131 #[test]
132 fn robust_to_unequal_class_sizes_and_more_noise() {
133 let mut seed = 4;
134 let truth = Array2::from_shape_fn((100, 100), |(r, c)| (40..52).contains(&r) && (40..55).contains(&c));
136 let img = Array2::from_shape_fn((100, 100), |i| ((if truth[i] { 200.0 } else { 70.0 }) + 15.0 * gauss(&mut seed)).round().clamp(0.0, 255.0) as u8);
137 let r = otsu(&img).unwrap();
138 assert!((90..180).contains(&(r.threshold as i32)), "threshold {}", r.threshold);
139 let found = r.binary.iter().filter(|v| **v == 255).count();
140 assert!((found as f64 / truth.iter().filter(|v| **v).count() as f64 - 1.0).abs() < 0.15, "found {found}");
141 }
142
143 #[test]
144 fn a_constant_image_has_nothing_to_separate() {
145 let img = Array2::from_elem((6, 6), 90u8);
146 let r = otsu(&img).unwrap();
147 assert_eq!(r.threshold, 90);
148 assert!(r.binary.iter().all(|v| *v == 0));
149 assert_eq!((r.between_class_variance, r.separability), (0.0, 0.0));
150 assert!(otsu(&Array2::<u8>::zeros((0, 3))).is_err());
151 }
152
153 #[test]
154 fn matches_a_brute_force_search_on_a_random_histogram_image() {
155 let mut seed = 8;
156 let img = Array2::from_shape_fn((40, 40), |_| ((lcg(&mut seed) + 0.5).powi(2) * 200.0) as u8);
157 let r = otsu(&img).unwrap();
158 let pix: Vec<f64> = img.iter().map(|&v| v as f64).collect();
160 let within = |t: u8| {
161 let (lo, hi): (Vec<f64>, Vec<f64>) = pix.iter().partition(|&&v| v <= t as f64);
162 let var = |s: &Vec<f64>| if s.is_empty() { 0.0 } else { let m = s.iter().sum::<f64>() / s.len() as f64; s.iter().map(|x| (x - m).powi(2)).sum::<f64>() };
163 var(&lo) + var(&hi)
164 };
165 let best = (0..255u8).min_by(|&a, &b| within(a).partial_cmp(&within(b)).unwrap()).unwrap();
166 assert!((within(r.threshold) - within(best)).abs() < 1e-6 * within(best).max(1.0), "{} vs {}", r.threshold, best);
167 }
168}