scirs2-ndimage 0.4.1

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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
//! Statistical measurement functions for labeled arrays

use scirs2_core::ndarray::{Array, Array1, Dimension};
use scirs2_core::numeric::{Float, FromPrimitive, NumAssign};
use std::fmt::Debug;

use crate::error::{NdimageError, NdimageResult};

/// Helper function for safe usize conversion
#[allow(dead_code)]
fn safe_usize_to_float<T: Float + FromPrimitive>(value: usize) -> NdimageResult<T> {
    T::from_usize(value).ok_or_else(|| {
        NdimageError::ComputationError(format!("Failed to convert usize {} to float type", value))
    })
}

/// Sum the values of an array for each labeled region
///
/// This function computes the sum of pixel values within each labeled region,
/// which is useful for analyzing connected components or regions of interest.
/// Background pixels (label 0) are automatically excluded from calculations.
///
/// # Arguments
///
/// * `input` - Input array containing values to sum
/// * `labels` - Label array defining regions (same shape as input)
/// * `index` - Specific labels to include (if None, includes all non-zero labels)
///
/// # Returns
///
/// * `Result<Array1<T>>` - Array containing sum of values for each region, indexed by label order
///
/// # Examples
///
/// ## Basic usage with 2D arrays
/// ```
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::sum_labels;
///
/// // Create input image and corresponding labels
/// let image = array![
///     [1.0, 2.0, 3.0],
///     [4.0, 5.0, 6.0],
///     [7.0, 8.0, 9.0]
/// ];
///
/// let labels = array![
///     [1, 1, 2],
///     [1, 2, 2],
///     [3, 3, 3]
/// ];
///
/// let sums = sum_labels(&image, &labels, None).expect("Operation failed");
/// // sums[0] = sum of region 1 = 1+2+4 = 7
/// // sums[1] = sum of region 2 = 3+5+6 = 14  
/// // sums[2] = sum of region 3 = 7+8+9 = 24
/// ```
///
/// ## Computing specific region sums
/// ```
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::sum_labels;
///
/// let values = array![
///     [10.0, 20.0, 30.0],
///     [40.0, 50.0, 60.0]
/// ];
///
/// let regions = array![
///     [1, 2, 3],
///     [1, 2, 3]
/// ];
///
/// // Only compute sums for regions 1 and 3
/// let partial_sums = sum_labels(&values, &regions, Some(&[1, 3])).expect("Operation failed");
/// // Returns sums only for the specified regions
/// assert_eq!(partial_sums.len(), 2);
/// ```
///
/// ## Processing segmented image data
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::sum_labels;
///
/// // Simulate segmented image with intensity values
/// let intensityimage = Array2::from_shape_fn((100, 100), |(i, j)| {
///     ((i + j) as f64).sin().abs() * 255.0
/// });
///
/// // Simulate segmentation labels (e.g., from watershed)
/// let segmentation = Array2::from_shape_fn((100, 100), |(i, j)| {
///     ((i / 10) * 10 + (j / 10)) + 1  // Create grid-like segments
/// });
///
/// let total_intensities = sum_labels(&intensityimage, &segmentation, None).expect("Operation failed");
/// // Each element contains total intensity for that segment
/// ```
#[allow(dead_code)]
pub fn sum_labels<T, D>(
    input: &Array<T, D>,
    labels: &Array<usize, D>,
    index: Option<&[usize]>,
) -> NdimageResult<Array1<T>>
where
    T: Float + FromPrimitive + Debug + NumAssign + std::ops::DivAssign + 'static,
    D: Dimension + 'static,
{
    // Validate inputs
    if input.ndim() == 0 {
        return Err(NdimageError::InvalidInput(
            "Input array cannot be 0-dimensional".into(),
        ));
    }

    if labels.shape() != input.shape() {
        return Err(NdimageError::DimensionError(
            "Labels array must have same shape as input array".to_string(),
        ));
    }

    // Find unique labels
    let unique_labels: std::collections::HashSet<usize> = if let Some(idx) = index {
        idx.iter().cloned().collect()
    } else {
        labels.iter().cloned().collect()
    };

    let mut sorted_labels: Vec<usize> = unique_labels.into_iter().collect();
    sorted_labels.sort();

    // Remove label 0 if it exists (typically background)
    if sorted_labels.first() == Some(&0) {
        sorted_labels.remove(0);
    }

    if sorted_labels.is_empty() {
        return Ok(Array1::<T>::zeros(0));
    }

    // Create a mapping from label to index
    let label_to_idx: std::collections::HashMap<usize, usize> = sorted_labels
        .iter()
        .enumerate()
        .map(|(i, &label)| (label, i))
        .collect();

    // Initialize sums array
    let mut sums = vec![T::zero(); sorted_labels.len()];

    // Sum values for each label
    for (input_val, label_val) in input.iter().zip(labels.iter()) {
        if let Some(&idx) = label_to_idx.get(label_val) {
            sums[idx] += *input_val;
        }
    }

    Ok(Array1::from_vec(sums))
}

