oximedia-cv 0.1.8

Computer vision for OxiMedia
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Hybrid scaling approaches combining multiple techniques.
//!
//! This module provides hybrid scaling methods that combine seam carving
//! with traditional scaling, cropping, and other techniques for better
//! visual results.

use super::energy::EnergyFunction;
use super::seam_carving::SeamCarver;
use crate::error::{CvError, CvResult};
use crate::image::resize::{resize_image, ResizeConfig, ResizeMethod};

/// Hybrid scaling strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HybridStrategy {
    /// Use only seam carving.
    SeamCarvingOnly,
    /// Use only traditional scaling.
    TraditionalOnly,
    /// Seam carve small changes, traditional scale large changes.
    Adaptive,
    /// Crop to target aspect ratio, then traditional scale.
    CropAndScale,
    /// Seam carve to intermediate size, then traditional scale.
    SeamThenScale,
    /// Traditional scale, then seam carve for final adjustment.
    ScaleThenSeam,
    /// Multi-operator approach (tries multiple strategies and picks best).
    MultiOperator,
}

/// Configuration for hybrid scaling.
#[derive(Debug, Clone)]
pub struct HybridConfig {
    /// Scaling strategy to use.
    pub strategy: HybridStrategy,
    /// Energy function for seam carving.
    pub energy_function: EnergyFunction,
    /// Traditional scaling method.
    pub resize_method: ResizeMethod,
    /// Threshold for adaptive strategy (fraction of dimension).
    pub adaptive_threshold: f64,
    /// Whether to preserve aspect ratio.
    pub preserve_aspect_ratio: bool,
}

impl Default for HybridConfig {
    fn default() -> Self {
        Self {
            strategy: HybridStrategy::Adaptive,
            energy_function: EnergyFunction::Gradient,
            resize_method: ResizeMethod::Bilinear,
            adaptive_threshold: 0.2,
            preserve_aspect_ratio: false,
        }
    }
}

impl HybridConfig {
    /// Create a new hybrid configuration.
    #[must_use]
    pub fn new(strategy: HybridStrategy) -> Self {
        Self {
            strategy,
            ..Default::default()
        }
    }

    /// Set energy function.
    #[must_use]
    pub const fn with_energy_function(mut self, energy_function: EnergyFunction) -> Self {
        self.energy_function = energy_function;
        self
    }

    /// Set resize method.
    #[must_use]
    pub const fn with_resize_method(mut self, resize_method: ResizeMethod) -> Self {
        self.resize_method = resize_method;
        self
    }

    /// Set adaptive threshold.
    #[must_use]
    pub const fn with_adaptive_threshold(mut self, threshold: f64) -> Self {
        self.adaptive_threshold = threshold;
        self
    }

    /// Set whether to preserve aspect ratio.
    #[must_use]
    pub const fn with_preserve_aspect_ratio(mut self, preserve: bool) -> Self {
        self.preserve_aspect_ratio = preserve;
        self
    }
}

/// Hybrid scaler combining multiple techniques.
#[derive(Debug, Clone)]
pub struct HybridScaler {
    config: HybridConfig,
    seam_carver: SeamCarver,
}

impl HybridScaler {
    /// Create a new hybrid scaler.
    #[must_use]
    pub fn new(config: HybridConfig) -> Self {
        let seam_carver = SeamCarver::new(config.energy_function);
        Self {
            config,
            seam_carver,
        }
    }

