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
//! Region property measurement functions
use ;
use ;
use Debug;
use RegionProperties;
use crate;
/// Helper function to convert dimension pattern to coordinate vector
/// Extract comprehensive properties of labeled regions
///
/// This function analyzes segmented images to compute geometric and statistical properties
/// of each labeled region. It's essential for object analysis, feature extraction, and
/// quantitative image analysis workflows.
///
/// # Arguments
///
/// * `input` - Input array containing values (intensities, measurements, etc.)
/// * `labels` - Label array defining regions (same shape as input)
/// * `properties` - List of property names to extract (if None, extracts all available properties)
/// Supported properties: "area", "centroid", "bbox", "mean_intensity",
/// "min_intensity", "max_intensity", "perimeter", "eccentricity"
///
/// # Returns
///
/// * `Result<Vec<RegionProperties<T>>>` - Vector of region property structures, one per region
///
/// # Examples
///
/// ## Basic region analysis
/// ```rust
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::region_properties;
///
/// // Image with different regions
/// let image = array![
/// [100.0, 100.0, 200.0, 200.0],
/// [100.0, 100.0, 200.0, 200.0],
/// [150.0, 150.0, 150.0, 150.0],
/// [150.0, 150.0, 150.0, 150.0]
/// ];
///
/// let labels = array![
/// [1, 1, 2, 2],
/// [1, 1, 2, 2],
/// [3, 3, 3, 3],
/// [3, 3, 3, 3]
/// ];
///
/// let props = region_properties(&image, &labels, None).expect("Operation failed");
///
/// for prop in &props {
/// println!("Region {}: area={}, centroid={:?}",
/// prop.label, prop.area, prop.centroid);
/// }
/// ```
///
/// ## Cell morphology analysis
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::region_properties;
///
/// // Simulate segmented cell image
/// let cell_intensities = Array2::from_shape_fn((50, 50), |(i, j)| {
/// // Create different cell-like regions with varying intensities
/// match ((i / 10), (j / 10)) {
/// (1, 1) => 80.0 + ((i + j) % 5) as f64, // Cell 1
/// (1, 3) => 120.0 + ((i * j) % 8) as f64, // Cell 2
/// (3, 1) => 90.0 + ((i as i32 - j as i32).abs() % 6) as f64, // Cell 3
/// _ => 30.0, // Background
/// }
/// });
///
/// let cell_labels = Array2::from_shape_fn((50, 50), |(i, j)| {
/// match ((i / 10), (j / 10)) {
/// (1, 1) => 1, // Cell 1
/// (1, 3) => 2, // Cell 2
/// (3, 1) => 3, // Cell 3
/// _ => 0, // Background
/// }
/// });
///
/// // Extract all cell properties
/// let cell_props = region_properties(&cell_intensities, &cell_labels, None).expect("Operation failed");
///
/// // Analyze cell characteristics
/// for cell in &cell_props {
/// println!("Cell {}: ", cell.label);
/// println!(" Area: {} pixels", cell.area);
/// println!(" Centroid: ({:.1}, {:.1})", cell.centroid[0], cell.centroid[1]);
/// println!(" Bounding box: {:?}", cell.bbox);
/// }
/// ```
///
/// ## Selective property extraction
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_ndimage::measurements::region_properties;
///
/// let data = array![
/// [1.0, 2.0, 5.0, 6.0],
/// [3.0, 4.0, 7.0, 8.0],
/// [9.0, 10.0, 11.0, 12.0]
/// ];
///
/// let regions = array![
/// [1, 1, 2, 2],
/// [1, 1, 2, 2],
/// [3, 3, 3, 3]
/// ];
///
/// // Extract only area and centroid properties
/// let props = region_properties(&data, ®ions,
/// Some(vec!["area", "centroid"])).expect("Operation failed");
///
/// // Properties will only contain the requested measurements
/// ```
///
/// ## Materials analysis workflow
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::region_properties;
///
/// // Simulate microscopy image of material grains
/// let grainimage = Array2::from_shape_fn((100, 100), |(i, j)| {
/// // Create grain-like structures with different properties
/// let grain_id = ((i / 25) * 2 + (j / 25)) + 1;
/// let base_intensity = match grain_id {
/// 1 => 60.0, // Grain type A
/// 2 => 90.0, // Grain type B
/// 3 => 110.0, // Grain type C
/// _ => 75.0, // Grain type D
/// };
///
/// // Add some texture variation
/// let texture = ((i * 3 + j * 7) % 20) as f64;
/// base_intensity + texture
/// });
///
/// let grain_labels = Array2::from_shape_fn((100, 100), |(i, j)| {
/// ((i / 25) * 2 + (j / 25)) + 1
/// });
///
/// let grain_props = region_properties(&grainimage, &grain_labels, None).expect("Operation failed");
///
/// // Quality control: identify grains with unusual properties
/// let total_area: usize = grain_props.iter().map(|g| g.area).sum();
/// let avg_area = total_area as f64 / grain_props.len() as f64;
///
/// for grain in &grain_props {
/// let area_ratio = grain.area as f64 / avg_area;
/// if area_ratio < 0.5 {
/// println!("Small grain detected: {} (area: {})", grain.label, grain.area);
/// } else if area_ratio > 2.0 {
/// println!("Large grain detected: {} (area: {})", grain.label, grain.area);
/// }
/// }
/// ```
///
/// ## Medical imaging: lesion characterization
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::region_properties;
///
/// // Simulate medical image with lesions
/// let medical_scan = Array2::from_shape_fn((80, 80), |(i, j)| {
/// // Normal tissue background
/// let mut intensity = 100.0;
///
/// // Add lesions with different characteristics
/// let dist1 = ((i as f64 - 20.0).powi(2) + (j as f64 - 30.0).powi(2)).sqrt();
/// let dist2 = ((i as f64 - 60.0).powi(2) + (j as f64 - 50.0).powi(2)).sqrt();
///
/// if dist1 < 8.0 {
/// intensity = 150.0; // Bright lesion
/// } else if dist2 < 12.0 {
/// intensity = 80.0; // Dark lesion
/// }
///
/// intensity
/// });
///
/// let lesion_segmentation = Array2::from_shape_fn((80, 80), |(i, j)| {
/// let dist1 = ((i as f64 - 20.0).powi(2) + (j as f64 - 30.0).powi(2)).sqrt();
/// let dist2 = ((i as f64 - 60.0).powi(2) + (j as f64 - 50.0).powi(2)).sqrt();
///
/// if dist1 < 8.0 {
/// 1 // Lesion 1
/// } else if dist2 < 12.0 {
/// 2 // Lesion 2
/// } else {
/// 0 // Normal tissue
/// }
/// });
///
/// let lesion_props = region_properties(&medical_scan, &lesion_segmentation, None).expect("Operation failed");
///
/// // Clinical analysis
/// for lesion in &lesion_props {
/// let area_mm2 = lesion.area as f64 * 0.01; // Convert pixels to mm²
/// println!("Lesion {}: {:.2} mm², center at ({:.1}, {:.1})",
/// lesion.label, area_mm2, lesion.centroid[0], lesion.centroid[1]);
/// }
/// ```
///
/// # Region Property Details
///
/// The `RegionProperties` structure contains:
/// - **label**: Original label value from the segmentation
/// - **area**: Number of pixels in the region (2D) or voxels (3D)
/// - **centroid**: Center of mass coordinates [y, x] in 2D or [z, y, x] in 3D
/// - **bbox**: Bounding box [min_row, min_col, max_row, max_col] in 2D
///
/// # Applications
///
/// - **Cell Biology**: Analyze cell morphology, size, and intensity
/// - **Medical Imaging**: Characterize lesions, organs, and anatomical structures
/// - **Materials Science**: Study grain sizes, shapes, and distributions
/// - **Quality Control**: Identify defects and measure component properties
/// - **Ecology**: Analyze organism shapes and sizes in microscopy
/// - **Manufacturing**: Inspect part dimensions and surface features
///
/// # Performance Notes
///
/// - Time complexity: O(n) where n is the total number of pixels
/// - Space complexity: O(r) where r is the number of regions
/// - For large images with many regions, consider processing in parallel
/// - Property calculation time increases with the number of requested properties
///
/// # Implementation Note
///
/// Current implementation is a placeholder returning minimal data.
/// Full region property calculation needs to be implemented with proper
/// geometric and statistical computations.
///
/// # Errors
///
/// Returns an error if:
/// - Input array is 0-dimensional
/// - Input and labels arrays have different shapes
/// - Invalid property names are specified
/// Find and locate objects in a labeled array
///
/// This function identifies all objects (connected components) in a labeled array and
/// returns their bounding boxes. It's commonly used after segmentation to locate and
/// extract individual objects for further analysis or processing.
///
/// # Arguments
///
/// * `input` - Input labeled array where each unique non-zero value represents an object
///
/// # Returns
///
/// * `Result<Vec<Vec<usize>>>` - Vector of bounding box coordinates for each object.
/// Each inner vector contains [min_coord1, max_coord1, min_coord2, max_coord2, ...]
/// for each dimension of the array.
///
/// # Examples
///
/// ## Basic object detection in 2D
/// ```rust
/// use scirs2_core::ndarray::{Array2, array};
/// use scirs2_ndimage::measurements::find_objects;
///
/// let labeledimage = array![
/// [0, 1, 1, 0, 0],
/// [0, 1, 1, 0, 2],
/// [0, 0, 0, 0, 2],
/// [3, 3, 0, 0, 2],
/// [3, 3, 0, 0, 0]
/// ];
///
/// let objects = find_objects(&labeledimage).expect("Operation failed");
///
/// // objects[0] = bounding box for object 1: [0, 2, 1, 3] (rows 0-1, cols 1-2)
/// // objects[1] = bounding box for object 2: [1, 4, 4, 5] (rows 1-3, cols 4-4)
/// // objects[2] = bounding box for object 3: [3, 5, 0, 2] (rows 3-4, cols 0-1)
/// ```
///
/// ## Cell detection and extraction workflow
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::find_objects;
///
/// // Simulate cell segmentation result
/// let cell_labels = Array2::from_shape_fn((100, 100), |(i, j)| {
/// // Create scattered cell-like objects
/// match ((i / 20), (j / 25)) {
/// (1, 0) => 1, // Cell 1 in upper left
/// (1, 2) => 2, // Cell 2 in upper right
/// (3, 1) => 3, // Cell 3 in lower center
/// (4, 3) => 4, // Cell 4 in lower right
/// _ => 0, // Background
/// }
/// });
///
/// let cell_bboxes = find_objects(&cell_labels).expect("Operation failed");
///
/// // Process each detected cell
/// for (cell_id, bbox) in cell_bboxes.iter().enumerate() {
/// let cell_label = cell_id + 1;
/// println!("Cell {}: bounding box = {:?}", cell_label, bbox);
///
/// // Extract cell region for detailed analysis
/// let min_row = bbox[0];
/// let max_row = bbox[1];
/// let min_col = bbox[2];
/// let max_col = bbox[3];
///
/// let cell_width = max_col - min_col;
/// let cell_height = max_row - min_row;
///
/// println!(" Size: {}x{} pixels", cell_width, cell_height);
/// }
/// ```
///
/// ## 3D object detection
/// ```rust
/// use scirs2_core::ndarray::Array3;
/// use scirs2_ndimage::measurements::find_objects;
///
/// // Create 3D labeled volume
/// let labeled_volume = Array3::from_shape_fn((50, 50, 50), |(z, y, x)| {
/// // Create 3D objects at different positions
/// if (z >= 10 && z < 20) && (y >= 10 && y < 20) && (x >= 10 && x < 20) {
/// 1 // Object 1: cube in center
/// } else if (z >= 30 && z < 40) && (y >= 5 && y < 15) && (x >= 35 && x < 45) {
/// 2 // Object 2: cube in corner
/// } else {
/// 0 // Background
/// }
/// });
///
/// let object_bboxes = find_objects(&labeled_volume).expect("Operation failed");
///
/// for (obj_id, bbox) in object_bboxes.iter().enumerate() {
/// println!("3D Object {}: ", obj_id + 1);
/// println!(" Z range: {}-{}", bbox[0], bbox[1]);
/// println!(" Y range: {}-{}", bbox[2], bbox[3]);
/// println!(" X range: {}-{}", bbox[4], bbox[5]);
///
/// let volume = (bbox[1] - bbox[0]) * (bbox[3] - bbox[2]) * (bbox[5] - bbox[4]);
/// println!(" Bounding volume: {} voxels", volume);
/// }
/// ```
///
/// ## Object extraction and cropping
/// ```rust
/// use scirs2_core::ndarray::{Array2, s};
/// use scirs2_ndimage::measurements::find_objects;
///
/// let segmentedimage = Array2::from_shape_fn((60, 60), |(i, j)| {
/// // Create multiple objects
/// if (i >= 10 && i < 25) && (j >= 10 && j < 25) {
/// 1 // Square object
/// } else if ((i as i32 - 40).pow(2) + (j as i32 - 40).pow(2)) < 100 {
/// 2 // Circular object
/// } else {
/// 0 // Background
/// }
/// });
///
/// let bboxes = find_objects(&segmentedimage).expect("Operation failed");
///
/// // Extract each object as a separate sub-array
/// for (obj_id, bbox) in bboxes.iter().enumerate() {
/// let min_row = bbox[0];
/// let max_row = bbox[1];
/// let min_col = bbox[2];
/// let max_col = bbox[3];
///
/// // Crop the object from the original image
/// let cropped_object = segmentedimage.slice(s![min_row..max_row, min_col..max_col]);
///
/// println!("Object {} cropped to shape: {:?}", obj_id + 1, cropped_object.shape());
///
/// // Save or process the cropped object...
/// }
/// ```
///
/// ## Quality control: filter objects by size
/// ```rust
/// use scirs2_core::ndarray::Array2;
/// use scirs2_ndimage::measurements::find_objects;
///
/// let detection_result = Array2::from_shape_fn((100, 100), |(i, j)| {
/// // Simulate detection with objects of various sizes
/// match ((i / 15), (j / 15)) {
/// (0, 0) => 1, // Small object
/// (1, 1) => 2, // Medium object
/// (2, 2) => 3, // Large object
/// (5, 5) => 4, // Tiny object (noise)
/// _ => 0,
/// }
/// });
///
/// let all_bboxes = find_objects(&detection_result).expect("Operation failed");
///
/// // Filter objects by minimum size
/// let min_area = 100; // Minimum area threshold
/// let valid_objects: Vec<(usize, &Vec<usize>)> = all_bboxes.iter()
/// .enumerate()
/// .filter(|(_, bbox)| {
/// let area = (bbox[1] - bbox[0]) * (bbox[3] - bbox[2]);
/// area >= min_area
/// })
/// .collect();
///
/// println!("Found {} objects after size filtering", valid_objects.len());
///
/// for (obj_id, bbox) in valid_objects {
/// let area = (bbox[1] - bbox[0]) * (bbox[3] - bbox[2]);
/// println!("Valid object {}: area = {} pixels", obj_id + 1, area);
/// }
/// ```
///
/// # Applications
///
/// - **Object Detection**: Locate all objects in segmented images
/// - **Cell Biology**: Find and extract individual cells for analysis
/// - **Quality Control**: Identify and measure components or defects
/// - **Medical Imaging**: Locate anatomical structures or lesions
/// - **Materials Science**: Find and analyze particles or grains
/// - **Automated Analysis**: Batch process multiple objects
///
/// # Performance Notes
///
/// - Time complexity: O(n) where n is the total number of pixels
/// - Space complexity: O(k) where k is the number of objects
/// - For large images with many small objects, consider pre-filtering by size
/// - Processing scales linearly with image dimensions
///
/// # Implementation Note
///
/// Current implementation is a placeholder returning minimal data.
/// Full object detection algorithm needs to be implemented with proper
/// bounding box calculation for each unique label.
///
/// # Errors
///
/// Returns an error if:
/// - Input array is 0-dimensional
/// - Memory allocation fails for large numbers of objects
///
/// # Related Functions
///
/// - [`region_properties`]: Get detailed properties of each object
/// - `count_labels`: Count pixels in each object
/// - Label connectivity functions for segmentation preprocessing