scirs2-vision 0.5.1

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
//! Octree-based color quantization
//!
//! This module implements octree color quantization, an efficient algorithm
//! for reducing the number of colors in an image while maintaining quality.

use crate::error::Result;
use image::{DynamicImage, Rgb, RgbImage};
use std::collections::VecDeque;

/// Octree node for color quantization
#[derive(Debug)]
struct OctreeNode {
    /// Sum of red values
    red_sum: u64,
    /// Sum of green values
    green_sum: u64,
    /// Sum of blue values
    blue_sum: u64,
    /// Number of pixels represented
    pixel_count: u64,
    /// Child nodes (8 for octree)
    children: [Option<Box<OctreeNode>>; 8],
    /// Whether this is a leaf node
    is_leaf: bool,
    /// Node level in the tree (0-7)
    level: u8,
}

impl OctreeNode {
    /// Create a new octree node
    fn new(level: u8) -> Self {
        Self {
            red_sum: 0,
            green_sum: 0,
            blue_sum: 0,
            pixel_count: 0,
            children: Default::default(),
            is_leaf: level == 7,
            level,
        }
    }

    /// Add a color to this node
    fn add_color(&mut self, r: u8, g: u8, b: u8, level: u8) {
        if self.is_leaf {
            self.red_sum += r as u64;
            self.green_sum += g as u64;
            self.blue_sum += b as u64;
            self.pixel_count += 1;
        } else {
            // Determine which child to add to
            let index = Self::get_child_index(r, g, b, level);

            if self.children[index].is_none() {
                self.children[index] = Some(Box::new(OctreeNode::new(level + 1)));
            }

            self.children[index]
                .as_mut()
                .expect("Operation failed")
                .add_color(r, g, b, level + 1);

            // Update this node's sums
            self.red_sum += r as u64;
            self.green_sum += g as u64;
            self.blue_sum += b as u64;
            self.pixel_count += 1;
        }
    }

    /// Get the child index for a color at a given level
    fn get_child_index(r: u8, g: u8, b: u8, level: u8) -> usize {
        let shift = 7 - level;
        let r_bit = ((r >> shift) & 1) as usize;
        let g_bit = ((g >> shift) & 1) as usize;
        let b_bit = ((b >> shift) & 1) as usize;

        (r_bit << 2) | (g_bit << 1) | b_bit
    }

    /// Count leaf nodes
    fn count_leaves(&self) -> usize {
        if self.is_leaf {
            1
        } else {
            self.children
                .iter()
                .filter_map(|child| child.as_ref())
                .map(|child| child.count_leaves())
                .sum()
        }
    }

    /// Get the average color for this node
    fn get_color(&self) -> [u8; 3] {
        [
            (self.red_sum.checked_div(self.pixel_count).unwrap_or(0)) as u8,
            (self.green_sum.checked_div(self.pixel_count).unwrap_or(0)) as u8,
            (self.blue_sum.checked_div(self.pixel_count).unwrap_or(0)) as u8,
        ]
    }

    /// Find the nearest color in the tree
    fn find_nearest_color(&self, r: u8, g: u8, b: u8, level: u8) -> [u8; 3] {
        if self.is_leaf || level == 7 {
            self.get_color()
        } else {
            let index = Self::get_child_index(r, g, b, level);

            if let Some(child) = &self.children[index] {
                child.find_nearest_color(r, g, b, level + 1)
            } else {
                // No exact child, find the nearest one
                let mut best_color = self.get_color();
                let mut best_distance = u32::MAX;

                for child in self.children.iter().flatten() {
                    let color = child.get_color();
                    let distance = color_distance_squared(r, g, b, color[0], color[1], color[2]);

                    if distance < best_distance {
                        best_distance = distance;
                        best_color = color;
                    }
                }

                best_color
            }
        }
    }

    /// Merge this node into a leaf (reduce colors)
    fn merge_to_leaf(&mut self) {
        if !self.is_leaf {
            self.is_leaf = true;
            self.children = Default::default();
        }
    }