    /// Resize a grayscale image.
    ///
    /// # Arguments
    ///
    /// * `image` - Input grayscale image
    /// * `src_width` - Source width
    /// * `src_height` - Source height
    /// * `dst_width` - Target width
    /// * `dst_height` - Target height
    ///
    /// # Returns
    ///
    /// Resized image.
    pub fn resize(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        if src_width == 0 || src_height == 0 {
            return Err(CvError::invalid_dimensions(src_width, src_height));
        }
        if dst_width == 0 || dst_height == 0 {
            return Err(CvError::invalid_dimensions(dst_width, dst_height));
        }

        // Handle no-op case
        if src_width == dst_width && src_height == dst_height {
            return Ok(image.to_vec());
        }

        match self.config.strategy {
            HybridStrategy::SeamCarvingOnly => {
                self.resize_seam_only(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::TraditionalOnly => {
                self.resize_traditional(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::Adaptive => {
                self.resize_adaptive(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::CropAndScale => {
                self.resize_crop_and_scale(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::SeamThenScale => {
                self.resize_seam_then_scale(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::ScaleThenSeam => {
                self.resize_scale_then_seam(image, src_width, src_height, dst_width, dst_height)
            }
            HybridStrategy::MultiOperator => {
                self.resize_multi_operator(image, src_width, src_height, dst_width, dst_height)
            }
        }
    }

    /// Resize using only seam carving.
    fn resize_seam_only(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        let mut result = image.to_vec();
        let mut current_width = src_width;
        let mut current_height = src_height;

        // Resize width
        if dst_width < src_width {
            result =
                self.seam_carver
                    .reduce_width(&result, current_width, current_height, dst_width)?;
            current_width = dst_width;
        } else if dst_width > src_width {
            result = self.seam_carver.enlarge_width(
                &result,
                current_width,
                current_height,
                dst_width,
            )?;
            current_width = dst_width;
        }

        // Resize height
        if dst_height < current_height {
            result = self.seam_carver.reduce_height(
                &result,
                current_width,
                current_height,
                dst_height,
            )?;
        } else if dst_height > current_height {
            // For height enlargement, we need to implement it
            // For now, fall back to traditional scaling
            let config = ResizeConfig::new(current_width, dst_height, self.config.resize_method, 1);
            result = resize_image(&result, current_width, current_height, &config)?;
        }

        Ok(result)
    }

    /// Resize using only traditional scaling.
    fn resize_traditional(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        let config = ResizeConfig::new(dst_width, dst_height, self.config.resize_method, 1);
        resize_image(image, src_width, src_height, &config)
    }

    /// Adaptive strategy: choose method based on size change.
    fn resize_adaptive(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        let width_change = (dst_width as f64 - src_width as f64).abs() / src_width as f64;
        let height_change = (dst_height as f64 - src_height as f64).abs() / src_height as f64;

        // If change is small, use seam carving
        if width_change < self.config.adaptive_threshold
            && height_change < self.config.adaptive_threshold
        {
            self.resize_seam_only(image, src_width, src_height, dst_width, dst_height)
        } else if width_change < self.config.adaptive_threshold {
            // Small width change, use seam + scale
            self.resize_seam_then_scale(image, src_width, src_height, dst_width, dst_height)
        } else if height_change < self.config.adaptive_threshold {
            // Small height change, use seam + scale
            self.resize_seam_then_scale(image, src_width, src_height, dst_width, dst_height)
        } else {
            // Large change, use traditional
            self.resize_traditional(image, src_width, src_height, dst_width, dst_height)
        }
    }

    /// Crop to aspect ratio, then scale.
    fn resize_crop_and_scale(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        let src_aspect = src_width as f64 / src_height as f64;
        let dst_aspect = dst_width as f64 / dst_height as f64;

        let (crop_width, crop_height) = if src_aspect > dst_aspect {
            // Source is wider, crop width
            let new_width = (src_height as f64 * dst_aspect).round() as u32;
            (new_width, src_height)
        } else {
            // Source is taller, crop height
            let new_height = (src_width as f64 / dst_aspect).round() as u32;
            (src_width, new_height)
        };

        // Crop from center
        let crop_x = (src_width - crop_width) / 2;
        let crop_y = (src_height - crop_height) / 2;

        let cropped = crop_image(
            image,
            src_width,
            src_height,
            crop_x,
            crop_y,
            crop_width,
            crop_height,
        )?;

        // Scale to final size
        let config = ResizeConfig::new(dst_width, dst_height, self.config.resize_method, 1);
        resize_image(&cropped, crop_width, crop_height, &config)
    }

    /// Seam carve to intermediate size, then traditional scale.
    fn resize_seam_then_scale(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        // Calculate intermediate size (50% of the change via seam carving)
        let width_diff = dst_width as i32 - src_width as i32;
        let height_diff = dst_height as i32 - src_height as i32;

        let mid_width = if width_diff != 0 {
            (src_width as i32 + width_diff / 2).max(1) as u32
        } else {
            src_width
        };

        let mid_height = if height_diff != 0 {
            (src_height as i32 + height_diff / 2).max(1) as u32
        } else {
            src_height
        };

        // Seam carve to intermediate size
        let intermediate =
            self.resize_seam_only(image, src_width, src_height, mid_width, mid_height)?;

        // Traditional scale to final size
        let config = ResizeConfig::new(dst_width, dst_height, self.config.resize_method, 1);
        resize_image(&intermediate, mid_width, mid_height, &config)
    }

    /// Traditional scale first, then seam carve for adjustment.
    fn resize_scale_then_seam(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        // Calculate intermediate size (traditional scale 80% of the way)
        let width_diff = dst_width as i32 - src_width as i32;
        let height_diff = dst_height as i32 - src_height as i32;

        let mid_width = (src_width as i32 + (width_diff * 8 / 10)).max(1) as u32;
        let mid_height = (src_height as i32 + (height_diff * 8 / 10)).max(1) as u32;

        // Traditional scale to intermediate
        let config = ResizeConfig::new(mid_width, mid_height, self.config.resize_method, 1);
        let intermediate = resize_image(image, src_width, src_height, &config)?;

        // Seam carve for final adjustment
        self.resize_seam_only(&intermediate, mid_width, mid_height, dst_width, dst_height)
    }

    /// Multi-operator approach: try multiple strategies and pick best.
    fn resize_multi_operator(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        // For now, use adaptive strategy
        // In a full implementation, we would try multiple strategies
        // and use a quality metric to pick the best result
        self.resize_adaptive(image, src_width, src_height, dst_width, dst_height)
    }

    /// Set protection mask for seam carving.
    pub fn set_protection_mask(&mut self, mask: Vec<u8>) {
        self.seam_carver.set_protection_mask(mask);
    }
}

/// Crop an image.
fn crop_image(
    image: &[u8],
    width: u32,
    height: u32,
    x: u32,
    y: u32,
    crop_width: u32,
    crop_height: u32,
) -> CvResult<Vec<u8>> {
    if x + crop_width > width || y + crop_height > height {
        return Err(CvError::invalid_roi(x, y, crop_width, crop_height));
    }

    let mut result = vec![0u8; crop_width as usize * crop_height as usize];

    for cy in 0..crop_height {
        let src_y = y + cy;
        let src_offset = src_y as usize * width as usize + x as usize;
        let dst_offset = cy as usize * crop_width as usize;

        result[dst_offset..dst_offset + crop_width as usize]
            .copy_from_slice(&image[src_offset..src_offset + crop_width as usize]);
    }

    Ok(result)
}

/// Multi-scale approach for large size changes.
///
/// Performs resizing in multiple steps to preserve quality.
#[derive(Debug)]
pub struct MultiScaleResizer {
    config: HybridConfig,
    max_scale_factor: f64,
}

impl MultiScaleResizer {
    /// Create a new multi-scale resizer.
    ///
    /// # Arguments
    ///
    /// * `config` - Hybrid configuration
    /// * `max_scale_factor` - Maximum scale factor per step
    #[must_use]
    pub const fn new(config: HybridConfig, max_scale_factor: f64) -> Self {
        Self {
            config,
            max_scale_factor,
        }
    }

    /// Resize image using multi-scale approach.
    pub fn resize(
        &self,
        image: &[u8],
        src_width: u32,
        src_height: u32,
        dst_width: u32,
        dst_height: u32,
    ) -> CvResult<Vec<u8>> {
        let width_ratio = dst_width as f64 / src_width as f64;
        let height_ratio = dst_height as f64 / src_height as f64;

        // Determine if we need multi-scale
        let needs_multiscale = width_ratio > self.max_scale_factor
            || width_ratio < 1.0 / self.max_scale_factor
            || height_ratio > self.max_scale_factor
            || height_ratio < 1.0 / self.max_scale_factor;

        if !needs_multiscale {
            // Single step is fine
            let scaler = HybridScaler::new(self.config.clone());
            return scaler.resize(image, src_width, src_height, dst_width, dst_height);
        }

        // Calculate steps
        let width_steps = calculate_steps(width_ratio, self.max_scale_factor);
        let height_steps = calculate_steps(height_ratio, self.max_scale_factor);
        let num_steps = width_steps.len().max(height_steps.len());

        let mut current_image = image.to_vec();
        let mut current_width = src_width;
        let mut current_height = src_height;

        for i in 0..num_steps {
            let target_width = if i < width_steps.len() {
                (src_width as f64 * width_steps[i]).round() as u32
            } else {
                dst_width
            };

            let target_height = if i < height_steps.len() {
                (src_height as f64 * height_steps[i]).round() as u32
            } else {
                dst_height
            };

            let scaler = HybridScaler::new(self.config.clone());
            current_image = scaler.resize(
                &current_image,
                current_width,
                current_height,
                target_width,
                target_height,
            )?;
            current_width = target_width;
            current_height = target_height;
        }

        Ok(current_image)
    }
}

/// Calculate intermediate steps for multi-scale resizing.
fn calculate_steps(ratio: f64, max_factor: f64) -> Vec<f64> {
    let mut steps = Vec::new();

    if ratio > 1.0 {
        // Upscaling
        let mut current = 1.0;
        while current * max_factor < ratio {
            current *= max_factor;
            steps.push(current);
        }
        steps.push(ratio);
    } else if ratio < 1.0 {
        // Downscaling
        let mut current = 1.0;
        while current / max_factor > ratio {
            current /= max_factor;
            steps.push(current);
        }
        steps.push(ratio);
    }

    steps
}

/// Aspect ratio preservation modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AspectMode {
    /// Stretch to fit (ignore aspect ratio).
    Stretch,
    /// Fit inside target (may have letterboxing).
    Fit,
    /// Fill target (may crop).
    Fill,
    /// Use content-aware scaling to adjust aspect ratio.
    ContentAware,
}

/// Resize with aspect ratio preservation.
pub fn resize_with_aspect_ratio(
    image: &[u8],
    src_width: u32,
    src_height: u32,
    dst_width: u32,
    dst_height: u32,
    mode: AspectMode,
    config: &HybridConfig,
) -> CvResult<Vec<u8>> {
    match mode {
        AspectMode::Stretch | AspectMode::ContentAware => {
            let scaler = HybridScaler::new(config.clone());
            scaler.resize(image, src_width, src_height, dst_width, dst_height)
        }
        AspectMode::Fit => resize_fit(image, src_width, src_height, dst_width, dst_height, config),
        AspectMode::Fill => {
            resize_fill(image, src_width, src_height, dst_width, dst_height, config)
        }
    }
}

/// Resize to fit inside target dimensions.
fn resize_fit(
    image: &[u8],
    src_width: u32,
    src_height: u32,
    dst_width: u32,
    dst_height: u32,
    config: &HybridConfig,
) -> CvResult<Vec<u8>> {
    let src_aspect = src_width as f64 / src_height as f64;
    let dst_aspect = dst_width as f64 / dst_height as f64;

    let (scale_width, scale_height) = if src_aspect > dst_aspect {
        // Fit to width
        (dst_width, (dst_width as f64 / src_aspect).round() as u32)
    } else {
        // Fit to height
        ((dst_height as f64 * src_aspect).round() as u32, dst_height)
    };

    let scaler = HybridScaler::new(config.clone());
    scaler.resize(image, src_width, src_height, scale_width, scale_height)
}

/// Resize to fill target dimensions.
fn resize_fill(
    image: &[u8],
    src_width: u32,
    src_height: u32,
    dst_width: u32,
    dst_height: u32,
    config: &HybridConfig,
) -> CvResult<Vec<u8>> {
    let src_aspect = src_width as f64 / src_height as f64;
    let dst_aspect = dst_width as f64 / dst_height as f64;

    let (scale_width, scale_height) = if src_aspect < dst_aspect {
        // Scale to width
        (dst_width, (dst_width as f64 / src_aspect).round() as u32)
    } else {
        // Scale to height
        ((dst_height as f64 * src_aspect).round() as u32, dst_height)
    };

    let scaler = HybridScaler::new(config.clone());
    let scaled = scaler.resize(image, src_width, src_height, scale_width, scale_height)?;

    // Crop to final size
    let crop_x = (scale_width - dst_width) / 2;
    let crop_y = (scale_height - dst_height) / 2;
    crop_image(
        &scaled,
        scale_width,
        scale_height,
        crop_x,
        crop_y,
        dst_width,
        dst_height,
    )
}

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

    #[test]
    fn test_hybrid_config_default() {
        let config = HybridConfig::default();
        assert_eq!(config.strategy, HybridStrategy::Adaptive);
    }

    #[test]
    fn test_hybrid_scaler_traditional() {
        let image = vec![128u8; 100];
        let config = HybridConfig::new(HybridStrategy::TraditionalOnly);
        let scaler = HybridScaler::new(config);
        let result = scaler
            .resize(&image, 10, 10, 8, 8)
            .expect("resize should succeed");
        assert_eq!(result.len(), 64);
    }

    #[test]
    fn test_crop_image() {
        let image = vec![128u8; 100];
        let cropped = crop_image(&image, 10, 10, 2, 2, 4, 4).expect("crop_image should succeed");
        assert_eq!(cropped.len(), 16);
    }

    #[test]
    fn test_calculate_steps() {
        let steps = calculate_steps(4.0, 2.0);
        assert!(!steps.is_empty());
        assert_eq!(*steps.last().expect("last should succeed"), 4.0);
    }

    #[test]
    fn test_multiscale_resizer() {
        let image = vec![128u8; 100];
        let config = HybridConfig::default();
        let resizer = MultiScaleResizer::new(config, 2.0);
        let result = resizer
            .resize(&image, 10, 10, 20, 20)
            .expect("resize should succeed");
        assert_eq!(result.len(), 400);
    }

    #[test]
    fn test_resize_with_aspect_fit() {
        let image = vec![128u8; 200]; // 10x20
        let config = HybridConfig::default();
        let result = resize_with_aspect_ratio(&image, 10, 20, 10, 10, AspectMode::Fit, &config)
            .expect("resize_with_aspect_ratio should succeed");
        // Should fit height, so width will be 5
        assert_eq!(result.len(), 50); // 5x10
    }
}