purecv 0.1.4

A pure Rust, high-performance computer vision library focused on safety and portability.
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
/*
 *  tests.rs
 *  purecv
 *
 *  This file is part of purecv - OpenCV.
 *
 *  purecv is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  purecv is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with purecv.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  As a special exception, the copyright holders of this library give you
 *  permission to link this library with independent modules to produce an
 *  executable, regardless of the license terms of these independent modules, and to
 *  copy and distribute the resulting executable under terms of your choice,
 *  provided that you also meet, for each linked independent module, the terms and
 *  conditions of the license of that module. An independent module is a module
 *  which is neither derived from nor based on this library. If you modify this
 *  library, you may extend this exception to your version of the library, but you
 *  are not obligated to do so. If you do not wish to do so, delete this exception
 *  statement from your version.
 *
 *  Copyright 2026 WebARKit.
 *
 *  Author(s): Walter Perdan @kalwalt https://github.com/kalwalt
 *
 */

#[cfg(test)]
mod tests {
    use crate::core::*;
    use crate::imgproc::*;

    #[test]
    fn test_blur() {
        let m = Matrix::from_vec(3, 3, 1, vec![10u8, 10, 10, 10, 10, 10, 10, 10, 10]);
        let ksize = Size2i::new(3, 3);
        let res = blur(&m, ksize, Point2i::new(-1, -1), BorderTypes::Reflect101).unwrap();
        assert_eq!(res.data, vec![10u8; 9]);
    }

    #[test]
    fn test_box_filter() {
        let m = Matrix::from_vec(3, 3, 1, vec![1u8, 1, 1, 1, 1, 1, 1, 1, 1]);
        let ksize = Size2i::new(3, 3);
        // Sum should be 9 for each pixel because of border reflection
        let res = box_filter(
            &m,
            ksize,
            Point2i::new(-1, -1),
            false,
            BorderTypes::Reflect101,
        )
        .unwrap();
        for val in res.data {
            assert_eq!(val, 9u8);
        }
    }

    #[test]
    fn test_gaussian_blur() {
        let m = Matrix::from_vec(5, 5, 1, vec![100u8; 25]);
        let ksize = Size2i::new(3, 3);
        let res = gaussian_blur(&m, ksize, 1.0, 1.0, BorderTypes::Reflect101).unwrap();
        // Since all pixels are 100, the result should be 100 (normalized)
        for val in res.data {
            assert!(val >= 99 && val <= 101); // Allow small deviation for rounding
        }
    }

    #[test]
    fn test_median_blur() {
        // Create a 3x3 matrix with an outlier
        let mut data = vec![10u8; 9];
        data[4] = 255; // Center is outlier
        let src = Matrix::from_vec(3, 3, 1, data);

        // Median of [10, 10, 10, 10, 255, 10, 10, 10, 10] is 10
        let blur = median_blur(&src, 3).unwrap();
        assert_eq!(*blur.at(1, 1, 0).unwrap(), 10);
    }

    #[test]
    fn test_bilateral_filter() {
        // Create a 5x5 matrix with an edge
        let mut data = vec![0u8; 25];
        for x in 3..5 {
            for y in 0..5 {
                data[y * 5 + x] = 255;
            }
        }
        let src = Matrix::from_vec(5, 5, 1, data);

        let res = bilateral_filter(&src, 5, 50.0, 50.0, BorderTypes::Reflect101).unwrap();

        // Edge should be preserved.
        // Row 2, Col 2 is x=2, y=2. Value is 0.
        // Row 2, Col 3 is x=3, y=2. Value is 255.
        let val_at_2_2 = *res.at(2, 2, 0).unwrap();
        let val_at_2_3 = *res.at(2, 3, 0).unwrap();

        assert!(val_at_2_2 < 50);
        assert!(val_at_2_3 > 200);
    }

