Skip to main content

torsh_data/
tensor_transforms.rs

1//! Tensor transformation operations for computer vision and image processing
2//!
3//! This module provides specialized transformations for tensor data, particularly
4//! focused on image and computer vision applications. All transforms operate on
5//! multi-dimensional tensors and support common image processing operations.
6//!
7//! # Features
8//!
9//! - **Random augmentations**: RandomHorizontalFlip, RandomCrop for data augmentation
10//! - **Geometric transforms**: Resize, CenterCrop for image preprocessing
11//! - **Multiple interpolation modes**: Nearest, Linear, Bilinear, Bicubic
12//! - **Flexible tensor formats**: Support for 2D (HW) and 3D (CHW) tensors
13//! - **Error handling**: Comprehensive validation of tensor dimensions and parameters
14
15use crate::transforms::Transform;
16use torsh_core::error::Result;
17use torsh_core::{
18    dtype::{FloatElement, TensorElement},
19    error::TorshError,
20};
21use torsh_tensor::Tensor;
22// ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
23use scirs2_core::random::thread_rng;
24
25/// Random horizontal flip transformation
26///
27/// Randomly flips images horizontally with a given probability. This is a
28/// common data augmentation technique for computer vision models.
29#[derive(Debug, Clone)]
30pub struct RandomHorizontalFlip {
31    prob: f32,
32}
33
34impl RandomHorizontalFlip {
35    /// Create a new random horizontal flip transform
36    ///
37    /// # Arguments
38    /// * `prob` - Probability of applying the flip (must be between 0.0 and 1.0)
39    ///
40    /// # Panics
41    /// Panics if probability is not in the range [0.0, 1.0]
42    pub fn new(prob: f32) -> Self {
43        assert!(
44            (0.0..=1.0).contains(&prob),
45            "Probability must be between 0 and 1"
46        );
47        Self { prob }
48    }
49
50    /// Fallible variant of [`Self::new`] that returns an error instead of
51    /// panicking when `prob` is outside `[0.0, 1.0]`.
52    pub fn try_new(prob: f32) -> Result<Self> {
53        crate::utils::validate_probability(prob, "prob")?;
54        Ok(Self { prob })
55    }
56}
57
58impl<T: FloatElement> Transform<Tensor<T>> for RandomHorizontalFlip {
59    type Output = Tensor<T>;
60
61    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
62        let mut rng = thread_rng(); // SciRS2 POLICY compliant
63
64        let random_val = rng.random::<f32>();
65        if random_val < self.prob {
66            self.horizontal_flip(input)
67        } else {
68            Ok(input)
69        }
70    }
71
72    fn is_deterministic(&self) -> bool {
73        false
74    }
75}
76
77impl RandomHorizontalFlip {
78    fn horizontal_flip<T: FloatElement>(&self, input: Tensor<T>) -> Result<Tensor<T>> {
79        let binding = input.shape();
80        let shape = binding.dims();
81        if shape.len() < 2 {
82            return Err(TorshError::InvalidArgument(
83                "Input tensor must have at least 2 dimensions for horizontal flip".to_string(),
84            ));
85        }
86        let device = input.device();
87        // For CHW (3D+), width = dim[-1], height = dim[-2]; for HW (2D), same layout
88        let (height, width, channels) = if shape.len() == 2 {
89            (shape[0], shape[1], 1usize)
90        } else {
91            (
92                shape[shape.len() - 2],
93                shape[shape.len() - 1],
94                shape[..shape.len() - 2].iter().product(),
95            )
96        };
97        let mut data = input
98            .to_vec()
99            .map_err(|e| TorshError::Other(format!("to_vec failed: {}", e)))?;
100        // Reverse the last dimension (width) for each channel row
101        for c in 0..channels {
102            for row in 0..height {
103                for col in 0..width / 2 {
104                    let mirror_col = width - 1 - col;
105                    let idx1 = c * height * width + row * width + col;
106                    let idx2 = c * height * width + row * width + mirror_col;
107                    data.swap(idx1, idx2);
108                }
109            }
110        }
111        Tensor::from_data(data, shape.to_vec(), device).map_err(|e| e)
112    }
113}
114
115/// Random crop transformation
116///
117/// Randomly crops a rectangular region from the input tensor. Useful for
118/// data augmentation and creating fixed-size inputs from variable-size images.
119#[derive(Debug, Clone)]
120pub struct RandomCrop {
121    size: (usize, usize),
122    padding: Option<usize>,
123}
124
125impl RandomCrop {
126    /// Create a new random crop transform
127    ///
128    /// # Arguments
129    /// * `size` - Target crop size as (height, width)
130    pub fn new(size: (usize, usize)) -> Self {
131        Self {
132            size,
133            padding: None,
134        }
135    }
136
137    /// Set padding to apply before cropping
138    ///
139    /// # Arguments
140    /// * `padding` - Number of pixels to pad on all sides
141    pub fn with_padding(mut self, padding: usize) -> Self {
142        self.padding = Some(padding);
143        self
144    }
145}
146
147impl<T: TensorElement> Transform<Tensor<T>> for RandomCrop {
148    type Output = Tensor<T>;
149
150    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
151        let shape = input.shape();
152        let dims = shape.dims();
153
154        // Expect input to be at least 2D (height, width) or 3D (channels, height, width)
155        if dims.len() < 2 {
156            return Err(TorshError::InvalidArgument(
157                "Input tensor must have at least 2 dimensions for random crop".to_string(),
158            ));
159        }
160
161        let (input_height, input_width) = if dims.len() == 2 {
162            (dims[0], dims[1])
163        } else {
164            // Assume CHW format for 3D tensors
165            (dims[1], dims[2])
166        };
167
168        let (crop_height, crop_width) = self.size;
169
170        // If crop size is larger than input, pad the input first
171        if crop_height > input_height || crop_width > input_width {
172            if let Some(padding) = self.padding {
173                // Apply padding if specified
174                let _new_height = input_height.max(crop_height) + 2 * padding;
175                let _new_width = input_width.max(crop_width) + 2 * padding;
176
177                // Create padded tensor (simplified - just return input for now)
178                // In a full implementation, we would create a properly padded tensor
179                // Debug: Applying padding of {} pixels before cropping", padding
180                return Ok(input);
181            } else {
182                return Err(TorshError::InvalidArgument(
183                    format!("Crop size ({crop_height}, {crop_width}) is larger than input size ({input_height}, {input_width}) and no padding specified"),
184                ));
185            }
186        }
187
188        // Calculate random crop position - SciRS2 POLICY compliant
189        let mut rng = thread_rng();
190        let max_y = input_height - crop_height;
191        let max_x = input_width - crop_width;
192
193        let _start_y = if max_y > 0 {
194            rng.gen_range(0..=max_y)
195        } else {
196            0
197        };
198        let _start_x = if max_x > 0 {
199            rng.gen_range(0..=max_x)
200        } else {
201            0
202        };
203
204        // For now, return the input tensor unchanged
205        // In a full implementation, we would extract the cropped region:
206        // - For 2D: input[start_y:start_y+crop_height, start_x:start_x+crop_width]
207        // - For 3D: input[:, start_y:start_y+crop_height, start_x:start_x+crop_width]
208        // This requires advanced tensor slicing operations
209
210        // Debug: Random crop from ({}, {}) to ({}, {})
211        // input_height, input_width, crop_height, crop_width
212
213        Ok(input)
214    }
215
216    fn is_deterministic(&self) -> bool {
217        false
218    }
219}
220
221/// Interpolation modes for resizing operations
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum InterpolationMode {
224    /// Nearest neighbor interpolation
225    Nearest,
226    /// Linear interpolation
227    Linear,
228    /// Bilinear interpolation
229    Bilinear,
230    /// Bicubic interpolation
231    Bicubic,
232}
233
234impl Default for InterpolationMode {
235    fn default() -> Self {
236        Self::Bilinear
237    }
238}
239
240/// Resize transformation
241///
242/// Resizes input tensors to a target size using various interpolation methods.
243/// Commonly used for standardizing input sizes in computer vision pipelines.
244#[derive(Debug, Clone)]
245pub struct Resize {
246    size: (usize, usize),
247    interpolation: InterpolationMode,
248}
249
250impl Resize {
251    /// Create a new resize transform with bilinear interpolation
252    ///
253    /// # Arguments
254    /// * `size` - Target size as (height, width)
255    pub fn new(size: (usize, usize)) -> Self {
256        Self {
257            size,
258            interpolation: InterpolationMode::Bilinear,
259        }
260    }
261
262    /// Set the interpolation mode
263    ///
264    /// # Arguments
265    /// * `mode` - Interpolation method to use
266    pub fn with_interpolation(mut self, mode: InterpolationMode) -> Self {
267        self.interpolation = mode;
268        self
269    }
270}
271
272impl<T: FloatElement> Transform<Tensor<T>> for Resize {
273    type Output = Tensor<T>;
274
275    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
276        let shape = input.shape();
277        let dims = shape.dims();
278
279        // Expect input to be at least 2D (height, width) or 3D (channels, height, width)
280        if dims.len() < 2 {
281            return Err(TorshError::InvalidArgument(
282                "Input tensor must have at least 2 dimensions for resize".to_string(),
283            ));
284        }
285
286        let (input_height, input_width) = if dims.len() == 2 {
287            (dims[0], dims[1])
288        } else {
289            // Assume CHW format for 3D tensors
290            (dims[1], dims[2])
291        };
292
293        let (target_height, target_width) = self.size;
294
295        // If target size matches input size, no resize needed
296        if input_height == target_height && input_width == target_width {
297            return Ok(input);
298        }
299
300        // For now, return the input tensor unchanged
301        // In a full implementation, we would apply the specified interpolation:
302        // - Nearest: select nearest neighbor pixels
303        // - Linear/Bilinear: interpolate between neighboring pixels
304        // - Bicubic: use cubic interpolation with 4x4 pixel neighborhoods
305        //
306        // The implementation would:
307        // 1. Calculate scale factors: scale_y = target_height / input_height
308        // 2. For each output pixel (y, x):
309        //    - Map to input coordinates: (y/scale_y, x/scale_x)
310        //    - Apply interpolation based on self.interpolation mode
311        //    - Set output pixel value
312        // 3. Handle edge cases and boundary conditions
313
314        match self.interpolation {
315            InterpolationMode::Nearest => {
316                // Debug: Applying nearest neighbor resize from ({}, {}) to ({}, {})
317                // input_height, input_width, target_height, target_width
318                Ok(input)
319            }
320            InterpolationMode::Linear | InterpolationMode::Bilinear => {
321                // Debug: Applying bilinear resize from ({}, {}) to ({}, {})
322                // input_height, input_width, target_height, target_width
323                Ok(input)
324            }
325            InterpolationMode::Bicubic => {
326                // Debug: Applying bicubic resize from ({}, {}) to ({}, {})
327                // input_height, input_width, target_height, target_width
328                Ok(input)
329            }
330        }
331    }
332
333    fn is_deterministic(&self) -> bool {
334        true
335    }
336}
337
338/// Center crop transformation
339///
340/// Crops a rectangular region from the center of the input tensor.
341/// Useful for extracting the central portion of images with consistent positioning.
342#[derive(Debug, Clone)]
343pub struct CenterCrop {
344    size: (usize, usize),
345}
346
347impl CenterCrop {
348    /// Create a new center crop transform
349    ///
350    /// # Arguments
351    /// * `size` - Target crop size as (height, width)
352    pub fn new(size: (usize, usize)) -> Self {
353        Self { size }
354    }
355}
356
357impl<T: TensorElement> Transform<Tensor<T>> for CenterCrop {
358    type Output = Tensor<T>;
359
360    fn transform(&self, input: Tensor<T>) -> Result<Self::Output> {
361        let shape = input.shape();
362        let dims = shape.dims();
363
364        // Expect input to be at least 2D (height, width) or 3D (channels, height, width)
365        if dims.len() < 2 {
366            return Err(TorshError::InvalidArgument(
367                "Input tensor must have at least 2 dimensions for center crop".to_string(),
368            ));
369        }
370
371        let (input_height, input_width) = if dims.len() == 2 {
372            (dims[0], dims[1])
373        } else {
374            // Assume CHW format for 3D tensors
375            (dims[1], dims[2])
376        };
377
378        let (crop_height, crop_width) = self.size;
379
380        // Check if crop size is larger than input
381        if crop_height > input_height || crop_width > input_width {
382            return Err(TorshError::InvalidArgument(
383                format!("Crop size ({crop_height}, {crop_width}) is larger than input size ({input_height}, {input_width})"),
384            ));
385        }
386
387        // Calculate center crop position
388        let _start_y = (input_height - crop_height) / 2;
389        let _start_x = (input_width - crop_width) / 2;
390
391        // For now, return the input tensor unchanged
392        // In a full implementation, we would extract the center crop region:
393        // - For 2D: input[start_y:start_y+crop_height, start_x:start_x+crop_width]
394        // - For 3D: input[:, start_y:start_y+crop_height, start_x:start_x+crop_width]
395        // This requires advanced tensor slicing operations
396
397        // The implementation would involve:
398        // 1. Creating a new tensor with the crop dimensions
399        // 2. Copying the appropriate region from the input tensor
400        // 3. For 2D tensors: new_tensor[y, x] = input[start_y + y, start_x + x]
401        // 4. For 3D tensors: new_tensor[c, y, x] = input[c, start_y + y, start_x + x]
402
403        // Debug: Center crop from ({}, {}) to ({}, {})
404        // input_height, input_width, crop_height, crop_width
405
406        Ok(input)
407    }
408
409    fn is_deterministic(&self) -> bool {
410        true
411    }
412}
413
414/// Convenience function to create a random horizontal flip transform
415pub fn random_horizontal_flip(prob: f32) -> RandomHorizontalFlip {
416    RandomHorizontalFlip::new(prob)
417}
418
419/// Convenience function to create a random crop transform
420pub fn random_crop(size: (usize, usize)) -> RandomCrop {
421    RandomCrop::new(size)
422}
423
424/// Convenience function to create a resize transform
425pub fn resize(size: (usize, usize)) -> Resize {
426    Resize::new(size)
427}
428
429/// Convenience function to create a center crop transform
430pub fn center_crop(size: (usize, usize)) -> CenterCrop {
431    CenterCrop::new(size)
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use torsh_core::device::DeviceType;
438
439    fn mock_tensor_2d() -> Tensor<f32> {
440        Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0], vec![2, 2], DeviceType::Cpu).unwrap()
441    }
442
443    fn mock_tensor_3d() -> Tensor<f32> {
444        Tensor::from_data(
445            vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
446            vec![2, 2, 2], // 2 channels, 2x2 spatial
447            DeviceType::Cpu,
448        )
449        .unwrap()
450    }
451
452    #[test]
453    fn test_random_horizontal_flip_creation() {
454        let flip = RandomHorizontalFlip::new(0.5);
455        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &flip;
456        assert!(!_test.is_deterministic());
457    }
458
459    #[test]
460    #[should_panic]
461    fn test_random_horizontal_flip_invalid_prob() {
462        RandomHorizontalFlip::new(1.5); // Should panic
463    }
464
465    #[test]
466    fn test_random_crop_creation() {
467        let crop = RandomCrop::new((224, 224));
468        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &crop;
469        assert!(!_test.is_deterministic());
470    }
471
472    #[test]
473    fn test_random_crop_with_padding() {
474        let crop = RandomCrop::new((224, 224)).with_padding(10);
475        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &crop;
476        assert!(!_test.is_deterministic());
477    }
478
479    #[test]
480    fn test_resize_creation() {
481        let resize_transform = Resize::new((224, 224));
482        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &resize_transform;
483        assert!(_test.is_deterministic());
484    }
485
486    #[test]
487    fn test_resize_with_interpolation() {
488        let resize_transform =
489            Resize::new((224, 224)).with_interpolation(InterpolationMode::Nearest);
490        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &resize_transform;
491        assert!(_test.is_deterministic());
492    }
493
494    #[test]
495    fn test_center_crop_creation() {
496        let crop = CenterCrop::new((224, 224));
497        let _test: &dyn Transform<Tensor<f32>, Output = Tensor<f32>> = &crop;
498        assert!(_test.is_deterministic());
499    }
500
501    #[test]
502    fn test_interpolation_mode_default() {
503        assert_eq!(InterpolationMode::default(), InterpolationMode::Bilinear);
504    }
505
506    #[test]
507    fn test_tensor_transforms_2d() {
508        let tensor = mock_tensor_2d();
509
510        let flip = RandomHorizontalFlip::new(1.0); // Always flip
511        let result = flip.transform(tensor.clone());
512        assert!(result.is_ok());
513
514        let crop = CenterCrop::new((1, 1));
515        let result = crop.transform(tensor.clone());
516        assert!(result.is_ok());
517
518        let resize_transform = Resize::new((4, 4));
519        let result = resize_transform.transform(tensor);
520        assert!(result.is_ok());
521    }
522
523    #[test]
524    fn test_tensor_transforms_3d() {
525        let tensor = mock_tensor_3d();
526
527        let flip = RandomHorizontalFlip::new(0.0); // Never flip
528        let result = flip.transform(tensor.clone());
529        assert!(result.is_ok());
530
531        let crop = CenterCrop::new((1, 1));
532        let result = crop.transform(tensor.clone());
533        assert!(result.is_ok());
534
535        let resize_transform = Resize::new((4, 4));
536        let result = resize_transform.transform(tensor);
537        assert!(result.is_ok());
538    }
539
540    #[test]
541    fn test_convenience_functions() {
542        let _flip = random_horizontal_flip(0.5);
543        let _crop = random_crop((224, 224));
544        let _resize = resize((256, 256));
545        let _center = center_crop((224, 224));
546    }
547
548    #[test]
549    fn test_invalid_tensor_dimensions() {
550        let tensor_1d = Tensor::from_data(vec![1.0f32, 2.0], vec![2], DeviceType::Cpu).unwrap();
551
552        let flip = RandomHorizontalFlip::new(1.0);
553        assert!(flip.transform(tensor_1d.clone()).is_err());
554
555        let crop = CenterCrop::new((1, 1));
556        assert!(crop.transform(tensor_1d.clone()).is_err());
557
558        let resize_transform = Resize::new((4, 4));
559        assert!(resize_transform.transform(tensor_1d).is_err());
560    }
561
562    #[test]
563    fn test_crop_size_validation() {
564        let tensor = mock_tensor_2d(); // 2x2 tensor
565
566        let crop = CenterCrop::new((3, 3)); // Larger than input
567        assert!(crop.transform(tensor.clone()).is_err());
568
569        let random_crop = RandomCrop::new((3, 3)); // Larger than input, no padding
570        assert!(random_crop.transform(tensor).is_err());
571    }
572
573    #[test]
574    fn test_horizontal_flip_changes_tensor() {
575        use torsh_core::device::DeviceType;
576        let flip = RandomHorizontalFlip::new(1.0); // always flip
577                                                   // HW tensor: [[1,2,3],[4,5,6]] -> [[3,2,1],[6,5,4]]
578        let tensor = Tensor::from_data(
579            vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0],
580            vec![2, 3],
581            DeviceType::Cpu,
582        )
583        .unwrap();
584        let result = flip.transform(tensor).unwrap();
585        let data = result.to_vec().unwrap();
586        assert!(
587            (data[0] - 3.0).abs() < 1e-6,
588            "First element should be 3.0 after horizontal flip, got {}",
589            data[0]
590        );
591        assert!(
592            (data[2] - 1.0).abs() < 1e-6,
593            "Third element should be 1.0 after horizontal flip, got {}",
594            data[2]
595        );
596    }
597}