scirs2-ndimage 0.4.2

N-dimensional image processing module for SciRS2 (scirs2-ndimage)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! Shape analysis: convex hull, contour extraction, shape descriptors, ellipse fitting,
//! and minimum bounding rectangle.
//!
//! # Overview
//!
//! This module provides geometric shape analysis tools operating on 2-D binary images
//! and point clouds:
//!
//! - **Convex hull** (Graham scan) for arbitrary 2-D point sets.
//! - **Contour extraction** using Moore-neighbourhood (8-connectivity) tracing.
//! - **Shape descriptors**: area, perimeter, circularity, eccentricity, aspect ratio,
//!   extent, solidity, convexity.
//! - **Ellipse fitting** via the algebraic least-squares method (Fitzgibbon et al.).
//! - **Minimum bounding rectangle** using the rotating calipers technique.

use crate::error::{NdimageError, NdimageResult};
use scirs2_core::ndarray::{Array2, ArrayView2};

// ─────────────────────────────────────────────────────────────────────────────
// Convex Hull – Graham Scan
// ─────────────────────────────────────────────────────────────────────────────

/// Compute the convex hull of a 2-D point set using the Graham scan algorithm.
///
/// Returns the hull vertices in counter-clockwise order.  If fewer than 3 distinct
/// points are supplied the function returns the (deduplicated) input sorted
/// lexicographically so callers always receive a valid polygon-like result.
///
/// # Arguments
///
/// * `points` – Slice of (x, y) coordinates.
///
/// # Errors
///
/// Returns [`NdimageError::InvalidInput`] when the input is empty.
///
/// # Example
///
/// ```
/// use scirs2_ndimage::shape_analysis::convex_hull_2d;
///
/// let pts = vec![(0.0_f64, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.5, 0.5)];
/// let hull = convex_hull_2d(&pts).unwrap();
/// assert_eq!(hull.len(), 4);
/// ```
pub fn convex_hull_2d(points: &[(f64, f64)]) -> NdimageResult<Vec<(f64, f64)>> {
    if points.is_empty() {
        return Err(NdimageError::InvalidInput(
            "convex_hull_2d: point set is empty".to_string(),
        ));
    }

    // Deduplicate
    let mut pts: Vec<(f64, f64)> = points.to_vec();
    pts.sort_by(|a, b| {
        a.0.partial_cmp(&b.0)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
    });
    pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-12 && (a.1 - b.1).abs() < 1e-12);

    if pts.len() < 3 {
        return Ok(pts);
    }

    // Cross product of vectors OA and OB
    let cross = |o: (f64, f64), a: (f64, f64), b: (f64, f64)| -> f64 {
        (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0)
    };

    let n = pts.len();
    let mut hull: Vec<(f64, f64)> = Vec::with_capacity(2 * n);

    // Lower hull
    for &p in &pts {
        while hull.len() >= 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
            hull.pop();
        }
        hull.push(p);
    }

    // Upper hull
    let lower_len = hull.len() + 1;
    for &p in pts.iter().rev() {
        while hull.len() >= lower_len && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
            hull.pop();
        }
        hull.push(p);
    }

    hull.pop(); // Remove last point (same as first)
    Ok(hull)
}

// ─────────────────────────────────────────────────────────────────────────────
// Contour Extraction – Moore Neighbourhood
// ─────────────────────────────────────────────────────────────────────────────

