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
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Similarity metrics for image registration
//!
//! This module provides various similarity metrics used to evaluate
//! the quality of image alignment during registration.

use crate::error::{Result, VisionError};
use scirs2_core::ndarray::Array2;
use std::collections::HashMap;

/// Available similarity metrics for registration
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SimilarityMetric {
    /// Sum of Squared Differences (lower is better)
    SumOfSquaredDifferences,
    /// Normalized Cross-Correlation (higher is better, range -1 to 1)
    NormalizedCrossCorrelation,
    /// Mutual Information (higher is better)
    MutualInformation,
    /// Normalized Mutual Information (higher is better, range 0 to 1)
    NormalizedMutualInformation,
    /// Mean Squared Error (lower is better)
    MeanSquaredError,
    /// Peak Signal-to-Noise Ratio (higher is better)
    PeakSignalToNoiseRatio,
    /// Structural Similarity Index (higher is better, range -1 to 1)
    StructuralSimilarity,
    /// Gradient Correlation (higher is better)
    GradientCorrelation,
}

/// Trait for similarity measure implementations
pub trait SimilarityMeasure {
    /// Compute similarity between two images
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64>;
    
    /// Whether higher values indicate better similarity
    fn higher_is_better(&self) -> bool;
    
    /// Get the optimal value for this metric
    fn optimal_value(&self) -> f64;
    
    /// Normalize the metric value to [0, 1] range where 1 is best
    fn normalize(&self, value: f64) -> f64;
}

/// Sum of Squared Differences implementation
#[derive(Debug, Clone)]
pub struct SumOfSquaredDifferences;

impl SimilarityMeasure for SumOfSquaredDifferences {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let sum_sq_diff: f64 = reference
            .iter()
            .zip(moving.iter())
            .map(|(&r, &m)| {
                let diff = r as f64 - m as f64;
                diff * diff
            })
            .sum();
            
        Ok(sum_sq_diff)
    }
    
    fn higher_is_better(&self) -> bool {
        false
    }
    
    fn optimal_value(&self) -> f64 {
        0.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        // Convert to similarity: lower SSD = higher similarity
        if value <= 0.0 {
            1.0
        } else {
            1.0 / (1.0 + value)
        }
    }
}

/// Normalized Cross-Correlation implementation
#[derive(Debug, Clone)]
pub struct NormalizedCrossCorrelation;

impl SimilarityMeasure for NormalizedCrossCorrelation {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let n = reference.len() as f64;
        
        // Compute means
        let ref_mean: f64 = reference.iter().map(|&x| x as f64).sum::<f64>() / n;
        let mov_mean: f64 = moving.iter().map(|&x| x as f64).sum::<f64>() / n;
        
        // Compute normalized cross-correlation
        let mut numerator = 0.0;
        let mut ref_var = 0.0;
        let mut mov_var = 0.0;
        
        for (&r, &m) in reference.iter().zip(moving.iter()) {
            let ref_centered = r as f64 - ref_mean;
            let mov_centered = m as f64 - mov_mean;
            
            numerator += ref_centered * mov_centered;
            ref_var += ref_centered * ref_centered;
            mov_var += mov_centered * mov_centered;
        }
        
        if ref_var == 0.0 || mov_var == 0.0 {
            return Ok(0.0);
        }
        
        let ncc = numerator / (ref_var * mov_var).sqrt();
        Ok(ncc)
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        1.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        // NCC is already in [-1, 1], convert to [0, 1]
        (value + 1.0) / 2.0
    }
}

/// Mutual Information implementation
#[derive(Debug, Clone)]
pub struct MutualInformation {
    bins: usize,
}

impl MutualInformation {
    /// Create new mutual information metric with specified number of bins
    pub fn new(bins: usize) -> Self {
        Self { _bins }
    }
}

impl Default for MutualInformation {
    fn default() -> Self {
        Self::new(256)
    }
}

impl SimilarityMeasure for MutualInformation {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let (joint_hist, ref_hist, mov_hist) = compute_histograms(reference, moving, self.bins)?;
        
        let total_samples = reference.len() as f64;
        let mut mi = 0.0;
        