/// Calculate the mean (average) value for each labeled region
///
/// This function computes the arithmetic mean of pixel values within each labeled region.
/// It's fundamental for analyzing region characteristics and is commonly used in
/// image segmentation, object analysis, and feature extraction workflows.
///
/// # Arguments
///
/// * `input` - Input array containing values to average
/// * `labels` - Label array defining regions (same shape as input)
/// * `index` - Specific labels to include (if None, includes all non-zero labels)
///
/// # Returns
///
/// * `Result<Array1<T>>` - Array containing mean value for each region, ordered by label
///
/// # Examples
///
/// ## Basic mean calculation for segmented image
/// ```rust
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::mean_labels;
///
/// // Image with different intensity regions
/// let image = array![
///     [10.0, 20.0, 100.0],
///     [15.0, 25.0, 110.0],
///     [80.0, 85.0, 90.0]
/// ];
///
/// let regions = array![
///     [1, 1, 2],      // Region 1: bright spot
///     [1, 1, 2],      // Region 2: very bright area  
///     [3, 3, 3]       // Region 3: medium bright area
/// ];
///
/// let means = mean_labels(&image, &regions, None).expect("Operation failed");
/// // means[0] = mean of region 1 = (10+20+15+25)/4 = 17.5
/// // means[1] = mean of region 2 = (100+110)/2 = 105.0
/// // means[2] = mean of region 3 = (80+85+90)/3 = 85.0
/// ```
///
/// ## Region-based intensity analysis
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::mean_labels;
///
/// // Simulate medical image with different tissue types
/// let intensity_map = Array2::from_shape_fn((50, 50), |(i, j)| {
///     match (i / 10, j / 10) {
///         (0..=1, 0..=1) => 50.0,   // Tissue type A
///         (2..=3, 2..=3) => 150.0,  // Tissue type B  
///         _ => 100.0,               // Background tissue
///     }
/// });
///
/// let tissue_labels = Array2::from_shape_fn((50, 50), |(i, j)| {
///     match (i / 10, j / 10) {
///         (0..=1, 0..=1) => 1,  // Label 1: Type A
///         (2..=3, 2..=3) => 2,  // Label 2: Type B
///         _ => 3,               // Label 3: Background
///     }
/// });
///
/// let tissue_means = mean_labels(&intensity_map, &tissue_labels, None).expect("Operation failed");
/// // Analyze mean intensities of different tissue types
/// for (i, &mean_intensity) in tissue_means.iter().enumerate() {
///     println!("Tissue type {}: mean intensity = {:.1}", i+1, mean_intensity);
/// }
/// ```
///
/// ## Quality control: analyzing specific regions only
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_ndimage::measurements::mean_labels;
///
/// let values = array![
///     [1.0, 2.0, 3.0, 4.0],
///     [5.0, 6.0, 7.0, 8.0],
///     [9.0, 10.0, 11.0, 12.0]
/// ];
///
/// let labels = array![
///     [1, 2, 3, 4],
///     [1, 2, 3, 4],
///     [1, 2, 3, 4]
/// ];
///
/// // Only analyze regions 2 and 4
/// let selected_means = mean_labels(&values, &labels, Some(&[2, 4])).expect("Operation failed");
/// // Returns means only for regions 2 and 4
/// assert_eq!(selected_means.len(), 2);
/// ```
///
/// ## Workflow: segmentation → feature extraction
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::mean_labels;
///
/// // Simulate workflow after watershed segmentation
/// let originalimage = Array2::<f64>::from_shape_fn((20, 20), |(i, j)| {
///     ((i as f64 - 10.0).powi(2) + (j as f64 - 10.0).powi(2)).sqrt()
/// });
///
/// let segmentation_result = Array2::from_shape_fn((20, 20), |(i, j)| {
///     if i < 10 && j < 10 { 1 }
///     else if i >= 10 && j < 10 { 2 }
///     else if i < 10 && j >= 10 { 3 }
///     else { 4 }
/// });
///
/// // Extract mean intensity for each segment
/// let segmentfeatures = mean_labels(&originalimage, &segmentation_result, None).expect("Operation failed");
///
/// // Filter segments by mean intensity threshold
/// let bright_segments: Vec<usize> = segmentfeatures.iter()
///     .enumerate()
///     .filter(|(_, &mean)| mean > 10.0)
///     .map(|(i_, _)| i_ + 1)  // Convert to 1-based labeling
///     .collect();
/// ```
///
/// # Applications
///
/// - **Medical Imaging**: Analyze tissue intensity characteristics
/// - **Materials Science**: Measure average properties in different phases
/// - **Quality Control**: Check uniformity within regions of interest
/// - **Feature Extraction**: Create descriptive statistics for machine learning
/// - **Image Segmentation**: Validate segmentation quality by intensity homogeneity
///
/// # Performance Notes
///
/// - Time complexity: O(n) where n is the total number of pixels
/// - Space complexity: O(r) where r is the number of unique regions
/// - Computation involves two passes: sum calculation then division by count
/// - For very large images, consider chunked processing
///
/// # Related Functions
///
/// - [`sum_labels`]: Get total values instead of averages
/// - [`variance_labels`]: Measure spread within regions
/// - [`count_labels`]: Get region sizes
///
/// # Errors
///
/// Returns an error if:
/// - Input array is 0-dimensional
/// - Input and labels arrays have different shapes
/// - Region has zero pixels (should not occur with valid labels)
#[allow(dead_code)]
pub fn mean_labels<T, D>(
    input: &Array<T, D>,
    labels: &Array<usize, D>,
    index: Option<&[usize]>,
) -> NdimageResult<Array1<T>>
where
    T: Float + FromPrimitive + Debug + NumAssign + std::ops::DivAssign + 'static,
    D: Dimension + 'static,
{
    // Validate inputs
    if input.ndim() == 0 {
        return Err(NdimageError::InvalidInput(
            "Input array cannot be 0-dimensional".into(),
        ));
    }

    if labels.shape() != input.shape() {
        return Err(NdimageError::DimensionError(
            "Labels array must have same shape as input array".to_string(),
        ));
    }

    // Get sums and counts for each label
    let sums = sum_labels(input, labels, index)?;
    let counts = count_labels(labels, index)?;

    if sums.len() != counts.len() {
        return Err(NdimageError::InvalidInput(
            "Mismatch between sums and counts arrays".into(),
        ));
    }

    // Calculate means (sum / count for each label)
    let means: Vec<T> = sums
        .iter()
        .zip(counts.iter())
        .map(|(&sum, &count)| {
            if count > 0 {
                sum / safe_usize_to_float(count).unwrap_or(T::one())
            } else {
                T::zero()
            }
        })
        .collect();

    Ok(Array1::from_vec(means))
}