    #[test]
    fn test_sobel() {
        // Vertical edge: left half 0, right half 255
        let mut data = vec![0u8; 100];
        for x in 5..10 {
            for y in 0..10 {
                data[y * 10 + x] = 255;
            }
        }
        let src = Matrix::from_vec(10, 10, 1, data);

        // Sobel dx=1, dy=0 should detect the vertical edge (x direction derivative)
        // With ksize=3, scale=1.0, delta=0.0
        let _res = sobel(&src, 1, 0, 3, 1.0, 0.0, BorderTypes::Reflect101).unwrap();

        // At the edge (x=4 to x=5), the derivative should be high.
        // Neighbors: x=4 (0), x=6 (255) -> 255 - 0 = 255.
        // Sobel dx=1: [-1, 0, 1] smoothed by [1, 2, 1] vertically.
        // Total weight is 4. Result should be around 255 * 4 = 1020,
        // but it's cast back to u8 if T is u8.
        // Let's use f32 to avoid overflow for testing.

        let src_f32: Matrix<f32> =
            Matrix::from_vec(10, 10, 1, src.data.iter().map(|&v| v as f32).collect());
        let res_f32 = sobel(&src_f32, 1, 0, 3, 1.0, 0.0, BorderTypes::Reflect101).unwrap();

        let edge_val = *res_f32.at(5, 5, 0).unwrap();
        assert!(edge_val > 500.0); // 255 * 4 = 1020 expected for Sobel ksize=3
    }

    #[test]
    fn test_scharr() {
        let mut data = vec![0u8; 100];
        for x in 5..10 {
            for y in 0..10 {
                data[y * 10 + x] = 255;
            }
        }
        let src = Matrix::<f32>::from_vec(10, 10, 1, data.iter().map(|&v| v as f32).collect());

        let res = scharr(&src, 1, 0, 1.0, 0.0, BorderTypes::Reflect101).unwrap();
        let edge_val = *res.at(5, 5, 0).unwrap();
        // Scharr weight for center row is 10, total 3+10+3 = 16.
        // Expected: 255 * 16 = 4080
        assert!(edge_val > 2000.0);
    }

    #[test]
    fn test_laplacian() {
        // Uniform image
        let src = Matrix::<f32>::from_vec(5, 5, 1, vec![100.0; 25]);
        let res = laplacian(&src, 1, 1.0, 0.0, BorderTypes::Reflect101).unwrap();

        // Laplacian of a uniform field should be 0
        for &val in &res.data {
            assert!(val.abs() < 1e-5);
        }

        // Image with a peak at (2, 2)
        let mut src_peak = Matrix::<f64>::new(5, 5, 1);
        src_peak.set(2, 2, 0, 255.0);
        let res_peak = laplacian(&src_peak, 1, 1.0, 0.0, BorderTypes::Reflect101).unwrap();
        // Laplacian [0, 1, 0; 1, -4, 1; 0, 1, 0] * 255 = [..., -4*255, ...] = -1020
        assert!(((*res_peak.at(2, 2, 0).unwrap() + 1020.0f64).abs()) < 1e-5);
    }

    #[test]
    fn test_canny() {
        let mut data = vec![0u8; 100];
        for x in 4..7 {
            for y in 0..10 {
                data[y * 10 + x] = 255;
            }
        }
        let src = Matrix::from_vec(10, 10, 1, data);

        // Edge should be at x=4 and x=7
        let edges = canny(&src, 50.0, 150.0, 3, false).unwrap();

        assert_eq!(*edges.at(5, 4, 0).unwrap(), 255);
        assert_eq!(*edges.at(5, 7, 0).unwrap(), 255);
        assert_eq!(*edges.at(5, 0, 0).unwrap(), 0);
    }

    #[test]
    fn test_cvt_color() {
        let mut data = vec![0u8; 12];
        // 2x2 RGB image. R,G,B
        data[0] = 255; // Red
        data[4] = 255; // Green
        data[8] = 255; // Blue
        let rgb_src = Matrix::from_vec(2, 2, 3, data);

        let gray = cvt_color(&rgb_src, ColorConversionCode::COLOR_RGB2GRAY).unwrap();

        // Allow ±1 tolerance: SIMD fixed-point (77/150/29) and scalar float
        // (0.299/0.587/0.114) differ by at most 1 LSB.
        assert!(
            (*gray.at(0, 0, 0).unwrap() as i16 - 76).abs() <= 1,
            "Red expected ~76, got {}",
            *gray.at(0, 0, 0).unwrap()
        );
        assert!(
            (*gray.at(0, 1, 0).unwrap() as i16 - 150).abs() <= 1,
            "Green expected ~150, got {}",
            *gray.at(0, 1, 0).unwrap()
        );
        assert!(
            (*gray.at(1, 0, 0).unwrap() as i16 - 29).abs() <= 1,
            "Blue expected ~29, got {}",
            *gray.at(1, 0, 0).unwrap()
        );
        assert_eq!(*gray.at(1, 1, 0).unwrap(), 0);

        let mut bgr_data = vec![0u8; 12];
        bgr_data[0] = 255; // Blue
        bgr_data[4] = 255; // Green
        bgr_data[8] = 255; // Red
        let bgr_src = Matrix::from_vec(2, 2, 3, bgr_data);

        let gray_bgr = cvt_color(&bgr_src, ColorConversionCode::COLOR_BGR2GRAY).unwrap();
        assert!(
            (*gray_bgr.at(0, 0, 0).unwrap() as i16 - 29).abs() <= 1,
            "Blue expected ~29, got {}",
            *gray_bgr.at(0, 0, 0).unwrap()
        );
        assert!(
            (*gray_bgr.at(0, 1, 0).unwrap() as i16 - 150).abs() <= 1,
            "Green expected ~150, got {}",
            *gray_bgr.at(0, 1, 0).unwrap()
        );
        assert!(
            (*gray_bgr.at(1, 0, 0).unwrap() as i16 - 76).abs() <= 1,
            "Red expected ~76, got {}",
            *gray_bgr.at(1, 0, 0).unwrap()
        );
        assert_eq!(*gray_bgr.at(1, 1, 0).unwrap(), 0);
    }

