scirs2-vision 0.4.4

Computer vision module for SciRS2 (scirs2-vision)
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
//! Sobel edge detection with gradient orientation
//!
//! The Sobel operator is used to detect edges in images by computing
//! the gradient magnitude and optionally the gradient direction.

use crate::error::Result;
use crate::feature::image_to_array;
use crate::simd_ops;
use image::{DynamicImage, GrayImage};
use scirs2_core::ndarray::Array2;
use scirs2_core::simd_ops::SimdUnifiedOps;
use std::f32::consts::PI;

/// Sobel edge detection with gradient magnitude and orientation
///
/// Computes edge strength and direction using Sobel operators.
///
/// # Arguments
///
/// * `img` - Input image
/// * `threshold` - Threshold for edge detection (0.0 to 1.0)
/// * `compute_orientation` - Whether to compute gradient orientation
///
/// # Returns
///
/// * Result containing tuple of (edge_image, Option<orientation_map>)
///   where orientation_map contains angles in radians [-π, π]
///
/// # Example
///
/// ```rust
/// use scirs2_vision::feature::sobel_edges_oriented;
/// use image::DynamicImage;
///
/// # fn main() -> scirs2_vision::error::Result<()> {
/// let img = image::open("examples/input/input.jpg").expect("Operation failed");
/// let (edges, orientations) = sobel_edges_oriented(&img, 0.1, true)?;
/// # Ok(())
/// # }
/// ```
#[allow(dead_code)]
pub fn sobel_edges_oriented(
    img: &DynamicImage,
    threshold: f32,
    compute_orientation: bool,
) -> Result<(GrayImage, Option<Array2<f32>>)> {
    let array = image_to_array(img)?;
    let (height, width) = array.dim();

    // Sobel kernels
    let sobel_x = [[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]];

    let sobel_y = [[-1.0, -2.0, -1.0], [0.0, 0.0, 0.0], [1.0, 2.0, 1.0]];

    let mut gradient_x = Array2::zeros((height, width));
    let mut gradient_y = Array2::zeros((height, width));
    let mut magnitude = Array2::zeros((height, width));
    let mut _orientation = if compute_orientation {
        Some(Array2::zeros((height, width)))
    } else {
        None
    };

    // Apply Sobel operators
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut gx = 0.0;
            let mut gy = 0.0;

            // Convolve with Sobel kernels
            for ky in 0..3 {
                for kx in 0..3 {
                    let pixel = array[[y + ky - 1, x + kx - 1]];
                    gx += pixel * sobel_x[ky][kx];
                    gy += pixel * sobel_y[ky][kx];
                }
            }

            gradient_x[[y, x]] = gx;
            gradient_y[[y, x]] = gy;

            // Compute gradient magnitude
            let mag = (gx * gx + gy * gy).sqrt();
            magnitude[[y, x]] = mag;

            // Compute gradient _orientation if requested
            if let Some(ref mut orient) = _orientation {
                orient[[y, x]] = gy.atan2(gx);
            }
        }
    }

    // Create binary edge image
    let edges =
        crate::feature::array_to_image(&magnitude.mapv(|x| if x > threshold { 1.0 } else { 0.0 }))?;

    Ok((edges, _orientation))
}

/// Simple Sobel edge detection (magnitude only)
///
/// # Arguments
///
/// * `img` - Input image
/// * `threshold` - Threshold for edge detection
///
/// # Returns
///
/// * Result containing edge image
#[allow(dead_code)]
pub fn sobel_edges(img: &DynamicImage, threshold: f32) -> Result<GrayImage> {
    let (edges, _) = sobel_edges_oriented(img, threshold, false)?;
    Ok(edges)
}

/// SIMD-accelerated Sobel edge detection
///
/// Uses SIMD operations when available for improved performance.
/// Falls back to regular implementation if SIMD is not available.
///
/// # Arguments
///
/// * `img` - Input image
/// * `threshold` - Threshold for edge detection
/// * `compute_orientation` - Whether to compute gradient orientation
///
/// # Returns
///
/// * Result containing tuple of (edge_image, Option<orientation_map>)
///
/// # Performance
///
/// 2-4x faster than regular implementation on SIMD-capable hardware.
#[allow(dead_code)]
pub fn sobel_edges_simd(
    img: &DynamicImage,
    threshold: f32,
    compute_orientation: bool,
) -> Result<(GrayImage, Option<Array2<f32>>)> {
    // Check if SIMD is available
    if f32::simd_available() {
        let array = image_to_array(img)?;

        // Use SIMD-accelerated gradient computation
        let (grad_x, grad_y, magnitude) = simd_ops::simd_sobel_gradients(&array.view())?;

        // Compute _orientation if requested
        let _orientation = if compute_orientation {
            let (height, width) = array.dim();
            let mut orient = Array2::zeros((height, width));

            // Compute _orientation using atan2
            for y in 0..height {
                for x in 0..width {
                    orient[[y, x]] = grad_y[[y, x]].atan2(grad_x[[y, x]]);
                }
            }

            Some(orient)
        } else {
            None
        };

        // Create binary edge image
        let edges =
            crate::feature::array_to_image(
                &magnitude.mapv(|x| if x > threshold { 1.0 } else { 0.0 }),
            )?;

        Ok((edges, _orientation))
    } else {
        // Fall back to regular implementation
        sobel_edges_oriented(img, threshold, compute_orientation)
    }
}