        for i in 0..self.bins {
            for j in 0..self.bins {
                let joint_prob = joint_hist[&(i, j)] / total_samples;
                let ref_prob = ref_hist[&i] / total_samples;
                let mov_prob = mov_hist[&j] / total_samples;
                
                if joint_prob > 0.0 && ref_prob > 0.0 && mov_prob > 0.0 {
                    mi += joint_prob * (joint_prob / (ref_prob * mov_prob)).ln();
                }
            }
        }
        
        Ok(mi)
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        // Theoretical maximum depends on image content
        (self.bins as f64).ln()
    }
    
    fn normalize(&self, value: f64) -> f64 {
        // Normalize by theoretical maximum
        let max_mi = self.optimal_value();
        if max_mi > 0.0 {
            (value / max_mi).clamp(0.0, 1.0)
        } else {
            0.0
        }
    }
}

/// Normalized Mutual Information implementation
#[derive(Debug, Clone)]
pub struct NormalizedMutualInformation {
    mi: MutualInformation,
}

impl NormalizedMutualInformation {
    /// Create new normalized mutual information metric
    pub fn new(bins: usize) -> Self {
        Self {
            mi: MutualInformation::new(_bins),
        }
    }
}

impl Default for NormalizedMutualInformation {
    fn default() -> Self {
        Self::new(256)
    }
}

impl SimilarityMeasure for NormalizedMutualInformation {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let (joint_hist, ref_hist, mov_hist) = compute_histograms(reference, moving, self.mi.bins)?;
        
        let total_samples = reference.len() as f64;
        let mut h_ref = 0.0;
        let mut h_mov = 0.0;
        let mut h_joint = 0.0;
        
        // Compute marginal entropies
        for i in 0..self.mi.bins {
            let ref_prob = ref_hist[&i] / total_samples;
            if ref_prob > 0.0 {
                h_ref -= ref_prob * ref_prob.ln();
            }
            
            let mov_prob = mov_hist[&i] / total_samples;
            if mov_prob > 0.0 {
                h_mov -= mov_prob * mov_prob.ln();
            }
        }
        
        // Compute joint entropy
        for i in 0..self.mi.bins {
            for j in 0..self.mi.bins {
                let joint_prob = joint_hist[&(i, j)] / total_samples;
                if joint_prob > 0.0 {
                    h_joint -= joint_prob * joint_prob.ln();
                }
            }
        }
        
        // Normalized MI = (H(ref) + H(mov)) / H(ref, mov)
        if h_joint > 0.0 {
            Ok((h_ref + h_mov) / h_joint)
        } else {
            Ok(0.0)
        }
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        2.0 // Maximum NMI is 2.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        (value / 2.0).clamp(0.0, 1.0)
    }
}

/// Mean Squared Error implementation
#[derive(Debug, Clone)]
pub struct MeanSquaredError;

impl SimilarityMeasure for MeanSquaredError {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let mse: f64 = reference
            .iter()
            .zip(moving.iter())
            .map(|(&r, &m)| {
                let diff = r as f64 - m as f64;
                diff * diff
            })
            .sum::<f64>() / reference.len() as f64;
            
        Ok(mse)
    }
    
    fn higher_is_better(&self) -> bool {
        false
    }
    
    fn optimal_value(&self) -> f64 {
        0.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        if value <= 0.0 {
            1.0
        } else {
            1.0 / (1.0 + value)
        }
    }
}

/// Peak Signal-to-Noise Ratio implementation
#[derive(Debug, Clone)]
pub struct PeakSignalToNoiseRatio {
    max_value: f64,
}

impl PeakSignalToNoiseRatio {
    /// Create new PSNR metric with specified maximum pixel value
    pub fn new(_maxvalue: f64) -> Self {
        Self { _max_value }
    }
}

impl Default for PeakSignalToNoiseRatio {
    fn default() -> Self {
        Self::new(1.0) // Assume normalized images
    }
}

impl SimilarityMeasure for PeakSignalToNoiseRatio {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let mse: f64 = reference
            .iter()
            .zip(moving.iter())
            .map(|(&r, &m)| {
                let diff = r as f64 - m as f64;
                diff * diff
            })
            .sum::<f64>() / reference.len() as f64;
        
