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
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
/*
 *  color.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(feature = "parallel")]
use rayon::prelude::*;

#[cfg(feature = "simd")]
use crate::core::simd::{
    simd_bgr_to_gray_u8, simd_bgra_to_gray_u8, simd_rgb_to_gray_u8, simd_rgba_to_gray_u8,
};

// Assuming the Matrix<T> struct is in scope
use crate::core::Matrix;

// ---------------------------------------------------------------------------
//  Row-level kernels — SIMD or scalar depending on feature flags
// ---------------------------------------------------------------------------

/// Process one row of RGB→gray conversion.
#[inline(always)]
fn rgb_to_gray_row(out_row: &mut [u8], in_row: &[u8]) {
    #[cfg(feature = "simd")]
    {
        simd_rgb_to_gray_u8(out_row, in_row);
    }
    #[cfg(not(feature = "simd"))]
    {
        for (out_pixel, in_val) in out_row.iter_mut().zip(in_row.chunks_exact(3)) {
            let r = in_val[0] as f32;
            let g = in_val[1] as f32;
            let b = in_val[2] as f32;
            *out_pixel = (0.299 * r + 0.587 * g + 0.114 * b).round() as u8;
        }
    }
}

/// Process one row of BGR→gray conversion.
#[inline(always)]
fn bgr_to_gray_row(out_row: &mut [u8], in_row: &[u8]) {
    #[cfg(feature = "simd")]
    {
        simd_bgr_to_gray_u8(out_row, in_row);
    }
    #[cfg(not(feature = "simd"))]
    {
        for (out_pixel, in_val) in out_row.iter_mut().zip(in_row.chunks_exact(3)) {
            let b = in_val[0] as f32;
            let g = in_val[1] as f32;
            let r = in_val[2] as f32;
            *out_pixel = (0.299 * r + 0.587 * g + 0.114 * b).round() as u8;
        }
    }
}

/// Process one row of RGBA→gray conversion (alpha ignored).
#[inline(always)]
fn rgba_to_gray_row(out_row: &mut [u8], in_row: &[u8]) {
    #[cfg(feature = "simd")]
    {
        simd_rgba_to_gray_u8(out_row, in_row);
    }
    #[cfg(not(feature = "simd"))]
    {
        for (out_pixel, in_val) in out_row.iter_mut().zip(in_row.chunks_exact(4)) {
            let r = in_val[0] as f32;
            let g = in_val[1] as f32;
            let b = in_val[2] as f32;
            *out_pixel = (0.299 * r + 0.587 * g + 0.114 * b).round() as u8;
        }
    }
}

/// Process one row of BGRA→gray conversion (alpha ignored).
#[inline(always)]
fn bgra_to_gray_row(out_row: &mut [u8], in_row: &[u8]) {
    #[cfg(feature = "simd")]
    {
        simd_bgra_to_gray_u8(out_row, in_row);
    }
    #[cfg(not(feature = "simd"))]
    {
        for (out_pixel, in_val) in out_row.iter_mut().zip(in_row.chunks_exact(4)) {
            let b = in_val[0] as f32;
            let g = in_val[1] as f32;
            let r = in_val[2] as f32;
            *out_pixel = (0.299 * r + 0.587 * g + 0.114 * b).round() as u8;
        }
    }
}

/// Color conversion codes for cvt_color.
/// Mimics OpenCV's cv::ColorConversionCodes.
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorConversionCode {
    /// Convert BGR to Grayscale
    COLOR_BGR2GRAY,
    /// Convert RGB to Grayscale
    COLOR_RGB2GRAY,
    /// Convert BGRA to Grayscale
    COLOR_BGRA2GRAY,
    /// Convert RGBA to Grayscale
    COLOR_RGBA2GRAY,
    /// Convert Grayscale to RGB
    COLOR_GRAY2RGB,
    /// Convert Grayscale to BGR
    COLOR_GRAY2BGR,
    /// Convert Grayscale to RGBA
    COLOR_GRAY2RGBA,
    /// Convert Grayscale to BGRA
    COLOR_GRAY2BGRA,
}

/// Converts an image from one color space to another.
///
/// This is the main wrapper function that mimics OpenCV's `cv::cvtColor`.
///
/// Returns a Result containing the new Matrix, or an Error if the input is invalid.
pub fn cvt_color(src: &Matrix<u8>, code: ColorConversionCode) -> Result<Matrix<u8>, &'static str> {
    match code {
        ColorConversionCode::COLOR_RGB2GRAY => cvt_color_rgb_to_gray(src),
        ColorConversionCode::COLOR_BGR2GRAY => cvt_color_bgr_to_gray(src),
        ColorConversionCode::COLOR_RGBA2GRAY => cvt_color_rgba_to_gray(src),
        ColorConversionCode::COLOR_BGRA2GRAY => cvt_color_bgra_to_gray(src),
        ColorConversionCode::COLOR_GRAY2RGB => cvt_color_gray_to_rgb(src),
        ColorConversionCode::COLOR_GRAY2BGR => cvt_color_gray_to_bgr(src),
        ColorConversionCode::COLOR_GRAY2RGBA => cvt_color_gray_to_rgba(src),
        ColorConversionCode::COLOR_GRAY2BGRA => cvt_color_gray_to_bgra(src),
    }
}

/// Converts an 8-bit RGB image to an 8-bit Grayscale image.\n/// Uses the standard luminosity formula: Y = 0.299*R + 0.587*G + 0.114*B
pub fn cvt_color_rgb_to_gray(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 3 {
        return Err("Input matrix must have exactly 3 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 1);
    let out_row_len = output.cols;
    let in_row_len = input.cols * 3;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                rgb_to_gray_row(out_row, in_row);
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                rgb_to_gray_row(out_row, in_row);
            });
    }

    Ok(output)
}

/// Converts an 8-bit BGR image to an 8-bit Grayscale image.\n/// Uses the standard luminosity formula: Y = 0.299*R + 0.587*G + 0.114*B
pub fn cvt_color_bgr_to_gray(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 3 {
        return Err("Input matrix must have exactly 3 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 1);
    let out_row_len = output.cols;
    let in_row_len = input.cols * 3;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                bgr_to_gray_row(out_row, in_row);
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                bgr_to_gray_row(out_row, in_row);
            });
    }

    Ok(output)
}

/// Converts an 8-bit RGBA image to an 8-bit Grayscale image.\n/// Uses the standard luminosity formula: Y = 0.299*R + 0.587*G + 0.114*B, ignores Alpha.
pub fn cvt_color_rgba_to_gray(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 4 {
        return Err("Input matrix must have exactly 4 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 1);
    let out_row_len = output.cols;
    let in_row_len = input.cols * 4;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                rgba_to_gray_row(out_row, in_row);
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                rgba_to_gray_row(out_row, in_row);
            });
    }

    Ok(output)
}

/// Converts an 8-bit BGRA image to an 8-bit Grayscale image.\n/// Uses the standard luminosity formula: Y = 0.299*R + 0.587*G + 0.114*B, ignores Alpha.
pub fn cvt_color_bgra_to_gray(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 4 {
        return Err("Input matrix must have exactly 4 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 1);
    let out_row_len = output.cols;
    let in_row_len = input.cols * 4;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                bgra_to_gray_row(out_row, in_row);
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                bgra_to_gray_row(out_row, in_row);
            });
    }

    Ok(output)
}

/// Converts an 8-bit Grayscale image to an 8-bit RGB image.
pub fn cvt_color_gray_to_rgb(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 1 {
        return Err("Input matrix must have exactly 1 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 3);
    let out_row_len = output.cols * 3;
    let in_row_len = input.cols;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(3).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                }
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(3).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                }
            });
    }

    Ok(output)
}

/// Converts an 8-bit Grayscale image to an 8-bit BGR image.
pub fn cvt_color_gray_to_bgr(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 1 {
        return Err("Input matrix must have exactly 1 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 3);
    let out_row_len = output.cols * 3;
    let in_row_len = input.cols;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(3).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                }
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(3).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                }
            });
    }

    Ok(output)
}

/// Converts an 8-bit Grayscale image to an 8-bit RGBA image.\n/// Alpha channel is set to 255 (fully opaque).
pub fn cvt_color_gray_to_rgba(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 1 {
        return Err("Input matrix must have exactly 1 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 4);
    let out_row_len = output.cols * 4;
    let in_row_len = input.cols;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(4).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                    out_val[3] = 255;
                }
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(4).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                    out_val[3] = 255;
                }
            });
    }

    Ok(output)
}

/// Converts an 8-bit Grayscale image to an 8-bit BGRA image.\n/// Alpha channel is set to 255 (fully opaque).
pub fn cvt_color_gray_to_bgra(input: &Matrix<u8>) -> Result<Matrix<u8>, &'static str> {
    if input.channels != 1 {
        return Err("Input matrix must have exactly 1 channels");
    }

    let mut output = Matrix::<u8>::new(input.rows, input.cols, 4);
    let out_row_len = output.cols * 4;
    let in_row_len = input.cols;

    #[cfg(feature = "parallel")]
    {
        output
            .data
            .par_chunks_exact_mut(out_row_len)
            .zip(input.data.par_chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(4).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                    out_val[3] = 255;
                }
            });
    }

    #[cfg(not(feature = "parallel"))]
    {
        output
            .data
            .chunks_exact_mut(out_row_len)
            .zip(input.data.chunks_exact(in_row_len))
            .for_each(|(out_row, in_row)| {
                for (out_val, in_pixel) in out_row.chunks_exact_mut(4).zip(in_row.iter()) {
                    let v = *in_pixel;
                    out_val[0] = v;
                    out_val[1] = v;
                    out_val[2] = v;
                    out_val[3] = 255;
                }
            });
    }

    Ok(output)
}