    /// Get all nodes at a specific level
    fn get_nodes_at_level(&mut self, targetlevel: u8) -> Vec<*mut OctreeNode> {
        let mut nodes = Vec::new();

        if self.level == targetlevel && !self.is_leaf {
            nodes.push(self as *mut OctreeNode);
        }

        for child in self.children.iter_mut().flatten() {
            nodes.extend(child.get_nodes_at_level(targetlevel));
        }

        nodes
    }
}

/// Octree color quantizer
pub struct OctreeQuantizer {
    root: OctreeNode,
    _maxcolors: usize,
}

impl OctreeQuantizer {
    /// Create a new octree quantizer
    ///
    /// # Arguments
    ///
    /// * `_maxcolors` - Maximum number of colors in the palette
    pub fn new(_maxcolors: usize) -> Self {
        Self {
            root: OctreeNode::new(0),
            _maxcolors,
        }
    }

    /// Add a color to the octree
    pub fn add_color(&mut self, r: u8, g: u8, b: u8) {
        self.root.add_color(r, g, b, 0);
    }

    /// Reduce the number of colors by merging nodes
    pub fn reduce_colors(&mut self) {
        while self.root.count_leaves() > self._maxcolors {
            // Find the deepest level with nodes
            for level in (0..7).rev() {
                let nodes = unsafe {
                    self.root
                        .get_nodes_at_level(level)
                        .into_iter()
                        .map(|ptr| &mut *ptr)
                        .collect::<Vec<_>>()
                };

                if !nodes.is_empty() {
                    // Merge the node with the least pixels
                    let min_node = nodes
                        .into_iter()
                        .min_by_key(|node| node.pixel_count)
                        .expect("Operation failed");

                    min_node.merge_to_leaf();
                    break;
                }
            }
        }
    }

    /// Find the nearest color in the palette
    pub fn find_nearest_color(&self, r: u8, g: u8, b: u8) -> [u8; 3] {
        self.root.find_nearest_color(r, g, b, 0)
    }

    /// Get all colors in the palette
    pub fn get_palette(&self) -> Vec<[u8; 3]> {
        let mut palette = Vec::new();
        let mut queue = VecDeque::new();
        queue.push_back(&self.root);

        while let Some(node) = queue.pop_front() {
            if node.is_leaf && node.pixel_count > 0 {
                palette.push(node.get_color());
            } else {
                for child in node.children.iter().flatten() {
                    queue.push_back(child);
                }
            }
        }

        palette
    }
}

