From 24e11362a00dd63dbf4d345a046439525beca05a Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Mon, 20 Jul 2020 14:42:33 +0100 Subject: [PATCH] flipping/mirroring images --- src/image.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/mock.rs | 13 +++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/image.rs b/src/image.rs index c55a843..1dc7a93 100644 --- a/src/image.rs +++ b/src/image.rs @@ -3,6 +3,34 @@ pub struct Image { pub pixels: Vec, // 64 for SD, 256 for HD } +impl Image { + /// flip image vertically + fn flip(&mut self) { + let mut pixels = Vec::with_capacity(64); + + for row in self.pixels.chunks(8).rev() { + for pixel in row { + pixels.push(*pixel); + } + } + + self.pixels = pixels; + } + + /// mirror image horizontally + fn mirror(&mut self) { + let mut pixels = Vec::with_capacity(64); + + for row in self.pixels.chunks(8) { + for i in (0..8).rev() { + pixels.push(row[i]); + } + } + + self.pixels = pixels; + } +} + impl From for Image { fn from(string: String) -> Image { let string = string.replace("NaN", "0"); @@ -114,4 +142,42 @@ mod test { assert_eq!(output, expected); } + + #[test] + fn flip() { + let mut image = crate::mock::image::asymmetrical(); + image.flip(); + + let flipped = Image { pixels: vec![ + 0,0,0,1,0,0,0,0, + 0,0,1,0,0,0,0,0, + 0,1,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0, + 0,1,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + ]}; + + assert_eq!(image, flipped); + } + + #[test] + fn test_mirror() { + let mut image = crate::mock::image::asymmetrical(); + image.mirror(); + + let mirrored = Image { pixels: vec![ + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,1,0, + 0,0,0,0,0,0,0,1, + 0,0,0,0,0,0,0,1, + 0,0,0,0,0,0,1,0, + 0,0,0,0,0,1,0,0, + 0,0,0,0,1,0,0,0, + ]}; + + assert_eq!(image, mirrored); + } } diff --git a/src/mock.rs b/src/mock.rs index fa67b2e..f5379c5 100644 --- a/src/mock.rs +++ b/src/mock.rs @@ -24,6 +24,19 @@ pub mod image { } } + pub fn asymmetrical() -> Image { + Image { pixels: vec![ + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,1,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0, + 1,0,0,0,0,0,0,0, + 0,1,0,0,0,0,0,0, + 0,0,1,0,0,0,0,0, + 0,0,0,1,0,0,0,0, + ]} + } + pub fn animation_frames() -> Vec { vec![ Image {