/// Compute gradient magnitude and orientation
///
/// Returns the raw gradient magnitude and orientation maps without thresholding.
///
/// # Arguments
///
/// * `img` - Input image
///
/// # Returns
///
/// * Result containing tuple of (magnitude_map, orientation_map)
#[allow(dead_code)]
pub fn compute_gradients(img: &DynamicImage) -> Result<(Array2<f32>, Array2<f32>)> {
    let array = image_to_array(img)?;
    let (height, width) = array.dim();

    // Sobel kernels
    let sobel_x = [[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]];

    let sobel_y = [[-1.0, -2.0, -1.0], [0.0, 0.0, 0.0], [1.0, 2.0, 1.0]];

    let mut magnitude = Array2::zeros((height, width));
    let mut orientation = Array2::zeros((height, width));

    // Apply Sobel operators
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let mut gx = 0.0;
            let mut gy = 0.0;

            // Convolve with Sobel kernels
            for ky in 0..3 {
                for kx in 0..3 {
                    let pixel = array[[y + ky - 1, x + kx - 1]];
                    gx += pixel * sobel_x[ky][kx];
                    gy += pixel * sobel_y[ky][kx];
                }
            }

            // Compute gradient magnitude
            magnitude[[y, x]] = (gx * gx + gy * gy).sqrt();

            // Compute gradient orientation
            orientation[[y, x]] = gy.atan2(gx);
        }
    }

    Ok((magnitude, orientation))
}

/// Create a color-coded orientation visualization
///
/// Maps gradient orientations to colors using HSV color space.
///
/// # Arguments
///
/// * `magnitude` - Gradient magnitude map
/// * `orientation` - Gradient orientation map (in radians)
/// * `mag_threshold` - Minimum magnitude to display
///
/// # Returns
///
/// * Result containing RGB visualization image
#[allow(dead_code)]
pub fn visualize_gradient_orientation(
    magnitude: &Array2<f32>,
    orientation: &Array2<f32>,
    mag_threshold: f32,
) -> Result<image::RgbImage> {
    use image::{Rgb, RgbImage};

    let (height, width) = magnitude.dim();
    let mut output = RgbImage::new(width as u32, height as u32);

    // Find max magnitude for normalization
    let max_mag = magnitude.iter().fold(0.0f32, |a, &b| a.max(b));

    for y in 0..height {
        for x in 0..width {
            let mag = magnitude[[y, x]];
            let angle = orientation[[y, x]];

            if mag > mag_threshold {
                // Map angle to hue (0-360 degrees)
                let hue = ((angle + PI) / (2.0 * PI)) * 360.0;

                // Use magnitude for saturation and value
                let saturation = (mag / max_mag).min(1.0);
                let value = saturation;

                // Convert HSV to RGB
                let (r, g, b) = hsv_to_rgb(hue, saturation, value);
                output.put_pixel(x as u32, y as u32, Rgb([r, g, b]));
            } else {
                output.put_pixel(x as u32, y as u32, Rgb([0, 0, 0]));
            }
        }
    }

    Ok(output)
}

/// Convert HSV to RGB
#[allow(dead_code)]
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
    let c = v * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = v - c;

    let (r, g, b) = if h < 60.0 {
        (c, x, 0.0)
    } else if h < 120.0 {
        (x, c, 0.0)
    } else if h < 180.0 {
        (0.0, c, x)
    } else if h < 240.0 {
        (0.0, x, c)
    } else if h < 300.0 {
        (x, 0.0, c)
    } else {
        (c, 0.0, x)
    };

    (
        ((r + m) * 255.0) as u8,
        ((g + m) * 255.0) as u8,
        ((b + m) * 255.0) as u8,
    )
}

