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
//! Shi-Tomasi corner detector (Good Features to Track)
//!
//! An improvement over the Harris corner detector that uses a simpler
//! corner score calculation based on the minimum eigenvalue of the
//! structure tensor matrix.
//!
//! # References
//!
//! - Shi, J. and Tomasi, C., 1994, June. Good features to track. In 1994 Proceedings of IEEE conference on computer vision and pattern recognition (pp. 593-600). IEEE.

use crate::error::{Result, VisionError};
use crate::feature::image_to_array;
use image::{DynamicImage, GrayImage};
use scirs2_core::ndarray::Array2;

/// Shi-Tomasi corner detection (Good Features to Track)
///
/// Detects corners using the Shi-Tomasi method, which improves upon Harris
/// corner detection by using the minimum eigenvalue as the corner score.
///
/// # Arguments
///
/// * `img` - Input image
/// * `block_size` - Size of the window for corner detection
/// * `threshold` - Threshold for corner detection
/// * `max_corners` - Maximum number of corners to return (0 for all)
/// * `min_distance` - Minimum distance between corners
///
/// # Returns
///
/// * Result containing corner points
///
/// # Example
///
/// ```rust
/// use scirs2_vision::feature::shi_tomasi_corners;
/// use image::DynamicImage;
///
/// # fn main() -> scirs2_vision::error::Result<()> {
/// let img = image::open("examples/input/input.jpg").expect("Operation failed");
/// let corners = shi_tomasi_corners(&img, 3, 0.01, 100, 10)?;
/// # Ok(())
/// # }
/// ```
#[allow(dead_code)]
pub fn shi_tomasi_corners(
    img: &DynamicImage,
    block_size: usize,
    threshold: f32,
    max_corners: usize,
    min_distance: usize,
) -> Result<GrayImage> {
    let array = image_to_array(img)?;
    let (height, width) = array.dim();

    // Check if block_size is valid
    if block_size.is_multiple_of(2) || block_size < 3 {
        return Err(VisionError::InvalidParameter(
            "block_size must be odd and at least 3".to_string(),
        ));
    }

    // Step 1: Calculate gradients
    let mut ix2 = Array2::zeros((height, width));
    let mut iy2 = Array2::zeros((height, width));
    let mut ixy = Array2::zeros((height, width));

    // Calculate gradients using Sobel operators
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            // Sobel X
            let gx = -array[[y - 1, x - 1]]
                + 1.0 * array[[y - 1, x + 1]]
                + -2.0 * array[[y, x - 1]]
                + 2.0 * array[[y, x + 1]]
                + -array[[y + 1, x - 1]]
                + 1.0 * array[[y + 1, x + 1]];

            // Sobel Y
            let gy = -array[[y - 1, x - 1]]
                + -2.0 * array[[y - 1, x]]
                + -array[[y - 1, x + 1]]
                + 1.0 * array[[y + 1, x - 1]]
                + 2.0 * array[[y + 1, x]]
                + 1.0 * array[[y + 1, x + 1]];

            ix2[[y, x]] = gx * gx;
            iy2[[y, x]] = gy * gy;
            ixy[[y, x]] = gx * gy;
        }
    }

    // Step 2: Apply window function (box filter)
    let radius = block_size / 2;
    let mut smoothed_ix2 = Array2::zeros((height, width));
    let mut smoothed_iy2 = Array2::zeros((height, width));
    let mut smoothed_ixy = Array2::zeros((height, width));

    for y in radius..(height - radius) {
        for x in radius..(width - radius) {
            let mut sum_ix2 = 0.0;
            let mut sum_iy2 = 0.0;
            let mut sum_ixy = 0.0;
            let mut count = 0;

            for dy in (y - radius)..=(y + radius) {
                for dx in (x - radius)..=(x + radius) {
                    sum_ix2 += ix2[[dy, dx]];
                    sum_iy2 += iy2[[dy, dx]];
                    sum_ixy += ixy[[dy, dx]];
                    count += 1;
                }
            }

            smoothed_ix2[[y, x]] = sum_ix2 / count as f32;
            smoothed_iy2[[y, x]] = sum_iy2 / count as f32;
            smoothed_ixy[[y, x]] = sum_ixy / count as f32;
        }
    }

    // Step 3: Calculate Shi-Tomasi response (minimum eigenvalue)
    let mut response = Array2::zeros((height, width));

    for y in radius..(height - radius) {
        for x in radius..(width - radius) {
            // Structure tensor matrix:
            // [a b]
            // [b c]
            let a = smoothed_ix2[[y, x]];
            let b = smoothed_ixy[[y, x]];
            let c = smoothed_iy2[[y, x]];

            // Minimum eigenvalue calculation
            // λ = (a + c - sqrt((a - c)² + 4b²)) / 2
            let trace = a + c;
            let _det = a * c - b * b;
            let discriminant = ((a - c) * (a - c) + 4.0 * b * b).sqrt();
            let min_eigenvalue = (trace - discriminant) / 2.0;

            response[[y, x]] = min_eigenvalue;
        }
    }

    // Step 4: Threshold and extract _corners
    let mut _corners = Vec::new();

    for y in radius..(height - radius) {
        for x in radius..(width - radius) {
            if response[[y, x]] > threshold {
                _corners.push((x, y, response[[y, x]]));
            }
        }
    }

    // Sort by response strength
    _corners.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));

    // Filter by minimum _distance
    let mut selected_corners = Vec::new();

    for (x, y, score) in _corners {
        let mut too_close = false;

        for &(sx, sy_, _) in &selected_corners {
            let dist_sq = ((x as i32 - sx as i32).pow(2) + (y as i32 - sy_ as i32).pow(2)) as usize;
            if dist_sq < min_distance * min_distance {
                too_close = true;
                break;
            }
        }

        if !too_close {
            selected_corners.push((x, y, score));

            if max_corners > 0 && selected_corners.len() >= max_corners {
                break;
            }
        }
    }

    // Create output image
    let mut output = Array2::zeros((height, width));
    for (x, y_, _) in selected_corners {
        output[[y_, x]] = 1.0;
    }

    crate::feature::array_to_image(&output)
}