        if mse == 0.0 {
            Ok(f64::INFINITY)
        } else {
            let psnr = 20.0 * (self.max_value / mse.sqrt()).log10();
            Ok(psnr)
        }
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        f64::INFINITY
    }
    
    fn normalize(&self, value: f64) -> f64 {
        if value.is_infinite() {
            1.0
        } else {
            // Normalize PSNR to [0, 1] range (assuming reasonable PSNR values 0-100 dB)
            (value / 100.0).clamp(0.0, 1.0)
        }
    }
}

/// Structural Similarity Index implementation
#[derive(Debug, Clone)]
pub struct StructuralSimilarity {
    window_size: usize,
    k1: f64,
    k2: f64,
    l: f64, // Dynamic range of pixel values
}

impl StructuralSimilarity {
    /// Create new SSIM metric with specified parameters
    pub fn new(_windowsize: usize, k1: f64, k2: f64, l: f64) -> Self {
        Self { window_size, k1, k2, l }
    }
}

impl Default for StructuralSimilarity {
    fn default() -> Self {
        Self::new(11, 0.01, 0.03, 1.0)
    }
}

impl SimilarityMeasure for StructuralSimilarity {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let (height, width) = reference.dim();
        let half_window = self.window_size / 2;
        
        if height < self.window_size || width < self.window_size {
            return Err(VisionError::InvalidParameter(
                "Image too small for SSIM window".to_string(),
            ));
        }
        
        let c1 = (self.k1 * self.l).powi(2);
        let c2 = (self.k2 * self.l).powi(2);
        
        let mut ssim_sum = 0.0;
        let mut valid_windows = 0;
        
        for y in half_window..(height - half_window) {
            for x in half_window..(width - half_window) {
                let mut ref_sum = 0.0;
                let mut mov_sum = 0.0;
                let mut ref_sq_sum = 0.0;
                let mut mov_sq_sum = 0.0;
                let mut ref_mov_sum = 0.0;
                let window_pixels = self.window_size * self.window_size;
                
                // Compute statistics over window
                for dy in 0..self.window_size {
                    for dx in 0..self.window_size {
                        let wy = y - half_window + dy;
                        let wx = x - half_window + dx;
                        
                        let ref_val = reference[[wy, wx]] as f64;
                        let mov_val = moving[[wy, wx]] as f64;
                        
                        ref_sum += ref_val;
                        mov_sum += mov_val;
                        ref_sq_sum += ref_val * ref_val;
                        mov_sq_sum += mov_val * mov_val;
                        ref_mov_sum += ref_val * mov_val;
                    }
                }
                
                let n = window_pixels as f64;
                let mu1 = ref_sum / n;
                let mu2 = mov_sum / n;
                let mu1_sq = mu1 * mu1;
                let mu2_sq = mu2 * mu2;
                let mu1_mu2 = mu1 * mu2;
                
                let sigma1_sq = (ref_sq_sum / n) - mu1_sq;
                let sigma2_sq = (mov_sq_sum / n) - mu2_sq;
                let sigma12 = (ref_mov_sum / n) - mu1_mu2;
                
                let numerator = (2.0 * mu1_mu2 + c1) * (2.0 * sigma12 + c2);
                let denominator = (mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2);
                
                if denominator > 0.0 {
                    ssim_sum += numerator / denominator;
                    valid_windows += 1;
                }
            }
        }
        
        if valid_windows > 0 {
            Ok(ssim_sum / valid_windows as f64)
        } else {
            Ok(0.0)
        }
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        1.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        // SSIM is already in [-1, 1], convert to [0, 1]
        (value + 1.0) / 2.0
    }
}

/// Gradient Correlation implementation
#[derive(Debug, Clone)]
pub struct GradientCorrelation;

impl SimilarityMeasure for GradientCorrelation {
    fn compute(&self, reference: &Array2<f32>, moving: &Array2<f32>) -> Result<f64> {
        validate_dimensions(reference, moving)?;
        
        let ref_grad = compute_gradient_magnitude(reference)?;
        let mov_grad = compute_gradient_magnitude(moving)?;
        
        // Compute correlation between gradient magnitudes
        let ncc = NormalizedCrossCorrelation;
        ncc.compute(&ref_grad, &mov_grad)
    }
    
    fn higher_is_better(&self) -> bool {
        true
    }
    
