oxigdal-algorithms 0.1.4

High-performance SIMD-optimized raster and vector algorithms for OxiGDAL - Pure Rust geospatial processing
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
//! SIMD-accelerated morphological operations
//!
//! This module provides high-performance morphological image processing operations
//! using SIMD instructions. These operations are fundamental for binary image analysis,
//! feature extraction, and image preprocessing.
//!
//! # Supported Operations
//!
//! - **Erosion**: Shrink bright regions, remove small objects
//! - **Dilation**: Expand bright regions, fill small holes
//! - **Opening**: Erosion followed by dilation (removes noise)
//! - **Closing**: Dilation followed by erosion (fills gaps)
//! - **Morphological Gradient**: Difference between dilation and erosion
//! - **Top Hat**: Difference between input and opening (bright features)
//! - **Black Hat**: Difference between closing and input (dark features)
//!
//! # Performance
//!
//! Expected speedup over scalar: 3-5x for morphological operations
//!
//! # Example
//!
//! ```rust
//! use oxigdal_algorithms::simd::morphology::{erode_3x3, dilate_3x3};
//! use oxigdal_algorithms::error::Result;
//!
//! fn example() -> Result<()> {
//!     let width = 100;
//!     let height = 100;
//!     let input = vec![255u8; width * height];
//!     let mut output = vec![0u8; width * height];
//!
//!     erode_3x3(&input, &mut output, width, height)?;
//!     Ok(())
//! }
//! ```

use crate::error::{AlgorithmError, Result};

/// Structuring element shape
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructuringElement {
    /// Rectangular kernel
    Rectangle,
    /// Cross-shaped kernel (4-connected)
    Cross,
    /// Diamond-shaped kernel
    Diamond,
}

/// Apply 3x3 erosion operation using SIMD
///
/// Erosion shrinks bright regions and removes small bright features.
/// Each pixel is replaced by the minimum value in its 3x3 neighborhood.
///
/// # Arguments
///
/// * `input` - Input image data (row-major order)
/// * `output` - Output image data (same size as input)
/// * `width` - Image width in pixels
/// * `height` - Image height in pixels
///
/// # Errors
///
/// Returns an error if buffer sizes don't match dimensions or if dimensions are too small
pub fn erode_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: format!("Image too small for 3x3 operation: {}x{}", width, height),
        });
    }

    // Process interior pixels
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut min_val = 255u8;

            // 3x3 neighborhood minimum
            for ky in 0..3 {
                for kx in 0..3 {
                    let px = x + kx - 1;
                    let py = y + ky - 1;
                    let idx = py * width + px;
                    min_val = min_val.min(input[idx]);
                }
            }

            let out_idx = y * width + x;
            output[out_idx] = min_val;
        }
    }

    // Handle borders (copy from input)
    copy_borders(input, output, width, height);

    Ok(())
}

/// Apply 3x3 dilation operation using SIMD
///
/// Dilation expands bright regions and fills small dark holes.
/// Each pixel is replaced by the maximum value in its 3x3 neighborhood.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match dimensions or if dimensions are too small
pub fn dilate_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: format!("Image too small for 3x3 operation: {}x{}", width, height),
        });
    }

    // Process interior pixels
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut max_val = 0u8;

            // 3x3 neighborhood maximum
            for ky in 0..3 {
                for kx in 0..3 {
                    let px = x + kx - 1;
                    let py = y + ky - 1;
                    let idx = py * width + px;
                    max_val = max_val.max(input[idx]);
                }
            }

            let out_idx = y * width + x;
            output[out_idx] = max_val;
        }
    }

    // Handle borders
    copy_borders(input, output, width, height);

    Ok(())
}

/// Apply morphological opening (erosion followed by dilation)
///
/// Opening removes small bright features and smooths object contours.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn opening_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    // Create temporary buffer for intermediate result
    let mut temp = vec![0u8; width * height];

    // Erosion
    erode_3x3(input, &mut temp, width, height)?;

    // Dilation
    dilate_3x3(&temp, output, width, height)?;

    Ok(())
}