    #[test]
    fn test_threshold() {
        let data = vec![10u8, 50, 100, 150, 200, 250];
        let src = Matrix::from_vec(1, 6, 1, data);

        // Binary threshold at 127
        let (_, res) = threshold(&src, 127.0, 255.0, ThresholdTypes::THRESH_BINARY).unwrap();
        assert_eq!(res.data, vec![0, 0, 0, 255, 255, 255]);

        // Binary Inv threshold at 127
        let (_, res_inv) =
            threshold(&src, 127.0, 255.0, ThresholdTypes::THRESH_BINARY_INV).unwrap();
        assert_eq!(res_inv.data, vec![255, 255, 255, 0, 0, 0]);

        // Truncate at 127
        let (_, res_trunc) = threshold(&src, 127.0, 255.0, ThresholdTypes::THRESH_TRUNC).unwrap();
        assert_eq!(res_trunc.data, vec![10, 50, 100, 127, 127, 127]);

        // ToZero at 127
        let (_, res_zero) = threshold(&src, 127.0, 255.0, ThresholdTypes::THRESH_TOZERO).unwrap();
        assert_eq!(res_zero.data, vec![0, 0, 0, 150, 200, 250]);

        // ToZero Inv at 127
        let (_, res_zero_inv) =
            threshold(&src, 127.0, 255.0, ThresholdTypes::THRESH_TOZERO_INV).unwrap();
        assert_eq!(res_zero_inv.data, vec![10, 50, 100, 0, 0, 0]);
    }

    // -------------------------------------------------------------------
    //  Color conversion: larger-image equivalence tests
    // -------------------------------------------------------------------

    #[test]
    fn test_cvt_color_rgb_to_gray_large() {
        // 64×64 RGB image with gradient pattern
        let rows = 64;
        let cols = 64;
        let mut data = vec![0u8; rows * cols * 3];
        for i in 0..rows * cols {
            data[i * 3] = (i % 256) as u8; // R
            data[i * 3 + 1] = ((i * 3) % 256) as u8; // G
            data[i * 3 + 2] = ((i * 7) % 256) as u8; // B
        }
        let src = Matrix::from_vec(rows, cols, 3, data.clone());
        let gray = cvt_color(&src, ColorConversionCode::COLOR_RGB2GRAY).unwrap();

        assert_eq!(gray.rows, rows);
        assert_eq!(gray.cols, cols);
        assert_eq!(gray.channels, 1);

        // Verify every pixel is within ±1 of the float formula
        for i in 0..rows * cols {
            let r = data[i * 3] as f32;
            let g = data[i * 3 + 1] as f32;
            let b = data[i * 3 + 2] as f32;
            let expected = (0.299 * r + 0.587 * g + 0.114 * b).round() as i16;
            let actual = gray.data[i] as i16;
            assert!(
                (expected - actual).abs() <= 1,
                "Pixel {i}: expected ~{expected}, got {actual}"
            );
        }
    }