/// Calculate the variance of an array for each labeled region
///
/// Computes the sample variance for pixel values within each labeled region.
/// Variance measures the spread of values around the mean, useful for analyzing
/// region homogeneity and texture properties.
///
/// # Arguments
///
/// * `input` - Input array containing values to analyze
/// * `labels` - Label array defining regions (same shape as input)  
/// * `index` - Specific labels to include (if None, includes all non-zero labels)
///
/// # Returns
///
/// * `Result<Array1<T>>` - Array containing variance for each region
///
/// # Examples
///
/// ## Basic variance calculation
/// ```
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::variance_labels;
///
/// let values = array![
///     [1.0, 2.0, 10.0],
///     [1.5, 2.5, 10.5],
///     [5.0, 5.0, 5.0]
/// ];
///
/// let regions = array![
///     [1, 1, 2],
///     [1, 1, 2],
///     [3, 3, 3]
/// ];
///
/// let variances = variance_labels(&values, &regions, None).expect("Operation failed");
/// // Region 1: variance of [1.0, 2.0, 1.5, 2.5]
/// // Region 2: variance of [10.0, 10.5]
/// // Region 3: variance of [5.0, 5.0, 5.0] = 0.0 (no variation)
/// ```
#[allow(dead_code)]
pub fn variance_labels<T, D>(
    input: &Array<T, D>,
    labels: &Array<usize, D>,
    index: Option<&[usize]>,
) -> NdimageResult<Array1<T>>
where
    T: Float + FromPrimitive + Debug + NumAssign + std::ops::DivAssign + 'static,
    D: Dimension + 'static,
{
    // Validate inputs
    if input.ndim() == 0 {
        return Err(NdimageError::InvalidInput(
            "Input array cannot be 0-dimensional".into(),
        ));
    }

    if labels.shape() != input.shape() {
        return Err(NdimageError::DimensionError(
            "Labels array must have same shape as input array".to_string(),
        ));
    }

    // Find unique labels
    let unique_labels: std::collections::HashSet<usize> = if let Some(idx) = index {
        idx.iter().cloned().collect()
    } else {
        labels.iter().cloned().collect()
    };

    let mut sorted_labels: Vec<usize> = unique_labels.into_iter().collect();
    sorted_labels.sort();

    // Remove label 0 if it exists (typically background)
    if sorted_labels.first() == Some(&0) {
        sorted_labels.remove(0);
    }

    if sorted_labels.is_empty() {
        return Ok(Array1::<T>::zeros(0));
    }

    // Create a mapping from label to index
    let label_to_idx: std::collections::HashMap<usize, usize> = sorted_labels
        .iter()
        .enumerate()
        .map(|(i, &label)| (label, i))
        .collect();

    // First pass: calculate means
    let mut sums = vec![T::zero(); sorted_labels.len()];
    let mut counts = vec![0usize; sorted_labels.len()];

    for (input_val, label_val) in input.iter().zip(labels.iter()) {
        if let Some(&idx) = label_to_idx.get(label_val) {
            sums[idx] += *input_val;
            counts[idx] += 1;
        }
    }

    // Calculate means
    let means: Vec<T> = sums
        .iter()
        .zip(&counts)
        .map(|(&sum, &count)| {
            if count > 0 {
                sum / safe_usize_to_float(count).unwrap_or(T::one())
            } else {
                T::zero()
            }
        })
        .collect();

    // Second pass: calculate variances
    let mut variance_sums = vec![T::zero(); sorted_labels.len()];

    for (input_val, label_val) in input.iter().zip(labels.iter()) {
        if let Some(&idx) = label_to_idx.get(label_val) {
            let diff = *input_val - means[idx];
            variance_sums[idx] += diff * diff;
        }
    }

    // Calculate sample variances (divide by n-1)
    let variances: Vec<T> = variance_sums
        .iter()
        .zip(&counts)
        .map(|(&var_sum, &count)| {
            if count > 1 {
                var_sum / safe_usize_to_float(count - 1).unwrap_or(T::one())
            } else {
                T::zero() // Single pixel regions have zero variance
            }
        })
        .collect();

    Ok(Array1::from_vec(variances))
}