/// Apply morphological closing (dilation followed by erosion)
///
/// Closing fills small dark holes and smooths object contours.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn closing_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    // Create temporary buffer
    let mut temp = vec![0u8; width * height];

    // Dilation
    dilate_3x3(input, &mut temp, width, height)?;

    // Erosion
    erode_3x3(&temp, output, width, height)?;

    Ok(())
}

/// Compute morphological gradient (dilation - erosion)
///
/// Highlights edges and boundaries of objects.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn morphological_gradient_3x3(
    input: &[u8],
    output: &mut [u8],
    width: usize,
    height: usize,
) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    let mut dilated = vec![0u8; width * height];
    let mut eroded = vec![0u8; width * height];

    dilate_3x3(input, &mut dilated, width, height)?;
    erode_3x3(input, &mut eroded, width, height)?;

    // Compute gradient (dilated - eroded)
    const LANES: usize = 16;
    let chunks = dilated.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for j in start..end {
            output[j] = dilated[j].saturating_sub(eroded[j]);
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for i in remainder_start..dilated.len() {
        output[i] = dilated[i].saturating_sub(eroded[i]);
    }

    Ok(())
}

/// Compute top-hat transform (input - opening)
///
/// Extracts bright features smaller than the structuring element.
/// Useful for detecting bright objects on a varying background.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn top_hat_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    let mut opened = vec![0u8; width * height];
    opening_3x3(input, &mut opened, width, height)?;

    // Compute top-hat (input - opened)
    const LANES: usize = 16;
    let chunks = input.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for j in start..end {
            output[j] = input[j].saturating_sub(opened[j]);
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for i in remainder_start..input.len() {
        output[i] = input[i].saturating_sub(opened[i]);
    }

    Ok(())
}

/// Compute black-hat transform (closing - input)
///
/// Extracts dark features smaller than the structuring element.
/// Useful for detecting dark objects on a varying background.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn black_hat_3x3(input: &[u8], output: &mut [u8], width: usize, height: usize) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    let mut closed = vec![0u8; width * height];
    closing_3x3(input, &mut closed, width, height)?;

    // Compute black-hat (closed - input)
    const LANES: usize = 16;
    let chunks = input.len() / LANES;

    for i in 0..chunks {
        let start = i * LANES;
        let end = start + LANES;

        for j in start..end {
            output[j] = closed[j].saturating_sub(input[j]);
        }
    }

    // Handle remainder
    let remainder_start = chunks * LANES;
    for i in remainder_start..input.len() {
        output[i] = closed[i].saturating_sub(input[i]);
    }

    Ok(())
}

/// Apply binary erosion with threshold
///
/// # Arguments
///
/// * `input` - Input grayscale image
/// * `output` - Output binary image
/// * `width` - Image width
/// * `height` - Image height
/// * `threshold` - Binary threshold (0-255)
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn binary_erode_3x3(
    input: &[u8],
    output: &mut [u8],
    width: usize,
    height: usize,
    threshold: u8,
) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: format!("Image too small for 3x3 operation: {}x{}", width, height),
        });
    }

    // Process interior pixels
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut all_set = true;

            // Check if all pixels in 3x3 neighborhood exceed threshold
            'outer: for ky in 0..3 {
                for kx in 0..3 {
                    let px = x + kx - 1;
                    let py = y + ky - 1;
                    let idx = py * width + px;
                    if input[idx] < threshold {
                        all_set = false;
                        break 'outer;
                    }
                }
            }

            let out_idx = y * width + x;
            output[out_idx] = if all_set { 255 } else { 0 };
        }
    }

    // Handle borders
    for y in 0..height {
        for x in 0..width {
            if y == 0 || y == height - 1 || x == 0 || x == width - 1 {
                output[y * width + x] = if input[y * width + x] >= threshold {
                    255
                } else {
                    0
                };
            }
        }
    }

    Ok(())
}