    #[test]
    fn test_cvt_color_bgr_to_gray_large() {
        let rows = 64;
        let cols = 64;
        let mut data = vec![0u8; rows * cols * 3];
        for i in 0..rows * cols {
            data[i * 3] = ((i * 7) % 256) as u8; // B
            data[i * 3 + 1] = ((i * 3) % 256) as u8; // G
            data[i * 3 + 2] = (i % 256) as u8; // R
        }
        let src = Matrix::from_vec(rows, cols, 3, data.clone());
        let gray = cvt_color(&src, ColorConversionCode::COLOR_BGR2GRAY).unwrap();

        for i in 0..rows * cols {
            let b = data[i * 3] as f32;
            let g = data[i * 3 + 1] as f32;
            let r = data[i * 3 + 2] as f32;
            let expected = (0.299 * r + 0.587 * g + 0.114 * b).round() as i16;
            let actual = gray.data[i] as i16;
            assert!(
                (expected - actual).abs() <= 1,
                "Pixel {i}: expected ~{expected}, got {actual}"
            );
        }
    }

    #[test]
    fn test_cvt_color_rgba_to_gray_large() {
        let rows = 32;
        let cols = 32;
        let mut data = vec![0u8; rows * cols * 4];
        for i in 0..rows * cols {
            data[i * 4] = (i % 256) as u8; // R
            data[i * 4 + 1] = ((i * 3) % 256) as u8; // G
            data[i * 4 + 2] = ((i * 7) % 256) as u8; // B
            data[i * 4 + 3] = 255; // A
        }
        let src = Matrix::from_vec(rows, cols, 4, data.clone());
        let gray = cvt_color(&src, ColorConversionCode::COLOR_RGBA2GRAY).unwrap();

        for i in 0..rows * cols {
            let r = data[i * 4] as f32;
            let g = data[i * 4 + 1] as f32;
            let b = data[i * 4 + 2] as f32;
            let expected = (0.299 * r + 0.587 * g + 0.114 * b).round() as i16;
            let actual = gray.data[i] as i16;
            assert!(
                (expected - actual).abs() <= 1,
                "Pixel {i}: expected ~{expected}, got {actual}"
            );
        }
    }

    // -------------------------------------------------------------------
    //  Threshold: all types equivalence tests
    // -------------------------------------------------------------------

    #[test]
    fn test_threshold_all_types_u8() {
        // Larger input to exercise SIMD paths
        let data: Vec<u8> = (0..256).map(|i| i as u8).collect();
        let src = Matrix::from_vec(1, 256, 1, data);

        // BINARY
        let (_, res) = threshold(&src, 127.0, 200.0, ThresholdTypes::THRESH_BINARY).unwrap();
        for i in 0..256 {
            let expected: u8 = if (i as u8) > 127 { 200 } else { 0 };
            assert_eq!(res.data[i], expected, "BINARY mismatch at {i}");
        }

        // BINARY_INV
        let (_, res) = threshold(&src, 127.0, 200.0, ThresholdTypes::THRESH_BINARY_INV).unwrap();
        for i in 0..256 {
            let expected: u8 = if (i as u8) > 127 { 0 } else { 200 };
            assert_eq!(res.data[i], expected, "BINARY_INV mismatch at {i}");
        }

        // TRUNC
        let (_, res) = threshold(&src, 127.0, 200.0, ThresholdTypes::THRESH_TRUNC).unwrap();
        for i in 0..256 {
            let expected: u8 = if (i as u8) > 127 { 127 } else { i as u8 };
            assert_eq!(res.data[i], expected, "TRUNC mismatch at {i}");
        }

        // TOZERO
        let (_, res) = threshold(&src, 127.0, 200.0, ThresholdTypes::THRESH_TOZERO).unwrap();
        for i in 0..256 {
            let expected: u8 = if (i as u8) > 127 { i as u8 } else { 0 };
            assert_eq!(res.data[i], expected, "TOZERO mismatch at {i}");
        }

        // TOZERO_INV
        let (_, res) = threshold(&src, 127.0, 200.0, ThresholdTypes::THRESH_TOZERO_INV).unwrap();
        for i in 0..256 {
            let expected: u8 = if (i as u8) > 127 { 0 } else { i as u8 };
            assert_eq!(res.data[i], expected, "TOZERO_INV mismatch at {i}");
        }
    }

    #[test]
    fn test_threshold_f32() {
        let data: Vec<f32> = (0..100).map(|i| i as f32 * 0.01).collect();
        let src = Matrix::from_vec(1, 100, 1, data);

        let (_, res) = threshold(&src, 0.5, 1.0, ThresholdTypes::THRESH_BINARY).unwrap();
        for i in 0..100 {
            let val = i as f32 * 0.01;
            let expected: f32 = if val > 0.5 { 1.0 } else { 0.0 };
            assert!(
                (res.data[i] - expected).abs() < 1e-5,
                "f32 BINARY mismatch at {i}: expected {expected}, got {}",
                res.data[i]
            );
        }
    }
}