1use crate::transforms::Transform;
16use torsh_core::error::Result;
17use torsh_core::{
18 dtype::{FloatElement, TensorElement},
19 error::TorshError,
20};
21use torsh_tensor::Tensor;
22use scirs2_core::random::thread_rng;
24
25#[derive(Debug, Clone)]
30pub struct RandomHorizontalFlip {
31 prob: f32,
32}
33
34impl RandomHorizontalFlip {
35 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 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(); 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 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 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#[derive(Debug, Clone)]
120pub struct RandomCrop {
121 size: (usize, usize),
122 padding: Option<usize>,
123}
124
125impl RandomCrop {
126 pub fn new(size: (usize, usize)) -> Self {
131 Self {
132 size,
133 padding: None,
134 }
135 }
136
137 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 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 (dims[1], dims[2])
166 };
167
168 let (crop_height, crop_width) = self.size;
169
170 if crop_height > input_height || crop_width > input_width {
172 if let Some(padding) = self.padding {
173 let _new_height = input_height.max(crop_height) + 2 * padding;
175 let _new_width = input_width.max(crop_width) + 2 * padding;
176
177 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 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 Ok(input)
214 }
215
216 fn is_deterministic(&self) -> bool {
217 false
218 }
219}
220
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum InterpolationMode {
224 Nearest,
226 Linear,
228 Bilinear,
230 Bicubic,
232}
233
234impl Default for InterpolationMode {
235 fn default() -> Self {
236 Self::Bilinear
237 }
238}
239
240#[derive(Debug, Clone)]
245pub struct Resize {
246 size: (usize, usize),
247 interpolation: InterpolationMode,
248}
249
250impl Resize {
251 pub fn new(size: (usize, usize)) -> Self {
256 Self {
257 size,
258 interpolation: InterpolationMode::Bilinear,
259 }
260 }
261
262 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 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 (dims[1], dims[2])
291 };
292
293 let (target_height, target_width) = self.size;
294
295 if input_height == target_height && input_width == target_width {
297 return Ok(input);
298 }
299
300 match self.interpolation {
315 InterpolationMode::Nearest => {
316 Ok(input)
319 }
320 InterpolationMode::Linear | InterpolationMode::Bilinear => {
321 Ok(input)
324 }
325 InterpolationMode::Bicubic => {
326 Ok(input)
329 }
330 }
331 }
332
333 fn is_deterministic(&self) -> bool {
334 true
335 }
336}
337
338#[derive(Debug, Clone)]
343pub struct CenterCrop {
344 size: (usize, usize),
345}
346
347impl CenterCrop {
348 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 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 (dims[1], dims[2])
376 };
377
378 let (crop_height, crop_width) = self.size;
379
380 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 let _start_y = (input_height - crop_height) / 2;
389 let _start_x = (input_width - crop_width) / 2;
390
391 Ok(input)
407 }
408
409 fn is_deterministic(&self) -> bool {
410 true
411 }
412}
413
414pub fn random_horizontal_flip(prob: f32) -> RandomHorizontalFlip {
416 RandomHorizontalFlip::new(prob)
417}
418
419pub fn random_crop(size: (usize, usize)) -> RandomCrop {
421 RandomCrop::new(size)
422}
423
424pub fn resize(size: (usize, usize)) -> Resize {
426 Resize::new(size)
427}
428
429pub 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], 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); }
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); 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); 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(); let crop = CenterCrop::new((3, 3)); assert!(crop.transform(tensor.clone()).is_err());
568
569 let random_crop = RandomCrop::new((3, 3)); 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); 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}