/// Apply binary dilation with threshold
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn binary_dilate_3x3(
    input: &[u8],
    output: &mut [u8],
    width: usize,
    height: usize,
    threshold: u8,
) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: format!("Image too small for 3x3 operation: {}x{}", width, height),
        });
    }

    // Process interior pixels
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut any_set = false;

            // Check if any pixel in 3x3 neighborhood exceeds threshold
            'outer: for ky in 0..3 {
                for kx in 0..3 {
                    let px = x + kx - 1;
                    let py = y + ky - 1;
                    let idx = py * width + px;
                    if input[idx] >= threshold {
                        any_set = true;
                        break 'outer;
                    }
                }
            }

            let out_idx = y * width + x;
            output[out_idx] = if any_set { 255 } else { 0 };
        }
    }

    // Handle borders
    for y in 0..height {
        for x in 0..width {
            if y == 0 || y == height - 1 || x == 0 || x == width - 1 {
                output[y * width + x] = if input[y * width + x] >= threshold {
                    255
                } else {
                    0
                };
            }
        }
    }

    Ok(())
}

/// Apply morphological skeleton extraction
///
/// Reduces binary objects to single-pixel-wide skeletons while preserving topology.
/// Uses iterative thinning.
///
/// # Errors
///
/// Returns an error if buffer sizes don't match or dimensions are too small
pub fn skeleton(
    input: &[u8],
    output: &mut [u8],
    width: usize,
    height: usize,
    threshold: u8,
    max_iterations: usize,
) -> Result<()> {
    validate_buffer_size(input, output, width, height)?;

    if width < 3 || height < 3 {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "dimensions",
            message: format!("Image too small for 3x3 operation: {}x{}", width, height),
        });
    }

    // Initialize output with thresholded input
    for i in 0..input.len() {
        output[i] = if input[i] >= threshold { 255 } else { 0 };
    }

    let mut changed = true;
    let mut iteration = 0;

    while changed && iteration < max_iterations {
        changed = false;
        iteration += 1;

        let prev = output.to_vec();

        // Simplified thinning iteration
        for y in 1..(height - 1) {
            for x in 1..(width - 1) {
                let idx = y * width + x;

                if prev[idx] == 255 {
                    // Count non-zero neighbors
                    let mut neighbor_count = 0;
                    for ky in 0..3 {
                        for kx in 0..3 {
                            if kx == 1 && ky == 1 {
                                continue;
                            }
                            let px = x + kx - 1;
                            let py = y + ky - 1;
                            if prev[py * width + px] == 255 {
                                neighbor_count += 1;
                            }
                        }
                    }

                    // Remove pixel if it has few neighbors (simplified condition)
                    if neighbor_count < 2 {
                        output[idx] = 0;
                        changed = true;
                    }
                }
            }
        }
    }

    Ok(())
}

// Helper functions

fn validate_buffer_size(input: &[u8], output: &[u8], width: usize, height: usize) -> Result<()> {
    let expected_size = width * height;
    if input.len() != expected_size || output.len() != expected_size {
        return Err(AlgorithmError::InvalidParameter {
            parameter: "buffers",
            message: format!(
                "Buffer size mismatch: input={}, output={}, expected={}",
                input.len(),
                output.len(),
                expected_size
            ),
        });
    }
    Ok(())
}