/// Extract outer contours from a binary image using Moore-neighbourhood (8-connected)
/// boundary tracing (Jacob's stopping criterion).
///
/// Returns one contour per connected component.  Each contour is a list of
/// (row, col) pixel coordinates.
///
/// # Arguments
///
/// * `binary` – 2-D boolean array where `true` denotes the foreground.
///
/// # Example
///
/// ```
/// use scirs2_ndimage::shape_analysis::contour_extraction;
/// use scirs2_core::ndarray::Array2;
///
/// let mut img = Array2::<bool>::default((6, 6));
/// for r in 1..5 { for c in 1..5 { img[[r, c]] = true; } }
/// let contours = contour_extraction(&img.view()).unwrap();
/// assert_eq!(contours.len(), 1);
/// assert!(!contours[0].is_empty());
/// ```
pub fn contour_extraction(
    binary: &ArrayView2<bool>,
) -> NdimageResult<Vec<Vec<(usize, usize)>>> {
    let rows = binary.nrows();
    let cols = binary.ncols();

    if rows == 0 || cols == 0 {
        return Ok(Vec::new());
    }

    // 8-connected Moore neighbourhood offsets (clockwise from right)
    const MOORE: [(i32, i32); 8] = [
        (0, 1),
        (1, 1),
        (1, 0),
        (1, -1),
        (0, -1),
        (-1, -1),
        (-1, 0),
        (-1, 1),
    ];

    let in_bounds = |r: i32, c: i32| -> bool {
        r >= 0 && r < rows as i32 && c >= 0 && c < cols as i32
    };

    let get = |r: usize, c: usize| -> bool {
        *binary.get((r, c)).unwrap_or(&false)
    };

    // Visited foreground pixels that have already been assigned to a contour
    let mut visited = Array2::<bool>::default((rows, cols));
    let mut contours: Vec<Vec<(usize, usize)>> = Vec::new();

    for start_r in 0..rows {
        for start_c in 0..cols {
            if !get(start_r, start_c) || visited[[start_r, start_c]] {
                continue;
            }

            // Check if this is a boundary pixel (has at least one background neighbour)
            let is_boundary = MOORE.iter().any(|(dr, dc)| {
                let nr = start_r as i32 + dr;
                let nc = start_c as i32 + dc;
                !in_bounds(nr, nc) || !get(nr as usize, nc as usize)
            });

            if !is_boundary {
                // Interior pixel – mark as visited but don't start a contour here
                visited[[start_r, start_c]] = true;
                continue;
            }

            // Moore neighbour tracing (Jacob's stopping criterion)
            let mut contour: Vec<(usize, usize)> = Vec::new();
            let start = (start_r, start_c);
            let mut current = start;

            // Entry direction: the neighbour we came FROM (index into MOORE)
            // We start looking from the background pixel to the left of start_c.
            let mut entry_dir: usize = 4; // direction 4 = (0, -1) = left

            loop {
                contour.push(current);
                visited[[current.0, current.1]] = true;

                // Search Moore neighbourhood starting from the pixel OPPOSITE to entry
                let start_search = (entry_dir + 5) % 8;
                let mut found = false;
                let mut next = current;
                let mut next_entry = 0usize;

                for k in 0..8usize {
                    let dir = (start_search + k) % 8;
                    let (dr, dc) = MOORE[dir];
                    let nr = current.0 as i32 + dr;
                    let nc = current.1 as i32 + dc;
                    if in_bounds(nr, nc) && get(nr as usize, nc as usize) {
                        next = (nr as usize, nc as usize);
                        // entry_dir for next pixel: direction pointing BACK to current
                        next_entry = (dir + 4) % 8;
                        found = true;
                        break;
                    }
                }

                if !found {
                    // Isolated pixel
                    break;
                }

                entry_dir = next_entry;
                current = next;

                // Jacob's stopping criterion: back to start AND arriving from same direction
                if current == start && entry_dir == (4 + 4) % 8 {
                    break;
                }
                // Simpler fallback: back to start
                if current == start {
                    break;
                }
                // Safety: contour cannot be longer than total pixels
                if contour.len() > rows * cols {
                    break;
                }
            }

            if !contour.is_empty() {
                contours.push(contour);
            }
        }
    }

    Ok(contours)
}

// ─────────────────────────────────────────────────────────────────────────────
// Shape Descriptors
// ─────────────────────────────────────────────────────────────────────────────

/// Collection of scalar shape descriptors computed from a contour.
#[derive(Debug, Clone)]
pub struct ShapeDescriptors {
    /// Area enclosed by the contour (shoelace formula, pixels²).
    pub area: f64,
    /// Perimeter (sum of Euclidean distances between consecutive contour points).
    pub perimeter: f64,
    /// Circularity: 4π·area / perimeter².  Perfect circle → 1.
    pub circularity: f64,
    /// Eccentricity of the best-fit ellipse (0 = circle, 1 = line).
    pub eccentricity: f64,
    /// Aspect ratio: major_axis / minor_axis of the bounding box.
    pub aspect_ratio: f64,
    /// Extent: area / bounding_box_area.
    pub extent: f64,
    /// Solidity: area / convex_hull_area.
    pub solidity: f64,
    /// Convexity: convex_hull_perimeter / perimeter.
    pub convexity: f64,
}