/// Calculate squared distance between two colors
#[allow(dead_code)]
fn color_distance_squared(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> u32 {
    let dr = r1 as i32 - r2 as i32;
    let dg = g1 as i32 - g2 as i32;
    let db = b1 as i32 - b2 as i32;

    (dr * dr + dg * dg + db * db) as u32
}

/// Perform octree color quantization on an image
///
/// # Arguments
///
/// * `img` - Input image
/// * `_maxcolors` - Maximum number of colors in the output
///
/// # Returns
///
/// * Result containing the quantized image
///
/// # Example
///
/// ```rust
/// use scirs2_vision::color::octree_quantize;
/// use image::{DynamicImage, RgbImage, Rgb};
///
/// // Create a simple test image
/// let mut img = RgbImage::new(4, 4);
/// for x in 0..4 {
///     for y in 0..4 {
///         let r = (x * 64) as u8;
///         let g = (y * 64) as u8;
///         let b = ((x + y) * 32) as u8;
///         img.put_pixel(x, y, Rgb([r, g, b]));
///     }
/// }
///
/// let dynamic_img = DynamicImage::ImageRgb8(img);
/// let quantized = octree_quantize(&dynamic_img, 8).expect("Operation failed");
/// assert_eq!(quantized.width(), 4);
/// assert_eq!(quantized.height(), 4);
/// ```
#[allow(dead_code)]
pub fn octree_quantize(img: &DynamicImage, maxcolors: usize) -> Result<DynamicImage> {
    let rgb = img.to_rgb8();
    let (width, height) = rgb.dimensions();

    // Build the octree
    let mut quantizer = OctreeQuantizer::new(maxcolors);

    for pixel in rgb.pixels() {
        quantizer.add_color(pixel[0], pixel[1], pixel[2]);
    }

    // Reduce _colors
    quantizer.reduce_colors();

    // Create quantized image
    let mut result = RgbImage::new(width, height);

    for (x, y, pixel) in rgb.enumerate_pixels() {
        let quantized_color = quantizer.find_nearest_color(pixel[0], pixel[1], pixel[2]);
        result.put_pixel(x, y, Rgb(quantized_color));
    }

    Ok(DynamicImage::ImageRgb8(result))
}

/// Adaptive octree quantization with importance weighting
///
/// # Arguments
///
/// * `img` - Input image
/// * `_maxcolors` - Maximum number of colors
/// * `importance_map` - Optional importance map (same size as image)
///
/// # Returns
///
/// * Result containing the quantized image
#[allow(dead_code)]
pub fn adaptive_octree_quantize(
    img: &DynamicImage,
    maxcolors: usize,
    importance_map: Option<&DynamicImage>,
) -> Result<DynamicImage> {
    let rgb = img.to_rgb8();
    let (width, height) = rgb.dimensions();

    // Get importance weights
    let weights = if let Some(map) = importance_map {
        let gray_map = map.to_luma8();
        gray_map
            .pixels()
            .map(|p| p[0] as f32 / 255.0)
            .collect::<Vec<_>>()
    } else {
        vec![1.0; (width * height) as usize]
    };

    // Build weighted octree
    let mut quantizer = OctreeQuantizer::new(maxcolors);

    for (idx, pixel) in rgb.pixels().enumerate() {
        let weight = (weights[idx] * 10.0).max(1.0) as usize;

        // Add color multiple times based on importance
        for _ in 0..weight {
            quantizer.add_color(pixel[0], pixel[1], pixel[2]);
        }
    }

    // Reduce _colors
    quantizer.reduce_colors();

    // Create quantized image
    let mut result = RgbImage::new(width, height);

    for (x, y, pixel) in rgb.enumerate_pixels() {
        let quantized_color = quantizer.find_nearest_color(pixel[0], pixel[1], pixel[2]);
        result.put_pixel(x, y, Rgb(quantized_color));
    }

    Ok(DynamicImage::ImageRgb8(result))
}

/// Generate a color palette from an image using octree
///
/// # Arguments
///
/// * `img` - Input image
/// * `palettesize` - Number of colors in the palette
///
/// # Returns
///
/// * Vector of RGB colors
#[allow(dead_code)]
pub fn extract_palette(img: &DynamicImage, palettesize: usize) -> Vec<[u8; 3]> {
    let rgb = img.to_rgb8();

    let mut quantizer = OctreeQuantizer::new(palettesize);

    for pixel in rgb.pixels() {
        quantizer.add_color(pixel[0], pixel[1], pixel[2]);
    }

    quantizer.reduce_colors();
    quantizer.get_palette()
}

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

    #[test]
    fn test_octree_node_basic() {
        let mut node = OctreeNode::new(0);
        node.add_color(255, 0, 0, 0);
        node.add_color(0, 255, 0, 0);

        assert!(node.count_leaves() > 0);
    }

    #[test]
    fn test_octree_quantize() {
        let img = DynamicImage::new_rgb8(10, 10);
        let result = octree_quantize(&img, 16);
        assert!(result.is_ok());

        let quantized = result.expect("Operation failed");
        assert_eq!(quantized.width(), 10);
        assert_eq!(quantized.height(), 10);
    }

    #[test]
    fn test_extract_palette() {
        let mut img = RgbImage::new(2, 2);
        img.put_pixel(0, 0, Rgb([255, 0, 0]));
        img.put_pixel(1, 0, Rgb([0, 255, 0]));
        img.put_pixel(0, 1, Rgb([0, 0, 255]));
        img.put_pixel(1, 1, Rgb([255, 255, 255]));

        let palette = extract_palette(&DynamicImage::ImageRgb8(img), 4);
        assert!(palette.len() <= 4);
        assert!(!palette.is_empty());
    }

    #[test]
    fn test_child_index() {
        assert_eq!(OctreeNode::get_child_index(255, 255, 255, 0), 7);
        assert_eq!(OctreeNode::get_child_index(0, 0, 0, 0), 0);
        assert_eq!(OctreeNode::get_child_index(128, 128, 128, 0), 7);
    }
}