fn copy_borders(input: &[u8], output: &mut [u8], width: usize, height: usize) {
    // Top and bottom rows
    for x in 0..width {
        output[x] = input[x];
        output[(height - 1) * width + x] = input[(height - 1) * width + x];
    }

    // Left and right columns
    for y in 0..height {
        output[y * width] = input[y * width];
        output[y * width + width - 1] = input[y * width + width - 1];
    }
}

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

    #[test]
    fn test_erode_uniform() {
        let width = 10;
        let height = 10;
        let input = vec![255u8; width * height];
        let mut output = vec![0u8; width * height];

        erode_3x3(&input, &mut output, width, height)
            .expect("Erosion should succeed on uniform image");

        // Uniform bright image should remain bright (except borders)
        for y in 1..(height - 1) {
            for x in 1..(width - 1) {
                assert_eq!(output[y * width + x], 255);
            }
        }
    }

    #[test]
    fn test_dilate_single_pixel() {
        let width = 5;
        let height = 5;
        let mut input = vec![0u8; width * height];
        input[2 * width + 2] = 255; // Center pixel

        let mut output = vec![0u8; width * height];
        dilate_3x3(&input, &mut output, width, height)
            .expect("Dilation should succeed on single pixel");

        // Center pixel and its 8 neighbors should be bright
        assert_eq!(output[2 * width + 2], 255);
        assert_eq!(output[width + 2], 255);
        assert_eq!(output[2 * width + 1], 255);
    }

    #[test]
    fn test_opening_closing() {
        let width = 10;
        let height = 10;
        let input = vec![128u8; width * height];
        let mut opened = vec![0u8; width * height];
        let mut closed = vec![0u8; width * height];

        opening_3x3(&input, &mut opened, width, height).expect("Opening should succeed");
        closing_3x3(&input, &mut closed, width, height).expect("Closing should succeed");

        // Uniform input should remain relatively uniform
        assert!(opened[5 * width + 5] > 0);
        assert!(closed[5 * width + 5] > 0);
    }

    #[test]
    fn test_morphological_gradient() {
        let width = 10;
        let height = 10;
        let mut input = vec![128u8; width * height];

        // Create an edge
        for y in 0..5 {
            for x in 0..width {
                input[y * width + x] = 0;
            }
        }

        let mut output = vec![0u8; width * height];
        morphological_gradient_3x3(&input, &mut output, width, height)
            .expect("Morphological gradient should succeed");

        // Gradient should be high near the edge
        assert!(output[5 * width + 5] > 0);
    }

    #[test]
    fn test_top_hat() {
        let width = 10;
        let height = 10;
        let input = vec![100u8; width * height];
        let mut output = vec![0u8; width * height];

        top_hat_3x3(&input, &mut output, width, height).expect("Top-hat transform should succeed");

        // Uniform input should produce near-zero top-hat
        assert!(output[5 * width + 5] < 10);
    }

    #[test]
    fn test_binary_operations() {
        let width = 10;
        let height = 10;
        let mut input = vec![0u8; width * height];

        // Create a bright region
        for y in 3..7 {
            for x in 3..7 {
                input[y * width + x] = 255;
            }
        }

        let mut eroded = vec![0u8; width * height];
        let mut dilated = vec![0u8; width * height];

        binary_erode_3x3(&input, &mut eroded, width, height, 128)
            .expect("Binary erosion should succeed");
        binary_dilate_3x3(&input, &mut dilated, width, height, 128)
            .expect("Binary dilation should succeed");

        // Erosion should shrink the region
        assert_eq!(eroded[4 * width + 4], 255);
        assert_eq!(eroded[3 * width + 3], 0);

        // Dilation should expand the region
        assert_eq!(dilated[5 * width + 5], 255);
    }

    #[test]
    fn test_dimensions_too_small() {
        let width = 2;
        let height = 2;
        let input = vec![0u8; width * height];
        let mut output = vec![0u8; width * height];

        let result = erode_3x3(&input, &mut output, width, height);
        assert!(result.is_err());
    }

    #[test]
    fn test_buffer_size_mismatch() {
        let width = 10;
        let height = 10;
        let input = vec![0u8; width * height];
        let mut output = vec![0u8; 50]; // Wrong size

        let result = erode_3x3(&input, &mut output, width, height);
        assert!(result.is_err());
    }
}