/// Compute histogram of oriented gradients for a region
///
/// # Arguments
///
/// * `magnitude` - Gradient magnitude map
/// * `orientation` - Gradient orientation map
/// * `num_bins` - Number of orientation bins
///
/// # Returns
///
/// * Histogram of oriented gradients
#[allow(dead_code)]
pub fn compute_hog_histogram(
    magnitude: &Array2<f32>,
    orientation: &Array2<f32>,
    num_bins: usize,
) -> Vec<f32> {
    let mut histogram = vec![0.0; num_bins];
    let bin_size = 2.0 * PI / num_bins as f32;

    for (&mag, &angle) in magnitude.iter().zip(orientation.iter()) {
        if mag > 0.0 {
            // Normalize angle to [0, 2π]
            let normalized_angle = if angle < 0.0 { angle + 2.0 * PI } else { angle };

            // Compute bin index
            let bin = ((normalized_angle / bin_size) as usize).min(num_bins - 1);

            // Add magnitude to bin
            histogram[bin] += mag;
        }
    }

    // Normalize histogram
    let sum: f32 = histogram.iter().sum();
    if sum > 0.0 {
        for val in &mut histogram {
            *val /= sum;
        }
    }

    histogram
}

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

    #[test]
    fn test_sobel_edges() {
        let img = DynamicImage::new_luma8(10, 10);
        let result = sobel_edges(&img, 0.1);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sobel_edges_oriented() {
        let img = DynamicImage::new_luma8(10, 10);
        let result = sobel_edges_oriented(&img, 0.1, true);
        assert!(result.is_ok());

        let (edges, orientations) = result.expect("Operation failed");
        assert!(orientations.is_some());
        assert_eq!(edges.dimensions(), (10, 10));
    }

    #[test]
    fn test_compute_gradients() {
        // Create test image with vertical edge
        let mut img = GrayImage::new(10, 10);
        for y in 0..10 {
            for x in 0..10 {
                img.put_pixel(x, y, image::Luma([if x < 5 { 0 } else { 255 }]));
            }
        }
        let dynamic_img = DynamicImage::ImageLuma8(img);

        let result = compute_gradients(&dynamic_img);
        assert!(result.is_ok());

        let (magnitude, orientation) = result.expect("Operation failed");
        assert_eq!(magnitude.dim(), (10, 10));
        assert_eq!(orientation.dim(), (10, 10));

        // Check that we detect edge around x=5
        assert!(magnitude[[5, 5]] > 0.0);
    }

    #[test]
    fn test_hsv_to_rgb() {
        // Test primary colors
        assert_eq!(hsv_to_rgb(0.0, 1.0, 1.0), (255, 0, 0)); // Red
        assert_eq!(hsv_to_rgb(120.0, 1.0, 1.0), (0, 255, 0)); // Green
        assert_eq!(hsv_to_rgb(240.0, 1.0, 1.0), (0, 0, 255)); // Blue

        // Test grayscale
        assert_eq!(hsv_to_rgb(0.0, 0.0, 0.5), (127, 127, 127)); // Gray
    }

    #[test]
    fn test_hog_histogram() {
        let magnitude =
            Array2::from_shape_vec((3, 3), vec![1.0, 0.0, 1.0, 0.0, 2.0, 0.0, 1.0, 0.0, 1.0])
                .expect("Operation failed");

        let orientation = Array2::from_shape_vec(
            (3, 3),
            vec![0.0, 0.0, PI / 2.0, 0.0, PI, 0.0, -PI / 2.0, 0.0, PI],
        )
        .expect("Operation failed");

        let histogram = compute_hog_histogram(&magnitude, &orientation, 4);

        assert_eq!(histogram.len(), 4);

        // Check normalization
        let sum: f32 = histogram.iter().sum();
        assert!((sum - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_sobel_simd() {
        // Create test image with vertical edge
        let mut img = GrayImage::new(10, 10);
        for y in 0..10 {
            for x in 0..10 {
                img.put_pixel(x, y, image::Luma([if x < 5 { 0 } else { 255 }]));
            }
        }
        let dynamic_img = DynamicImage::ImageLuma8(img);

        // Test SIMD implementation
        let result = sobel_edges_simd(&dynamic_img, 100.0, true);
        assert!(result.is_ok());

        let (edges, orientations) = result.expect("Operation failed");
        assert!(orientations.is_some());
        assert_eq!(edges.dimensions(), (10, 10));

        // Compare with regular implementation
        let (edges_regular_, _) =
            sobel_edges_oriented(&dynamic_img, 100.0, true).expect("Operation failed");

        // Results should be similar (allowing for minor numerical differences)
        assert_eq!(edges.dimensions(), edges_regular_.dimensions());
    }
}