Skip to main content

lib_jsl_dsp/discrete/image/segmentation/
otsu.rs

1//! Otsu's method: automatic global thresholding.
2//!
3//! Given the gray-level histogram of an image, Otsu's method picks the threshold `t` that
4//! maximises the *between-class variance* of the two classes it creates (pixels `<= t` and
5//! pixels `> t`), equivalently minimises the within-class variance. For a bimodal histogram
6//! (dark background, bright foreground) it lands in the valley between the modes without any
7//! tuning. With class probabilities `ω₀(t)`, `ω₁(t)` and means `μ₀(t)`, `μ₁(t)`:
8//!
9//! `σ_b²(t) = ω₀ ω₁ (μ₀ − μ₁)²`
10//!
11//! When several thresholds tie (as for an image with only two gray levels), the middle of the
12//! tied range is returned.
13//!
14//! See the book entry [Segmentation](https://jwkunz.github.io/lib_jsl/book/image/segmentation.html#otsus-threshold).
15
16use crate::discrete::image::filters::histogram_equalization::histogram;
17use lib_jsl_core::ErrorsJSL;
18use ndarray::Array2;
19
20/// The result of Otsu thresholding.
21#[derive(Clone, Debug, PartialEq)]
22#[non_exhaustive]
23pub struct OtsuResult {
24    /// The threshold: pixels `<= threshold` are background.
25    pub threshold: u8,
26    /// The thresholded image: 0 for background, 255 for foreground.
27    pub binary: Array2<u8>,
28    /// The maximised between-class variance.
29    pub between_class_variance: f64,
30    /// Separability `σ_b² / σ_total²` in `[0, 1]`: near 1 for cleanly bimodal images, 0 for a flat one.
31    pub separability: f64,
32}
33
34/// Computes the Otsu threshold of an 8-bit image.
35pub fn otsu_threshold(image: &Array2<u8>) -> Result<u8, ErrorsJSL> {
36    Ok(otsu(image)?.threshold)
37}
38
39#[allow(clippy::needless_range_loop)]
40/// Thresholds an 8-bit image with Otsu's method.
41pub 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    // ANCHOR: otsu
55    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    // ANCHOR_END: otsu
72    let threshold = if best > 0.0 {
73        ((best_range.0 + best_range.1) / 2) as u8
74    } else {
75        // A single gray level: no meaningful split; everything is background.
76        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    /// Dark background (mean 60) with a bright rectangle (mean 180), plus Gaussian noise.
100    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        // A small bright object on a large dark background: heavy class imbalance.
135        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        // Brute force: recompute within-class variance directly from the pixels.
159        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}