    fn optimal_value(&self) -> f64 {
        1.0
    }
    
    fn normalize(&self, value: f64) -> f64 {
        (value + 1.0) / 2.0
    }
}

/// Factory function to create similarity measure from metric type
#[allow(dead_code)]
pub fn create_similarity_measure(metric: SimilarityMetric) -> Box<dyn SimilarityMeasure> {
    match _metric {
        SimilarityMetric::SumOfSquaredDifferences => Box::new(SumOfSquaredDifferences),
        SimilarityMetric::NormalizedCrossCorrelation => Box::new(NormalizedCrossCorrelation),
        SimilarityMetric::MutualInformation => Box::new(MutualInformation::default()),
        SimilarityMetric::NormalizedMutualInformation => Box::new(NormalizedMutualInformation::default()),
        SimilarityMetric::MeanSquaredError => Box::new(MeanSquaredError),
        SimilarityMetric::PeakSignalToNoiseRatio => Box::new(PeakSignalToNoiseRatio::default()),
        SimilarityMetric::StructuralSimilarity => Box::new(StructuralSimilarity::default()),
        SimilarityMetric::GradientCorrelation => Box::new(GradientCorrelation),
    }
}

// Helper functions

#[allow(dead_code)]
fn validate_dimensions(reference: &Array2<f32>, moving: &Array2<f32>) -> Result<()> {
    if reference.dim() != moving.dim() {
        return Err(VisionError::InvalidParameter(
            "Reference and moving images must have the same dimensions".to_string(),
        ));
    }
    
    let (height, width) = reference.dim();
    if height == 0 || width == 0 {
        return Err(VisionError::InvalidParameter(
            "Images must have non-zero dimensions".to_string(),
        ));
    }
    
    Ok(())
}

#[allow(dead_code)]
fn compute_histograms(
    reference: &Array2<f32>,
    moving: &Array2<f32>,
    bins: usize,
) -> Result<(HashMap<(usize, usize), f64>, HashMap<usize, f64>, HashMap<usize, f64>)> {
    // Find min/max values for histogram binning
    let ref_min = reference.iter().fold(f32::INFINITY, |a, &b| a.min(b)) as f64;
    let ref_max = reference.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64;
    let mov_min = moving.iter().fold(f32::INFINITY, |a, &b| a.min(b)) as f64;
    let mov_max = moving.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64;
    
    let ref_range = ref_max - ref_min;
    let mov_range = mov_max - mov_min;
    
    if ref_range == 0.0 || mov_range == 0.0 {
        return Err(VisionError::InvalidParameter(
            "Image has no intensity variation".to_string(),
        ));
    }
    
    let mut joint_hist = HashMap::new();
    let mut ref_hist = HashMap::new();
    let mut mov_hist = HashMap::new();
    
    for (&r, &m) in reference.iter().zip(moving.iter()) {
        let ref_bin = ((r as f64 - ref_min) / ref_range * (bins - 1) as f64).round() as usize;
        let mov_bin = ((m as f64 - mov_min) / mov_range * (bins - 1) as f64).round() as usize;
        
        let ref_bin = ref_bin.min(bins - 1);
        let mov_bin = mov_bin.min(bins - 1);
        
        *joint_hist.entry((ref_bin, mov_bin)).or_insert(0.0) += 1.0;
        *ref_hist.entry(ref_bin).or_insert(0.0) += 1.0;
        *mov_hist.entry(mov_bin).or_insert(0.0) += 1.0;
    }
    
    Ok((joint_hist, ref_hist, mov_hist))
}