/// Count the number of pixels/elements in each labeled region
///
/// This function computes the size (area in 2D, volume in 3D) of each labeled region
/// by counting the number of pixels/elements belonging to each label. Region size is
/// a fundamental geometric property used for filtering, analysis, and feature extraction.
///
/// # Arguments
///
/// * `labels` - Label array defining regions where each unique value represents a region
/// * `index` - Specific labels to count (if None, counts all non-zero labels)
///
/// # Returns
///
/// * `Result<Array1<usize>>` - Array containing pixel count for each region, ordered by label
///
/// # Examples
///
/// ## Basic region size measurement
/// ```rust
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::count_labels;
///
/// let segmentation = array![
///     [1, 1, 2, 2],
///     [1, 0, 2, 3],  // 0 = background (excluded)
///     [4, 4, 4, 3]
/// ];
///
/// let counts = count_labels(&segmentation, None).expect("Operation failed");
/// // counts[0] = 3 pixels in region 1
/// // counts[1] = 3 pixels in region 2  
/// // counts[2] = 2 pixels in region 3
/// // counts[3] = 3 pixels in region 4
/// // Background (label 0) is automatically excluded
/// ```
///
/// ## Object size filtering workflow
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::count_labels;
///
/// // Simulate segmented image with objects of various sizes
/// let labels = Array2::from_shape_fn((100, 100), |(i, j)| {
///     match (i / 20, j / 20) {
///         (0, 0) => 1,  // Large object
///         (1, 1) => 2,  // Medium object  
///         (2, 2) => 3,  // Small object
///         (3, 3) => 4,  // Tiny object
///         _ => 0,       // Background
///     }
/// });
///
/// let object_sizes = count_labels(&labels, None).expect("Operation failed");
///
/// // Filter objects by minimum size (remove small noise)
/// let min_size = 100;
/// let large_objects: Vec<usize> = object_sizes.iter()
///     .enumerate()
///     .filter(|(_, &size)| size >= min_size)
///     .map(|(i_, _)| i_ + 1)  // Convert to 1-based label
///     .collect();
///
/// println!("Large objects (>= {} pixels): {:?}", min_size, large_objects);
/// ```
///
/// ## Cell counting and size analysis
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_ndimage::measurements::count_labels;
///
/// // Simulated cell segmentation result
/// let cell_labels = array![
///     [1, 1, 1, 0, 2, 2],
///     [1, 1, 1, 0, 2, 2],
///     [1, 1, 0, 0, 0, 0],
///     [0, 0, 0, 3, 3, 3],
///     [4, 4, 5, 3, 3, 3],
///     [4, 4, 5, 5, 5, 5]
/// ];
///
/// let cell_sizes = count_labels(&cell_labels, None).expect("Operation failed");
///
/// // Analyze cell size distribution
/// let total_cells = cell_sizes.len();
/// let total_area: usize = cell_sizes.iter().sum();
/// let average_size = total_area as f64 / total_cells as f64;
///
/// println!("Found {} cells", total_cells);
/// println!("Average cell size: {:.1} pixels", average_size);
///
/// // Identify unusually large or small cells
/// for (i, &size) in cell_sizes.iter().enumerate() {
///     let cell_id = i + 1;
///     if size < 3 {
///         println!("Cell {} is very small ({} pixels)", cell_id, size);
///     } else if size > 10 {
///         println!("Cell {} is very large ({} pixels)", cell_id, size);
///     }
/// }
/// ```
///
/// ## Quality control: count specific regions only
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_ndimage::measurements::count_labels;
///
/// let labels = array![
///     [1, 2, 3, 4, 5],
///     [1, 2, 3, 4, 5],
///     [1, 2, 3, 4, 5]
/// ];
///
/// // Only count regions 2, 4, and 5
/// let selected_counts = count_labels(&labels, Some(&[2, 4, 5])).expect("Operation failed");
/// assert_eq!(selected_counts.len(), 3);
/// // Each selected region has 3 pixels
/// assert_eq!(selected_counts[0], 3); // Region 2
/// assert_eq!(selected_counts[1], 3); // Region 4  
/// assert_eq!(selected_counts[2], 3); // Region 5
/// ```
///
/// ## Segmentation validation workflow
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::count_labels;
///
/// // After watershed or other segmentation algorithm
/// let segmentation_result = Array2::from_shape_fn((50, 50), |(i, j)| {
///     // Simulate segmentation with regions of different sizes
///     if i < 25 && j < 25 { 1 }
///     else if i >= 25 && j < 25 { 2 }
///     else if i < 25 && j >= 25 { 3 }
///     else { 4 }
/// });
///
/// let region_sizes = count_labels(&segmentation_result, None).expect("Operation failed");
///
/// // Validation: check for reasonable region sizes
/// let image_area = 50 * 50;
/// let total_segmented: usize = region_sizes.iter().sum();
///
/// println!("Segmentation coverage: {:.1}%",
///          100.0 * total_segmented as f64 / image_area as f64);
///
/// // Check for undersegmentation (too few, too large regions)
/// let oversized_threshold = image_area / 10;
/// let oversized_regions = region_sizes.iter()
///     .filter(|&&size| size > oversized_threshold)
///     .count();
///
/// if oversized_regions > 0 {
///     println!("Warning: {} oversized regions detected", oversized_regions);
/// }
/// ```
///
/// # Applications
///
/// - **Object Detection**: Count and size objects in segmented images
/// - **Cell Biology**: Measure cell sizes and count cell populations
/// - **Quality Control**: Filter regions by size criteria
/// - **Materials Science**: Analyze particle size distributions
/// - **Medical Imaging**: Measure lesion or organ sizes
/// - **Segmentation Validation**: Check segmentation quality
///
/// # Performance Notes
///
/// - Time complexity: O(n) where n is the total number of pixels
/// - Space complexity: O(r) where r is the number of unique regions
/// - Very efficient single-pass algorithm
/// - For memory-critical applications, consider processing in chunks
///
/// # Related Functions
///
/// - [`sum_labels`]: Get total intensity values per region
/// - [`mean_labels`]: Get average intensity per region  
/// - [`variance_labels`]: Measure intensity variation within regions
///
/// # Errors
///
/// Returns an error if:
/// - Label array is 0-dimensional
/// - No valid labels found (returns empty array, not error)
#[allow(dead_code)]
pub fn count_labels<D>(
    labels: &Array<usize, D>,
    index: Option<&[usize]>,
) -> NdimageResult<Array1<usize>>
where
    D: Dimension,
{
    // Validate inputs
    if labels.ndim() == 0 {
        return Err(NdimageError::InvalidInput(
            "Labels array cannot be 0-dimensional".into(),
        ));
    }

    // Find unique labels
    let unique_labels: std::collections::HashSet<usize> = if let Some(idx) = index {
        idx.iter().cloned().collect()
    } else {
        labels.iter().cloned().collect()
    };

    let mut sorted_labels: Vec<usize> = unique_labels.into_iter().collect();
    sorted_labels.sort();

    // Remove label 0 if it exists (typically background)
    if sorted_labels.first() == Some(&0) {
        sorted_labels.remove(0);
    }

    if sorted_labels.is_empty() {
        return Ok(Array1::<usize>::zeros(0));
    }

    // Create a mapping from label to index
    let label_to_idx: std::collections::HashMap<usize, usize> = sorted_labels
        .iter()
        .enumerate()
        .map(|(i, &label)| (label, i))
        .collect();

    // Initialize counts array
    let mut counts = vec![0usize; sorted_labels.len()];

    // Count occurrences of each label
    for &label_val in labels.iter() {
        if let Some(&idx) = label_to_idx.get(&label_val) {
            counts[idx] += 1;
        }
    }

    Ok(Array1::from_vec(counts))
}