/// Compute shape descriptors for a contour given as (row, col) pixel coordinates.
///
/// # Arguments
///
/// * `contour` – Ordered list of boundary pixels (row, col).
///
/// # Errors
///
/// Returns [`NdimageError::InvalidInput`] when the contour has fewer than 3 points.
///
/// # Example
///
/// ```
/// use scirs2_ndimage::shape_analysis::shape_descriptors;
///
/// let contour: Vec<(usize, usize)> = vec![(0,0),(0,1),(0,2),(1,2),(2,2),(2,1),(2,0),(1,0)];
/// let d = shape_descriptors(&contour).unwrap();
/// assert!(d.area > 0.0);
/// assert!(d.circularity > 0.0 && d.circularity <= 1.0 + 1e-6);
/// ```
pub fn shape_descriptors(contour: &[(usize, usize)]) -> NdimageResult<ShapeDescriptors> {
    if contour.len() < 3 {
        return Err(NdimageError::InvalidInput(
            "shape_descriptors: contour must have at least 3 points".to_string(),
        ));
    }

    let pts_f: Vec<(f64, f64)> = contour
        .iter()
        .map(|&(r, c)| (c as f64, r as f64)) // (x, y)
        .collect();

    // --- Area (shoelace) ---
    let area = shoelace_area(&pts_f).abs();

    // --- Perimeter ---
    let n = pts_f.len();
    let perimeter: f64 = pts_f
        .iter()
        .zip(pts_f.iter().cycle().skip(1))
        .take(n)
        .map(|(&(x0, y0), &(x1, y1))| ((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt())
        .sum();

    // --- Circularity ---
    let circularity = if perimeter > 1e-12 {
        4.0 * std::f64::consts::PI * area / perimeter.powi(2)
    } else {
        0.0
    };

    // --- Bounding box ---
    let (min_x, max_x, min_y, max_y) = pts_f.iter().fold(
        (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY),
        |(mnx, mxx, mny, mxy), &(x, y)| {
            (mnx.min(x), mxx.max(x), mny.min(y), mxy.max(y))
        },
    );
    let bbox_w = (max_x - min_x).max(1.0);
    let bbox_h = (max_y - min_y).max(1.0);
    let bbox_area = bbox_w * bbox_h;

    // --- Aspect ratio ---
    let aspect_ratio = if bbox_h > 1e-12 {
        bbox_w / bbox_h
    } else {
        1.0
    };

    // --- Extent ---
    let extent = area / bbox_area;

    // --- Convex hull ---
    let hull = convex_hull_2d(&pts_f).unwrap_or_default();

    // Convex hull area
    let hull_area = if hull.len() >= 3 {
        shoelace_area(&hull).abs()
    } else {
        area
    };

    // Convex hull perimeter
    let hull_perim: f64 = if hull.len() >= 2 {
        let hn = hull.len();
        hull.iter()
            .zip(hull.iter().cycle().skip(1))
            .take(hn)
            .map(|(&(x0, y0), &(x1, y1))| ((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt())
            .sum()
    } else {
        perimeter
    };

    // --- Solidity ---
    let solidity = if hull_area > 1e-12 {
        (area / hull_area).min(1.0)
    } else {
        1.0
    };

    // --- Convexity ---
    let convexity = if perimeter > 1e-12 {
        (hull_perim / perimeter).min(1.0)
    } else {
        1.0
    };

    // --- Eccentricity via second-order central moments ---
    let (cx, cy) = pts_f.iter().fold((0.0f64, 0.0f64), |(ax, ay), &(x, y)| {
        (ax + x, ay + y)
    });
    let cx = cx / n as f64;
    let cy = cy / n as f64;

    let (mu20, mu02, mu11) = pts_f.iter().fold((0.0f64, 0.0f64, 0.0f64), |(m20, m02, m11), &(x, y)| {
        let dx = x - cx;
        let dy = y - cy;
        (m20 + dx * dx, m02 + dy * dy, m11 + dx * dy)
    });
    let mu20 = mu20 / n as f64;
    let mu02 = mu02 / n as f64;
    let mu11 = mu11 / n as f64;

    let diff = mu20 - mu02;
    let discriminant = (diff * diff + 4.0 * mu11 * mu11).sqrt();
    let lambda1 = (mu20 + mu02 + discriminant) / 2.0;
    let lambda2 = ((mu20 + mu02 - discriminant) / 2.0).max(0.0);

    let eccentricity = if lambda1 > 1e-12 {
        (1.0 - lambda2 / lambda1).sqrt()
    } else {
        0.0
    };

    Ok(ShapeDescriptors {
        area,
        perimeter,
        circularity: circularity.min(1.0 + 1e-9),
        eccentricity,
        aspect_ratio,
        extent: extent.min(1.0),
        solidity,
        convexity,
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// Ellipse Fitting (Fitzgibbon algebraic least-squares)
// ─────────────────────────────────────────────────────────────────────────────

/// Fit an ellipse to a set of 2-D points using the Fitzgibbon–Pilu–Fisher
/// algebraic least-squares method.
///
/// Returns `(cx, cy, a, b, angle_rad)` where:
/// - `(cx, cy)` is the ellipse centre,
/// - `a` ≥ `b` are the semi-axes,
/// - `angle_rad` is the tilt of the major axis (radians, measured from the
///    positive x-axis counter-clockwise).
///
/// # Arguments
///
/// * `points` – At least 5 (x, y) sample points.
///
/// # Errors
///
/// - [`NdimageError::InvalidInput`] if fewer than 5 points are given.
/// - [`NdimageError::ComputationError`] if the SVD / eigenvalue solver fails.
///
/// # Example
///
/// ```
/// use scirs2_ndimage::shape_analysis::ellipse_fit;
/// use std::f64::consts::PI;
///
/// // Generate points on a 3×2 axis-aligned ellipse
/// let pts: Vec<(f64, f64)> = (0..36)
///     .map(|i| {
///         let t = i as f64 * PI / 18.0;
///         (3.0 * t.cos(), 2.0 * t.sin())
///     })
///     .collect();
/// let (cx, cy, a, b, _angle) = ellipse_fit(&pts).unwrap();
/// assert!((cx).abs() < 0.1);
/// assert!((cy).abs() < 0.1);
/// assert!((a - 3.0).abs() < 0.1);
/// assert!((b - 2.0).abs() < 0.1);
/// ```
pub fn ellipse_fit(points: &[(f64, f64)]) -> NdimageResult<(f64, f64, f64, f64, f64)> {
    if points.len() < 5 {
        return Err(NdimageError::InvalidInput(
            "ellipse_fit: at least 5 points are required".to_string(),
        ));
    }

    let n = points.len();

    // Build the design matrix D (n × 6), columns: x², xy, y², x, y, 1
    // Scatter matrix S = D'D
    let mut s = [[0.0f64; 6]; 6];
    for &(x, y) in points {
        let row = [x * x, x * y, y * y, x, y, 1.0];
        for i in 0..6 {
            for j in 0..6 {
                s[i][j] += row[i] * row[j];
            }
        }
    }

    // Constraint matrix C (only C[0][2], C[1][1], C[2][0] are non-zero for the
    // "bookstein" ellipse-specific constraint 4ac - b² = 1)
    // We use the eigenvector approach: solve (S⁻¹ C) v = λ v, pick the eigenvector
    // with the smallest positive eigenvalue.
    //
    // For numerical stability we use the reduced 3×3 system (Bookstein constraint).
    // The Fitzgibbon direct method:
    //   C = [[0,0,2],[0,-1,0],[2,0,0]]  (top-left 3×3) and zeros elsewhere.

    // Partition S into blocks
    // S = [S11 S12; S21 S22]  where S11, S12, S21, S22 are 3×3
    let s11 = sub_matrix_3x3(&s, 0, 0);
    let s12 = sub_matrix_3x3(&s, 0, 3);
    let s21 = sub_matrix_3x3(&s, 3, 0);
    let s22 = sub_matrix_3x3(&s, 3, 3);

    let s22_inv = mat3_inv(&s22).ok_or_else(|| {
        NdimageError::ComputationError("ellipse_fit: singular scatter sub-matrix".to_string())
    })?;

    // Reduced system M = C11^{-1} (S11 - S12 S22^{-1} S21)
    let tmp = mat3_mul(&s12, &mat3_mul(&s22_inv, &s21));
    let m_raw = mat3_sub(&s11, &tmp);

    // C11 = [[0,0,2],[0,-1,0],[2,0,0]], C11^{-1} = [[0,0,0.5],[0,-1,0],[0.5,0,0]]
    // M = C11^{-1} * m_raw
    let m = [
        [
            0.5 * m_raw[2][0],
            0.5 * m_raw[2][1],
            0.5 * m_raw[2][2],
        ],
        [
            -m_raw[1][0],
            -m_raw[1][1],
            -m_raw[1][2],
        ],
        [
            0.5 * m_raw[0][0],
            0.5 * m_raw[0][1],
            0.5 * m_raw[0][2],
        ],
    ];

    // Find eigenvalues / eigenvectors of M (3×3 via characteristic polynomial)
    let (eigenvalues, eigenvectors) = mat3_eigen(&m);

    // Pick eigenvector with smallest positive eigenvalue where 4ac - b² > 0
    let mut best: Option<[f64; 3]> = None;
    let mut best_eval = f64::INFINITY;
    for i in 0..3 {
        let ev = eigenvalues[i];
        if ev.is_finite() && ev > 1e-15 {
            let v = eigenvectors[i];
            let cond = 4.0 * v[0] * v[2] - v[1] * v[1];
            if cond > 0.0 && ev < best_eval {
                best_eval = ev;
                best = Some(v);
            }
        }
    }

    let a1 = best.ok_or_else(|| {
        NdimageError::ComputationError(
            "ellipse_fit: no valid ellipse eigenvector found".to_string(),
        )
    })?;

    // Recover full 6-vector: [a, b, c, d, e, f]
    // a2 = -S22^{-1} S21 a1
    let neg_s22inv_s21_a1 = mat3_mul_vec(&mat3_mul(&s22_inv, &s21), &a1);
    let coeffs = [
        a1[0],
        a1[1],
        a1[2],
        -neg_s22inv_s21_a1[0],
        -neg_s22inv_s21_a1[1],
        -neg_s22inv_s21_a1[2],
    ];

    // Convert general conic Ax²+Bxy+Cy²+Dx+Ey+F=0 to geometric parameters
    conic_to_ellipse(coeffs)
}

// ─────────────────────────────────────────────────────────────────────────────
// Minimum Bounding Rectangle – Rotating Calipers
// ─────────────────────────────────────────────────────────────────────────────

/// Compute the minimum-area bounding rectangle of a 2-D point set.
///
/// Returns the four corners of the rectangle in counter-clockwise order.
///
/// Uses the rotating calipers algorithm on the convex hull.
///
/// # Arguments
///
/// * `points` – At least one (x, y) point.
///
/// # Errors
///
/// Returns [`NdimageError::InvalidInput`] when the input is empty.
///
/// # Example
///
/// ```
/// use scirs2_ndimage::shape_analysis::minimum_bounding_rectangle;
///
/// let pts = vec![(0.0_f64, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0)];
/// let rect = minimum_bounding_rectangle(&pts).unwrap();
/// // Area should be close to 12
/// let area = {
///     let (dx1, dy1) = (rect[1].0 - rect[0].0, rect[1].1 - rect[0].1);
///     let (dx2, dy2) = (rect[3].0 - rect[0].0, rect[3].1 - rect[0].1);
///     let l1 = (dx1*dx1 + dy1*dy1).sqrt();
///     let l2 = (dx2*dx2 + dy2*dy2).sqrt();
///     l1 * l2
/// };
/// assert!((area - 12.0).abs() < 0.5);
/// ```
pub fn minimum_bounding_rectangle(points: &[(f64, f64)]) -> NdimageResult<[(f64, f64); 4]> {
    if points.is_empty() {
        return Err(NdimageError::InvalidInput(
            "minimum_bounding_rectangle: point set is empty".to_string(),
        ));
    }

    let hull = convex_hull_2d(points)?;
    if hull.len() == 1 {
        let p = hull[0];
        return Ok([p, p, p, p]);
    }
    if hull.len() == 2 {
        let (x0, y0) = hull[0];
        let (x1, y1) = hull[1];
        return Ok([(x0, y0), (x1, y1), (x1, y1), (x0, y0)]);
    }

    let n = hull.len();
    let mut min_area = f64::INFINITY;
    let mut best_rect = [(0.0f64, 0.0f64); 4];

    // Rotating calipers: iterate over each edge of the hull
    for i in 0..n {
        let j = (i + 1) % n;
        let (ex, ey) = (hull[j].0 - hull[i].0, hull[j].1 - hull[i].1);
        let len_e = (ex * ex + ey * ey).sqrt();
        if len_e < 1e-12 {
            continue;
        }
        let ux = ex / len_e; // unit edge vector
        let uy = ey / len_e;

        // Project all hull points onto (ux, uy) and its perpendicular (-uy, ux)
        let (mut min_u, mut max_u, mut min_v, mut max_v) =
            (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);

        for &(px, py) in &hull {
            let u = px * ux + py * uy;
            let v = -px * uy + py * ux;
            min_u = min_u.min(u);
            max_u = max_u.max(u);
            min_v = min_v.min(v);
            max_v = max_v.max(v);
        }

        let area = (max_u - min_u) * (max_v - min_v);
        if area < min_area {
            min_area = area;
            // Reconstruct four corners from (u,v) back to (x,y)
            let corner = |u: f64, v: f64| -> (f64, f64) {
                (u * ux - v * uy, u * uy + v * ux)
            };
            best_rect = [
                corner(min_u, min_v),
                corner(max_u, min_v),
                corner(max_u, max_v),
                corner(min_u, max_v),
            ];
        }
    }

    Ok(best_rect)
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Shoelace formula for signed polygon area.
fn shoelace_area(pts: &[(f64, f64)]) -> f64 {
    let n = pts.len();
    if n < 3 {
        return 0.0;
    }
    let mut area = 0.0f64;
    for i in 0..n {
        let j = (i + 1) % n;
        area += pts[i].0 * pts[j].1;
        area -= pts[j].0 * pts[i].1;
    }
    area / 2.0
}

// 3×3 matrix helpers (row-major arrays)

fn sub_matrix_3x3(s: &[[f64; 6]; 6], row_off: usize, col_off: usize) -> [[f64; 3]; 3] {
    let mut m = [[0.0f64; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            m[i][j] = s[row_off + i][col_off + j];
        }
    }
    m
}

fn mat3_det(m: &[[f64; 3]; 3]) -> f64 {
    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
}

fn mat3_inv(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
    let det = mat3_det(m);
    if det.abs() < 1e-14 {
        return None;
    }
    let inv_det = 1.0 / det;
    let mut inv = [[0.0f64; 3]; 3];
    inv[0][0] = (m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inv_det;
    inv[0][1] = (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inv_det;
    inv[0][2] = (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inv_det;
    inv[1][0] = (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inv_det;
    inv[1][1] = (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inv_det;
    inv[1][2] = (m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inv_det;
    inv[2][0] = (m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inv_det;
    inv[2][1] = (m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inv_det;
    inv[2][2] = (m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inv_det;
    Some(inv)
}

fn mat3_mul(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let mut c = [[0.0f64; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            for k in 0..3 {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    c
}

fn mat3_sub(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let mut c = [[0.0f64; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            c[i][j] = a[i][j] - b[i][j];
        }
    }
    c
}

fn mat3_mul_vec(m: &[[f64; 3]; 3], v: &[f64; 3]) -> [f64; 3] {
    let mut out = [0.0f64; 3];
    for i in 0..3 {
        for j in 0..3 {
            out[i] += m[i][j] * v[j];
        }
    }
    out
}

/// Compute eigenvalues and eigenvectors of a real 3×3 matrix using the
/// characteristic polynomial (Cardano) + inverse iteration refinement.
/// Returns `(eigenvalues, eigenvectors)` both of length 3.
fn mat3_eigen(m: &[[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
    // Characteristic polynomial: λ³ - p·λ² + q·λ - r = 0
    let p = m[0][0] + m[1][1] + m[2][2]; // trace
    let q = m[0][0] * m[1][1] + m[1][1] * m[2][2] + m[0][0] * m[2][2]
        - m[0][1] * m[1][0]
        - m[1][2] * m[2][1]
        - m[0][2] * m[2][0];
    let r = mat3_det(m);

    // Depress: λ = t + p/3
    let a = q - p * p / 3.0;
    let b = 2.0 * p * p * p / 27.0 - p * q / 3.0 + r;

    let disc = (b / 2.0).powi(2) + (a / 3.0).powi(3);

    let eigenvalues: [f64; 3] = if disc >= 0.0 {
        // One or two repeated real roots (or complex pair – degenerate case)
        let sqrt_disc = disc.sqrt();
        let u = cbrt(-b / 2.0 + sqrt_disc);
        let v = cbrt(-b / 2.0 - sqrt_disc);
        let t0 = u + v;
        let t1 = -(u + v) / 2.0;
        [t0 + p / 3.0, t1 + p / 3.0, t1 + p / 3.0]
    } else {
        // Three distinct real roots
        let rho = (-a / 3.0).sqrt().max(1e-30);
        let theta = ((-b / 2.0) / (rho * rho * rho)).clamp(-1.0, 1.0).acos();
        [
            2.0 * rho * (theta / 3.0).cos() + p / 3.0,
            2.0 * rho * ((theta + 2.0 * std::f64::consts::PI) / 3.0).cos() + p / 3.0,
            2.0 * rho * ((theta + 4.0 * std::f64::consts::PI) / 3.0).cos() + p / 3.0,
        ]
    };

    // Compute eigenvectors via (M - λI) null-space (cross-product method)
    let mut evecs = [[0.0f64; 3]; 3];
    for (i, &lam) in eigenvalues.iter().enumerate() {
        let a_mat = [
            [m[0][0] - lam, m[0][1], m[0][2]],
            [m[1][0], m[1][1] - lam, m[1][2]],
            [m[2][0], m[2][1], m[2][2] - lam],
        ];
        // Take cross products of pairs of rows and pick the largest
        let r0 = a_mat[0];
        let r1 = a_mat[1];
        let r2 = a_mat[2];
        let candidates = [
            cross3(r0, r1),
            cross3(r1, r2),
            cross3(r0, r2),
        ];
        let best = candidates
            .iter()
            .copied()
            .max_by(|x, y| {
                let nx = x[0] * x[0] + x[1] * x[1] + x[2] * x[2];
                let ny = y[0] * y[0] + y[1] * y[1] + y[2] * y[2];
                nx.partial_cmp(&ny).unwrap_or(std::cmp::Ordering::Equal)
            })
            .unwrap_or([1.0, 0.0, 0.0]);
        let norm = (best[0] * best[0] + best[1] * best[1] + best[2] * best[2])
            .sqrt()
            .max(1e-30);
        evecs[i] = [best[0] / norm, best[1] / norm, best[2] / norm];
    }

    (eigenvalues, evecs)
}

fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}

fn cbrt(x: f64) -> f64 {
    if x >= 0.0 {
        x.powf(1.0 / 3.0)
    } else {
        -(-x).powf(1.0 / 3.0)
    }
}

/// Convert general conic coefficients [A, B, C, D, E, F] to ellipse geometry.
fn conic_to_ellipse(c: [f64; 6]) -> NdimageResult<(f64, f64, f64, f64, f64)> {
    let (a, b, cc, d, e, f) = (c[0], c[1], c[2], c[3], c[4], c[5]);

    // Centre
    let denom = 4.0 * a * cc - b * b;
    if denom.abs() < 1e-14 {
        return Err(NdimageError::ComputationError(
            "ellipse_fit: degenerate conic (not an ellipse)".to_string(),
        ));
    }
    let cx = (b * e - 2.0 * cc * d) / denom;
    let cy = (b * d - 2.0 * a * e) / denom;

    // Axis-aligned form
    let f_prime = a * cx * cx + b * cx * cy + cc * cy * cy + d * cx + e * cy + f;

    let m_11 = a;
    let m_12 = b / 2.0;
    let m_22 = cc;

    let eig_diff = ((m_11 - m_22).powi(2) + m_12 * m_12 * 4.0).sqrt();
    let lam1 = (m_11 + m_22 + eig_diff) / 2.0;
    let lam2 = (m_11 + m_22 - eig_diff) / 2.0;

    if -f_prime / lam1 <= 0.0 || -f_prime / lam2 <= 0.0 {
        return Err(NdimageError::ComputationError(
            "ellipse_fit: conic is not a real ellipse".to_string(),
        ));
    }

    let axis1 = (-f_prime / lam1).sqrt();
    let axis2 = (-f_prime / lam2).sqrt();
    let (semi_major, semi_minor) = if axis1 >= axis2 {
        (axis1, axis2)
    } else {
        (axis2, axis1)
    };

    // Angle of major axis
    let angle = if (m_12).abs() < 1e-14 && m_11 <= m_22 {
        0.0
    } else if (m_12).abs() < 1e-14 {
        std::f64::consts::PI / 2.0
    } else {
        ((lam1 - m_11) / m_12).atan()
    };

    Ok((cx, cy, semi_major, semi_minor, angle))
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::Array2;

    #[test]
    fn test_convex_hull_square() {
        let pts = vec![
            (0.0, 0.0),
            (1.0, 0.0),
            (1.0, 1.0),
            (0.0, 1.0),
            (0.5, 0.5),
        ];
        let hull = convex_hull_2d(&pts).expect("convex_hull_2d should succeed for square point set");
        assert_eq!(hull.len(), 4);
    }

    #[test]
    fn test_convex_hull_collinear() {
        let pts = vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)];
        let hull = convex_hull_2d(&pts).expect("convex_hull_2d should succeed for collinear points");
        // Collinear – degenerate hull
        assert!(hull.len() >= 2);
    }

    #[test]
    fn test_convex_hull_empty() {
        assert!(convex_hull_2d(&[]).is_err());
    }

    #[test]
    fn test_contour_extraction_filled_square() {
        let mut img = Array2::<bool>::default((8, 8));
        for r in 2..6 {
            for c in 2..6 {
                img[[r, c]] = true;
            }
        }
        let contours = contour_extraction(&img.view()).expect("contour_extraction should succeed on valid image");
        assert_eq!(contours.len(), 1);
        assert!(!contours[0].is_empty());
    }

    #[test]
    fn test_contour_extraction_empty_image() {
        let img = Array2::<bool>::default((5, 5));
        let contours = contour_extraction(&img.view()).expect("contour_extraction should succeed on empty image");
        assert!(contours.is_empty());
    }

    #[test]
    fn test_shape_descriptors_square() {
        // 4×4 filled square: use the 8-pixel contour
        let contour: Vec<(usize, usize)> = vec![
            (0, 0), (0, 1), (0, 2), (0, 3),
            (1, 3), (2, 3), (3, 3),
            (3, 2), (3, 1), (3, 0),
            (2, 0), (1, 0),
        ];
        let d = shape_descriptors(&contour).expect("shape_descriptors should succeed for valid square contour");
        assert!(d.area > 0.0);
        assert!(d.perimeter > 0.0);
        assert!(d.circularity > 0.0);
        assert!(d.circularity <= 1.0 + 1e-9);
        assert!(d.solidity > 0.0 && d.solidity <= 1.0);
    }

    #[test]
    fn test_shape_descriptors_too_few() {
        assert!(shape_descriptors(&[(0, 0), (1, 1)]).is_err());
    }

    #[test]
    fn test_minimum_bounding_rectangle_axis_aligned() {
        let pts = vec![
            (0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0),
        ];
        let rect = minimum_bounding_rectangle(&pts).expect("minimum_bounding_rectangle should succeed for axis-aligned rectangle");
        let area = {
            let (dx1, dy1) = (rect[1].0 - rect[0].0, rect[1].1 - rect[0].1);
            let (dx2, dy2) = (rect[3].0 - rect[0].0, rect[3].1 - rect[0].1);
            let l1 = (dx1 * dx1 + dy1 * dy1).sqrt();
            let l2 = (dx2 * dx2 + dy2 * dy2).sqrt();
            l1 * l2
        };
        assert!((area - 12.0).abs() < 0.5, "area = {area}");
    }

    #[test]
    fn test_ellipse_fit_circle() {
        let pts: Vec<(f64, f64)> = (0..36)
            .map(|i| {
                let t = i as f64 * std::f64::consts::PI / 18.0;
                (t.cos(), t.sin())
            })
            .collect();
        let (cx, cy, a, b, _angle) = ellipse_fit(&pts).expect("ellipse_fit should succeed for circular point set");
        assert!((cx).abs() < 0.05, "cx={cx}");
        assert!((cy).abs() < 0.05, "cy={cy}");
        assert!((a - 1.0).abs() < 0.05, "a={a}");
        assert!((b - 1.0).abs() < 0.05, "b={b}");
    }
}