#[allow(dead_code)]
fn compute_gradient_magnitude(image: &Array2<f32>) -> Result<Array2<f32>> {
    let (height, width) = image.dim();
    let mut gradient = Array2::zeros((height, width));
    
    for y in 1..(height - 1) {
        for x in 1..(width - 1) {
            let gx = image[[y, x + 1]] - image[[y, x - 1]];
            let gy = image[[y + 1, x]] - image[[y - 1, x]];
            gradient[[y, x]] = (gx * gx + gy * gy).sqrt();
        }
    }
    
    Ok(gradient)
}

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

    fn create_test_images() -> (Array2<f32>, Array2<f32>) {
        let mut reference = Array2::zeros((50, 50));
        let mut moving = Array2::zeros((50, 50));
        
        // Create a simple pattern
        for i in 10..40 {
            for j in 10..40 {
                reference[[i, j]] = 1.0;
                moving[[i + 2, j + 2]] = 1.0; // Shifted version
            }
        }
        
        (reference, moving)
    }

    #[test]
    fn test_sum_of_squared_differences() {
        let (reference, moving) = create_test_images();
        let ssd = SumOfSquaredDifferences;
        
        let result = ssd.compute(&reference, &moving).expect("Operation failed");
        assert!(result > 0.0);
        
        // Test with identical images
        let result_identical = ssd.compute(&reference, &reference).expect("Operation failed");
        assert_eq!(result_identical, 0.0);
    }

    #[test]
    fn test_normalized_cross_correlation() {
        let (reference, moving) = create_test_images();
        let ncc = NormalizedCrossCorrelation;
        
        let result = ncc.compute(&reference, &moving).expect("Operation failed");
        assert!(result >= -1.0 && result <= 1.0);
        
        // Test with identical images
        let result_identical = ncc.compute(&reference, &reference).expect("Operation failed");
        assert!((result_identical - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_mutual_information() {
        let (reference, moving) = create_test_images();
        let mi = MutualInformation::new(16); // Use fewer bins for test
        
        let result = mi.compute(&reference, &moving).expect("Operation failed");
        assert!(result >= 0.0);
        
        // MI should be higher for identical images
        let result_identical = mi.compute(&reference, &reference).expect("Operation failed");
        assert!(result_identical >= result);
    }

    #[test]
    fn test_mean_squared_error() {
        let (reference, moving) = create_test_images();
        let mse = MeanSquaredError;
        
        let result = mse.compute(&reference, &moving).expect("Operation failed");
        assert!(result >= 0.0);
        
        // MSE should be 0 for identical images
        let result_identical = mse.compute(&reference, &reference).expect("Operation failed");
        assert_eq!(result_identical, 0.0);
    }

    #[test]
    fn test_peak_signal_to_noise_ratio() {
        let (reference, moving) = create_test_images();
        let psnr = PeakSignalToNoiseRatio::default();
        
        let result = psnr.compute(&reference, &moving).expect("Operation failed");
        assert!(result > 0.0);
        
        // PSNR should be infinite for identical images
        let result_identical = psnr.compute(&reference, &reference).expect("Operation failed");
        assert!(result_identical.is_infinite());
    }

    #[test]
    fn test_structural_similarity() {
        let reference = Array2::ones((20, 20));
        let moving = Array2::ones((20, 20));
        
        let ssim = StructuralSimilarity::default();
        let result = ssim.compute(&reference, &moving).expect("Operation failed");
        
        // SSIM should be 1 for identical images
        assert!((result - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_gradient_correlation() {
        let (reference, moving) = create_test_images();
        let gc = GradientCorrelation;
        
        let result = gc.compute(&reference, &moving).expect("Operation failed");
        assert!(result >= -1.0 && result <= 1.0);
    }

    #[test]
    fn test_metric_normalization() {
        let (reference, moving) = create_test_images();
        
        let ssd = SumOfSquaredDifferences;
        let result = ssd.compute(&reference, &moving).expect("Operation failed");
        let normalized = ssd.normalize(result);
        assert!(normalized >= 0.0 && normalized <= 1.0);
        
        let ncc = NormalizedCrossCorrelation;
        let result = ncc.compute(&reference, &moving).expect("Operation failed");
        let normalized = ncc.normalize(result);
        assert!(normalized >= 0.0 && normalized <= 1.0);
    }

    #[test]
    fn test_create_similarity_measure() {
        let metric = SimilarityMetric::NormalizedCrossCorrelation;
        let measure = create_similarity_measure(metric);
        
        let reference = Array2::ones((10, 10));
        let moving = Array2::ones((10, 10));
        
        let result = measure.compute(&reference, &moving).expect("Operation failed");
        assert!((result - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_dimension_validation() {
        let reference = Array2::ones((10, 10));
        let moving = Array2::ones((5, 5));
        
        let ssd = SumOfSquaredDifferences;
        let result = ssd.compute(&reference, &moving);
        assert!(result.is_err());
    }
}