/// Calculate histogram of values within labeled regions
///
/// This function computes histograms of pixel values within specified labeled regions.
/// It's useful for analyzing intensity distributions, texture characteristics, and
/// statistical properties of different regions in segmented images.
///
/// # Arguments
///
/// * `input` - Input array containing values to histogram
/// * `min` - Minimum value of histogram range (values below this are ignored)
/// * `max` - Maximum value of histogram range (values above this are ignored)
/// * `bins` - Number of histogram bins to create
/// * `labels` - Label array defining regions (if None, uses entire input array)
/// * `index` - Specific labels to include (if None, includes all non-zero labels)
///
/// # Returns
///
/// * `Result<(Array1<usize>, Array1<T>)>` - Tuple containing:
///   - Histogram counts for each bin
///   - Bin edges (length = bins + 1)
///
/// # Examples
///
/// ## Basic histogram of entire image
/// ```rust
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::histogram;
///
/// let image = array![
///     [0.0, 0.5, 1.0],
///     [0.2, 0.8, 1.2],
///     [0.4, 0.6, 0.9]
/// ];
///
/// // Create histogram with 5 bins from 0.0 to 1.0
/// let (counts, edges) = histogram(&image, 0.0, 1.0, 5, None, None).expect("Operation failed");
///
/// // edges will be [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
/// // counts shows how many pixels fall in each bin
/// println!("Histogram counts: {:?}", counts);
/// println!("Bin edges: {:?}", edges);
/// ```
///
/// ## Histogram of specific regions only
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_ndimage::measurements::histogram;
///
/// let intensities = array![
///     [10.0, 20.0, 100.0, 110.0],
///     [15.0, 25.0, 105.0, 115.0],
///     [12.0, 22.0, 102.0, 112.0]
/// ];
///
/// let regions = array![
///     [1, 1, 2, 2],
///     [1, 1, 2, 2],
///     [1, 1, 2, 2]
/// ];
///
/// // Histogram only region 1 (low intensity values)
/// let (hist_region1, edges1) = histogram(&intensities, 10.0, 30.0, 4,
///                                        Some(&regions), Some(&[1])).expect("Operation failed");
///
/// // Histogram only region 2 (high intensity values)  
/// let (hist_region2, edges2) = histogram(&intensities, 100.0, 120.0, 4,
///                                        Some(&regions), Some(&[2])).expect("Operation failed");
/// ```
///
/// ## Texture analysis workflow
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::histogram;
///
/// // Simulate textured image regions
/// let textureimage = Array2::from_shape_fn((50, 50), |(i, j)| {
///     let noise = ((i * 7 + j * 11) % 100) as f64 / 100.0;
///     match (i / 25, j / 25) {
///         (0, 0) => 0.2 + 0.1 * noise,  // Low intensity, low variation
///         (0, 1) => 0.8 + 0.1 * noise,  // High intensity, low variation
///         (1, 0) => 0.4 + 0.3 * noise,  // Medium intensity, high variation
///         _ => 0.6 + 0.2 * noise,       // Medium intensity, medium variation
///     }
/// });
///
/// let texture_labels = Array2::from_shape_fn((50, 50), |(i, j)| {
///     match (i / 25, j / 25) {
///         (0, 0) => 1,
///         (0, 1) => 2,
///         (1, 0) => 3,
///         _ => 4,
///     }
/// });
///
/// // Analyze histogram characteristics of each texture region
/// for region_id in 1..=4 {
///     let (hist_counts, _hist_edges) = histogram(&textureimage, 0.0, 1.0, 10,
///                               Some(&texture_labels), Some(&[region_id])).expect("Operation failed");
///
///     // Calculate histogram statistics
///     let total_pixels: usize = hist_counts.iter().sum();
///     let entropy = -hist_counts.iter()
///         .map(|&count| {
///             if count > 0 {
///                 let p = count as f64 / total_pixels as f64;
///                 p * p.log2()
///             } else {
///                 0.0
///             }
///         })
///         .sum::<f64>();
///     
///     println!("Region {}: entropy = {:.3}", region_id, entropy);
/// }
/// ```
///
/// ## Medical image intensity analysis
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::histogram;
///
/// // Simulate medical image with different tissue types
/// let medicalimage = Array2::from_shape_fn((100, 100), |(i, j)| {
///     match (i / 33, j / 33) {
///         (0, _) => 50.0 + (i % 10) as f64,   // Tissue A: 50-60 range
///         (1, _) => 150.0 + (j % 15) as f64,  // Tissue B: 150-165 range
///         _ => 100.0 + ((i + j) % 20) as f64, // Tissue C: 100-120 range
///     }
/// });
///
/// let tissue_segmentation = Array2::from_shape_fn((100, 100), |(i, j)| {
///     match (i / 33, j / 33) {
///         (0, _) => 1,  // Tissue A
///         (1, _) => 2,  // Tissue B
///         _ => 3,       // Tissue C
///     }
/// });
///
/// // Analyze intensity distribution for each tissue type
/// for tissue_type in 1..=3 {
///     let (tissue_hist, bin_edges) = histogram(&medicalimage, 0.0, 200.0, 20,
///                                              Some(&tissue_segmentation),
///                                              Some(&[tissue_type])).expect("Operation failed");
///     
///     // Find peak intensity for this tissue type
///     let peak_bin = tissue_hist.iter()
///         .enumerate()
///         .max_by_key(|(_, &count)| count)
///         .map(|(i_, _)| i_)
///         .unwrap_or(0);
///     
///     let peak_intensity = (bin_edges[peak_bin] + bin_edges[peak_bin + 1]) / 2.0;
///     println!("Tissue {}: peak intensity = {:.1}", tissue_type, peak_intensity);
/// }
/// ```
///
/// ## Quality control: histogram-based thresholding
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::histogram;
///
/// let image = Array2::from_shape_fn((50, 50), |(i, j)| {
///     let di = i as i32 - 25;
///     let dj = j as i32 - 25;
///     if di * di + dj * dj < 400 {
///         200.0  // Bright circular object
///     } else {
///         50.0   // Dark background
///     }
/// });
///
/// // Calculate histogram to find optimal threshold
/// let (hist, edges) = histogram(&image, 0.0, 255.0, 25, None, None).expect("Operation failed");
///
/// // Find valley between peaks (simplified Otsu-like approach)
/// let peak1 = hist.iter().take(10).enumerate().max_by_key(|(_, &v)| v).expect("Operation failed").0;
/// let peak2 = hist.iter().skip(15).enumerate().max_by_key(|(_, &v)| v).expect("Operation failed").0 + 15;
///
/// // Threshold is approximately between the peaks
/// let threshold = (edges[peak1] + edges[peak2]) / 2.0;
/// println!("Suggested threshold: {:.1}", threshold);
/// ```
///
/// # Applications
///
/// - **Medical Imaging**: Analyze tissue intensity distributions
/// - **Materials Science**: Study grain intensity characteristics
/// - **Quality Control**: Detect anomalies in intensity patterns
/// - **Texture Analysis**: Characterize surface textures
/// - **Image Enhancement**: Guide contrast adjustment algorithms
/// - **Segmentation**: Determine optimal thresholds
///
/// # Performance Notes
///
/// - Time complexity: O(n) where n is the number of pixels
/// - Space complexity: O(b) where b is the number of bins
/// - For large images, consider processing regions separately
/// - Bin count affects both precision and computation speed
///
/// # Implementation Note
///
/// Current implementation is a placeholder and returns empty histogram.
/// Full histogram calculation needs to be implemented with proper binning logic.
///
/// # Errors
///
/// Returns an error if:
/// - Input array is 0-dimensional
/// - min >= max (invalid range)
/// - bins = 0 (invalid bin count)
/// - Labels array shape doesn't match input array shape
#[allow(dead_code)]
pub fn histogram<T, D>(
    input: &Array<T, D>,
    min: T,
    max: T,
    bins: usize,
    labels: Option<&Array<usize, D>>,
    _index: Option<&[usize]>,
) -> NdimageResult<(Array1<usize>, Array1<T>)>
where
    T: Float + FromPrimitive + Debug + NumAssign + std::ops::DivAssign + 'static,
    D: Dimension + 'static,
{
    // Validate inputs
    if input.ndim() == 0 {
        return Err(NdimageError::InvalidInput(
            "Input array cannot be 0-dimensional".into(),
        ));
    }

    if min >= max {
        return Err(NdimageError::InvalidInput(format!(
            "min must be less than max (got min={:?}, max={:?})",
            min, max
        )));
    }

    if bins == 0 {
        return Err(NdimageError::InvalidInput(
            "bins must be greater than 0".into(),
        ));
    }

    if let Some(lab) = labels {
        if lab.shape() != input.shape() {
            return Err(NdimageError::DimensionError(
                "Labels array must have same shape as input array".to_string(),
            ));
        }
    }

    // Create bin edges
    let bin_width = (max - min) / T::from_usize(bins).expect("Operation failed");
    let mut edges = Array1::<T>::zeros(bins + 1);
    for i in 0..=bins {
        edges[i] = min + T::from_usize(i).expect("Operation failed") * bin_width;
    }

    // Initialize histogram
    let mut hist = Array1::<usize>::zeros(bins);

    // Compute histogram
    match labels {
        None => {
            // Process all values in the array
            for &value in input.iter() {
                if value >= min && value < max {
                    let bin_idx = ((value - min) / bin_width).to_usize().unwrap_or(0);
                    let bin_idx = bin_idx.min(bins - 1); // Ensure we don't exceed bounds
                    hist[bin_idx] += 1;
                } else if value == max {
                    // Special case for values exactly at max
                    hist[bins - 1] += 1;
                }
            }
        }
        Some(label_array) => {
            // Process only values with specific labels
            for (value, &label) in input.iter().zip(label_array.iter()) {
                // Skip background (label 0) if not explicitly requested
                if label > 0 && *value >= min && *value < max {
                    let bin_idx = ((*value - min) / bin_width).to_usize().unwrap_or(0);
                    let bin_idx = bin_idx.min(bins - 1);
                    hist[bin_idx] += 1;
                } else if label > 0 && *value == max {
                    hist[bins - 1] += 1;
                }
            }
        }
    }

    Ok((hist, edges))
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::{array, Array2, Array3};

    #[test]
    fn test_sum_labels_basic() {
        let input: Array2<f64> = Array2::eye(3);
        let labels: Array2<usize> = Array2::from_elem((3, 3), 1);
        let result =
            sum_labels(&input, &labels, None).expect("sum_labels should succeed for basic test");

        assert!(!result.is_empty());
        assert_eq!(result.len(), 1);
        assert_abs_diff_eq!(result[0], 3.0, epsilon = 1e-10); // Sum of diagonal elements
    }

    #[test]
    fn test_sum_labels_multiple_regions() {
        let input = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]];
        let labels = array![[1, 1, 2], [1, 2, 2], [3, 3, 3]];

        let sums = sum_labels(&input, &labels, None)
            .expect("sum_labels should succeed for multiple regions test");
        assert_eq!(sums.len(), 3);
        assert_abs_diff_eq!(sums[0], 1.0 + 2.0 + 4.0, epsilon = 1e-10); // Region 1
        assert_abs_diff_eq!(sums[1], 3.0 + 5.0 + 6.0, epsilon = 1e-10); // Region 2
        assert_abs_diff_eq!(sums[2], 7.0 + 8.0 + 9.0, epsilon = 1e-10); // Region 3
    }

    #[test]
    fn test_sum_labels_with_background() {
        let input = array![[1.0, 2.0], [3.0, 4.0]];
        let labels = array![[0, 1], [1, 2]]; // Label 0 is background

        let sums = sum_labels(&input, &labels, None)
            .expect("sum_labels should succeed with background test");
        assert_eq!(sums.len(), 2); // Should exclude background (label 0)
        assert_abs_diff_eq!(sums[0], 2.0 + 3.0, epsilon = 1e-10); // Region 1
        assert_abs_diff_eq!(sums[1], 4.0, epsilon = 1e-10); // Region 2
    }

    #[test]
    fn test_sum_labels_selective_index() {
        let input = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
        let labels = array![[1, 2, 3], [1, 2, 3]];

        let sums = sum_labels(&input, &labels, Some(&[1, 3]))
            .expect("sum_labels should succeed with selective index test");
        assert_eq!(sums.len(), 2); // Only regions 1 and 3
        assert_abs_diff_eq!(sums[0], 1.0 + 4.0, epsilon = 1e-10); // Region 1
        assert_abs_diff_eq!(sums[1], 3.0 + 6.0, epsilon = 1e-10); // Region 3
    }

    #[test]
    fn test_sum_labels_edge_cases() {
        // Empty result case
        let input = array![[1.0, 2.0]];
        let labels = array![[0, 0]]; // All background
        let sums = sum_labels(&input, &labels, None)
            .expect("sum_labels should succeed for empty result test");
        assert_eq!(sums.len(), 0);

        // Single pixel regions
        let input2 = array![[1.0, 2.0, 3.0]];
        let labels2 = array![[1, 2, 3]];
        let sums2 = sum_labels(&input2, &labels2, None)
            .expect("sum_labels should succeed for single pixel test");
        assert_eq!(sums2.len(), 3);
        assert_abs_diff_eq!(sums2[0], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(sums2[1], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(sums2[2], 3.0, epsilon = 1e-10);
    }

    #[test]
    fn test_sum_labels_3d() {
        let input = Array3::from_shape_fn((2, 2, 2), |(i, j, k)| (i + j + k) as f64);
        let labels = Array3::from_shape_fn((2, 2, 2), |(i, j, _k)| if i == j { 1 } else { 2 });

        let sums =
            sum_labels(&input, &labels, None).expect("sum_labels should succeed for 3D test");
        assert_eq!(sums.len(), 2);
        assert!(sums[0] > 0.0);
        assert!(sums[1] > 0.0);
    }

    #[test]
    fn test_mean_labels_basic() {
        let input: Array2<f64> = Array2::eye(3);
        let labels: Array2<usize> = Array2::from_elem((3, 3), 1);
        let result =
            mean_labels(&input, &labels, None).expect("mean_labels should succeed for basic test");

        assert!(!result.is_empty());
        assert_eq!(result.len(), 1);
        assert_abs_diff_eq!(result[0], 3.0 / 9.0, epsilon = 1e-10);
    }

    #[test]
    fn test_mean_labels_multiple_regions() {
        let input = array![[2.0, 4.0, 6.0], [8.0, 10.0, 12.0]];
        let labels = array![[1, 1, 2], [1, 2, 2]];

        let means = mean_labels(&input, &labels, None)
            .expect("mean_labels should succeed for multiple regions test");
        assert_eq!(means.len(), 2);
        assert_abs_diff_eq!(means[0], (2.0 + 4.0 + 8.0) / 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(means[1], (6.0 + 10.0 + 12.0) / 3.0, epsilon = 1e-10);
    }

    #[test]
    fn test_variance_labels_basic() {
        let input = array![[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]];
        let labels = array![[1, 1, 2], [1, 2, 2]];

        let variances = variance_labels(&input, &labels, None)
            .expect("variance_labels should succeed for basic test");
        assert_eq!(variances.len(), 2);

        // Manual variance calculation for region 1: [1, 3, 2]
        // Mean = 2.0, variance = ((1-2)² + (3-2)² + (2-2)²) / (3-1) = (1+1+0)/2 = 1.0
        assert_abs_diff_eq!(variances[0], 1.0, epsilon = 1e-10);

        // Manual variance calculation for region 2: [5, 4, 6]
        // Mean = 5.0, variance = ((5-5)² + (4-5)² + (6-5)²) / (3-1) = (0+1+1)/2 = 1.0
        assert_abs_diff_eq!(variances[1], 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_variance_labels_zero_variance() {
        let input = array![[5.0, 5.0, 3.0], [5.0, 3.0, 3.0]];
        let labels = array![[1, 1, 2], [1, 2, 2]];

        let variances = variance_labels(&input, &labels, None)
            .expect("variance_labels should succeed for zero variance test");
        assert_eq!(variances.len(), 2);
        assert_abs_diff_eq!(variances[0], 0.0, epsilon = 1e-10); // All values are 5.0
        assert_abs_diff_eq!(variances[1], 0.0, epsilon = 1e-10); // All values are 3.0
    }

    #[test]
    fn test_variance_labels_single_pixel() {
        let input = array![[1.0, 2.0, 3.0]];
        let labels = array![[1, 2, 3]]; // Each pixel is its own region

        let variances = variance_labels(&input, &labels, None)
            .expect("variance_labels should succeed for single pixel test");
        assert_eq!(variances.len(), 3);
        // Single pixel regions should have zero variance
        assert_abs_diff_eq!(variances[0], 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(variances[1], 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(variances[2], 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_count_labels_basic() {
        let labels: Array2<usize> = Array2::from_elem((3, 3), 1);
        let result =
            count_labels(&labels, None).expect("count_labels should succeed for basic test");

        assert!(!result.is_empty());
        assert_eq!(result.len(), 1);
        assert_eq!(result[0], 9); // 3x3 grid with all label 1
    }

    #[test]
    fn test_count_labels_multiple_regions() {
        let labels = array![[1, 1, 2, 2], [1, 3, 3, 2], [4, 4, 4, 4]];

        let counts = count_labels(&labels, None)
            .expect("count_labels should succeed for multiple regions test");
        assert_eq!(counts.len(), 4);
        assert_eq!(counts[0], 3); // Region 1: 3 pixels
        assert_eq!(counts[1], 3); // Region 2: 3 pixels
        assert_eq!(counts[2], 2); // Region 3: 2 pixels
        assert_eq!(counts[3], 4); // Region 4: 4 pixels
    }

    #[test]
    fn test_count_labels_with_background() {
        let labels = array![[0, 1, 1], [0, 2, 2], [0, 0, 3]];

        let counts =
            count_labels(&labels, None).expect("count_labels should succeed with background test");
        assert_eq!(counts.len(), 3); // Should exclude background (label 0)
        assert_eq!(counts[0], 2); // Region 1: 2 pixels
        assert_eq!(counts[1], 2); // Region 2: 2 pixels
        assert_eq!(counts[2], 1); // Region 3: 1 pixel
    }

    #[test]
    fn test_error_handling() {
        // Test dimension mismatch
        let input = array![[1.0, 2.0]];
        let labels = array![[1], [2]]; // Wrong shape

        assert!(sum_labels(&input, &labels, None).is_err());
        assert!(mean_labels(&input, &labels, None).is_err());
        assert!(variance_labels(&input, &labels, None).is_err());

        // Test 0-dimensional input
        let input_0d = scirs2_core::ndarray::arr0(1.0);
        let labels_0d = scirs2_core::ndarray::arr0(1);

        assert!(sum_labels(&input_0d, &labels_0d, None).is_err());
        assert!(mean_labels(&input_0d, &labels_0d, None).is_err());
        assert!(variance_labels(&input_0d, &labels_0d, None).is_err());
        assert!(count_labels(&labels_0d, None).is_err());
    }

    #[test]
    fn test_high_dimensional_arrays() {
        // Test 4D arrays
        let input = Array::from_shape_fn((2, 2, 2, 2), |(i, j, k, l)| (i + j + k + l) as f64);
        let labels = Array::from_shape_fn((2, 2, 2, 2), |(i, j, _k, _l)| i + j + 1);

        let sums =
            sum_labels(&input, &labels, None).expect("sum_labels should succeed for 4D test");
        let means =
            mean_labels(&input, &labels, None).expect("mean_labels should succeed for 4D test");
        let variances = variance_labels(&input, &labels, None)
            .expect("variance_labels should succeed for 4D test");
        let counts = count_labels(&labels, None).expect("count_labels should succeed for 4D test");

        assert!(!sums.is_empty());
        assert!(!means.is_empty());
        assert!(!variances.is_empty());
        assert!(!counts.is_empty());
        assert_eq!(sums.len(), means.len());
        assert_eq!(means.len(), variances.len());
        assert_eq!(variances.len(), counts.len());
    }
}