/// Simplified Shi-Tomasi corner detection
///
/// Uses default parameters suitable for most applications.
///
/// # Arguments
///
/// * `img` - Input image
/// * `max_corners` - Maximum number of corners to return
///
/// # Returns
///
/// * Result containing corner points
#[allow(dead_code)]
pub fn shi_tomasi_corners_simple(_img: &DynamicImage, maxcorners: usize) -> Result<GrayImage> {
    shi_tomasi_corners(_img, 3, 0.01, maxcorners, 10)
}

/// Extract good features to track with sub-pixel accuracy
///
/// Returns corner coordinates with floating-point precision.
///
/// # Arguments
///
/// * `img` - Input image
/// * `block_size` - Size of the window for corner detection
/// * `threshold` - Threshold for corner detection
/// * `max_corners` - Maximum number of corners to return
/// * `min_distance` - Minimum distance between corners
///
/// # Returns
///
/// * Result containing vector of (x, y, score) tuples
#[allow(dead_code)]
pub fn good_features_to_track(
    img: &DynamicImage,
    block_size: usize,
    threshold: f32,
    max_corners: usize,
    min_distance: usize,
) -> Result<Vec<(f32, f32, f32)>> {
    let array = image_to_array(img)?;
    let (height, width) = array.dim();

    // Check if block_size is valid
    if block_size.is_multiple_of(2) || block_size < 3 {
        return Err(VisionError::InvalidParameter(
            "block_size must be odd and at least 3".to_string(),
        ));
    }

    // Calculate gradients and response (same as above)
    let mut ix2 = Array2::zeros((height, width));
    let mut iy2 = Array2::zeros((height, width));
    let mut ixy = Array2::zeros((height, width));

    // Calculate gradients
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let gx = -array[[y - 1, x - 1]]
                + 1.0 * array[[y - 1, x + 1]]
                + -2.0 * array[[y, x - 1]]
                + 2.0 * array[[y, x + 1]]
                + -array[[y + 1, x - 1]]
                + 1.0 * array[[y + 1, x + 1]];

            let gy = -array[[y - 1, x - 1]]
                + -2.0 * array[[y - 1, x]]
                + -array[[y - 1, x + 1]]
                + 1.0 * array[[y + 1, x - 1]]
                + 2.0 * array[[y + 1, x]]
                + 1.0 * array[[y + 1, x + 1]];

            ix2[[y, x]] = gx * gx;
            iy2[[y, x]] = gy * gy;
            ixy[[y, x]] = gx * gy;
        }
    }

    // Apply window function
    let radius = block_size / 2;
    let mut response = Array2::zeros((height, width));

    for y in radius..(height - radius) {
        for x in radius..(width - radius) {
            let mut sum_ix2 = 0.0;
            let mut sum_iy2 = 0.0;
            let mut sum_ixy = 0.0;
            let mut count = 0;

            for dy in (y - radius)..=(y + radius) {
                for dx in (x - radius)..=(x + radius) {
                    sum_ix2 += ix2[[dy, dx]];
                    sum_iy2 += iy2[[dy, dx]];
                    sum_ixy += ixy[[dy, dx]];
                    count += 1;
                }
            }

            let a = sum_ix2 / count as f32;
            let b = sum_ixy / count as f32;
            let c = sum_iy2 / count as f32;

            // Minimum eigenvalue
            let trace = a + c;
            let discriminant = ((a - c) * (a - c) + 4.0 * b * b).sqrt();
            response[[y, x]] = (trace - discriminant) / 2.0;
        }
    }

    // Extract _corners with sub-pixel refinement
    let mut _corners = Vec::new();

    for y in (radius + 1)..(height - radius - 1) {
        for x in (radius + 1)..(width - radius - 1) {
            let r = response[[y, x]];

            if r > threshold {
                // Check if local maximum
                let mut is_max = true;
                for dy in -1..=1 {
                    for dx in -1..=1 {
                        if dy == 0 && dx == 0 {
                            continue;
                        }
                        if response[[(y as i32 + dy) as usize, (x as i32 + dx) as usize]] >= r {
                            is_max = false;
                            break;
                        }
                    }
                    if !is_max {
                        break;
                    }
                }

                if is_max {
                    // Sub-pixel refinement using quadratic interpolation
                    let dx = (response[[y, x + 1]] - response[[y, x - 1]]) / 2.0;
                    let dy = (response[[y + 1, x]] - response[[y - 1, x]]) / 2.0;
                    let dxx = response[[y, x + 1]] - 2.0 * r + response[[y, x - 1]];
                    let dyy = response[[y + 1, x]] - 2.0 * r + response[[y - 1, x]];

                    let mut sub_x = x as f32;
                    let mut sub_y = y as f32;

                    if dxx.abs() > 1e-6 {
                        sub_x -= dx / dxx;
                    }
                    if dyy.abs() > 1e-6 {
                        sub_y -= dy / dyy;
                    }

                    _corners.push((sub_x, sub_y, r));
                }
            }
        }
    }

    // Sort by response strength
    _corners.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));

    // Filter by minimum _distance
    let mut selected_corners = Vec::new();

    for (x, y, score) in _corners {
        let mut too_close = false;

        for &(sx, sy_, _) in &selected_corners {
            let x_diff: f32 = x - sx;
            let y_diff: f32 = y - sy_;
            let dist_sq: f32 = x_diff.powi(2) + y_diff.powi(2);
            if dist_sq < (min_distance as f32 * min_distance as f32) {
                too_close = true;
                break;
            }
        }

        if !too_close {
            selected_corners.push((x, y, score));

            if max_corners > 0 && selected_corners.len() >= max_corners {
                break;
            }
        }
    }

    Ok(selected_corners)
}

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

    #[test]
    fn test_shi_tomasi_detection() {
        // Create a test image with corners
        let mut img = GrayImage::new(20, 20);

        // Background
        for y in 0..20 {
            for x in 0..20 {
                img.put_pixel(x, y, Luma([128u8]));
            }
        }

        // Create a bright square
        for y in 5..15 {
            for x in 5..15 {
                img.put_pixel(x, y, Luma([255u8]));
            }
        }

        let dynamic_img = DynamicImage::ImageLuma8(img);
        let result = shi_tomasi_corners_simple(&dynamic_img, 10);

        assert!(result.is_ok());
        let corners = result.expect("Operation failed");

        // Count detected corners
        let mut corner_count = 0;
        for y in 0..20 {
            for x in 0..20 {
                if corners.get_pixel(x, y)[0] > 0 {
                    corner_count += 1;
                }
            }
        }

        // Should detect corners of the square
        assert!(
            corner_count >= 4,
            "Should detect at least 4 corners, found {corner_count}"
        );
    }

    #[test]
    fn test_good_features_to_track() {
        let img = GrayImage::new(20, 20);
        let dynamic_img = DynamicImage::ImageLuma8(img);

        let result = good_features_to_track(&dynamic_img, 3, 0.01, 10, 5);
        assert!(result.is_ok());

        let features = result.expect("Operation failed");
        assert!(features.len() <= 10, "Should not exceed max_corners");
    }

    #[test]
    fn test_invalid_block_size() {
        let img = GrayImage::new(20, 20);
        let dynamic_img = DynamicImage::ImageLuma8(img);

        // Test even block size
        let result = shi_tomasi_corners(&dynamic_img, 4, 0.01, 10, 5);
        assert!(result.is_err());

        // Test too small block size
        let result = shi_tomasi_corners(&dynamic_img, 1, 0.01, 10, 5);
        assert!(result.is_err());
    }
}