From 8ab38776d5fa232db5cf57064fa13080591ca41d Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Sun, 25 Oct 2026 22:28:29 +0000 Subject: [PATCH] Use Image for_each for kernel convolution --- src/kernel.rs | 46 ++++++++++++++++++++-------------------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/src/kernel.rs b/src/kernel.rs index 2cc88a4..2b2888f 100644 --- a/src/kernel.rs +++ b/src/kernel.rs @@ -28,24 +28,19 @@ impl Kernel for [[f32; N]; N] { x: img.extent.x - 2 * l, y: img.extent.y - 2 * l, }; - - let mut pixels = Vec::with_capacity(extent.size() as usize); - for y in 0..extent.y { - for x in 0..extent.x { - let mut pixel = P::default(); - for i in 0..N { - for j in 0..N { - let img_x = x as usize + i; - let img_y = y as usize + j; - let idx = img_y * img.extent.x as usize + img_x; - pixel += img.pixels[idx] * self[j][i]; - } + let mut result = image::Image::with_extent(extent); + result.for_each(|x, y, p| { + for i in 0..N { + for j in 0..N { + let img_x = x as usize + i; + let img_y = y as usize + j; + let idx = img_y * img.extent.x as usize + img_x; + *p += img.pixels[idx] * self[j][i]; } - pixels.push(pixel / mag); } - } - - image::Image { extent, pixels } + *p /= mag; + }); + result } } @@ -70,15 +65,15 @@ mod tests { let input = image::Image { extent: image::Extent { x: 3, y: 3 }, pixels: vec![ - image::SRGBA::new(0.1, 0.0, 0.0, 1.0), - image::SRGBA::new(0.0, 0.2, 0.0, 1.0), - image::SRGBA::new(0.0, 0.0, 0.3, 1.0), - image::SRGBA::new(0.2, 0.0, 0.0, 1.0), - image::SRGBA::new(0.0, 0.3, 0.0, 1.0), - image::SRGBA::new(0.0, 0.0, 0.1, 1.0), - image::SRGBA::new(0.3, 0.0, 0.0, 1.0), - image::SRGBA::new(0.0, 0.1, 0.0, 1.0), - image::SRGBA::new(0.0, 0.0, 0.2, 1.0), + image::SRGB::new(0.1, 0.0, 0.0), + image::SRGB::new(0.0, 0.2, 0.0), + image::SRGB::new(0.0, 0.0, 0.3), + image::SRGB::new(0.2, 0.0, 0.0), + image::SRGB::new(0.0, 0.3, 0.0), + image::SRGB::new(0.0, 0.0, 0.1), + image::SRGB::new(0.3, 0.0, 0.0), + image::SRGB::new(0.0, 0.1, 0.0), + image::SRGB::new(0.0, 0.0, 0.2), ], }; let kernel = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]; @@ -97,6 +92,5 @@ mod tests { output.pixels[0].b, (0.3 * 0.3 + 0.1 * 0.6 + 0.2 * 0.9) / 4.5, ); - assert_eq!(output.pixels[0].a, 1.0); } }