Refactor allowing multiple pixel formats

This commit is contained in:
cdo committed 2026-10-25 22:24:52 +00:00
1 parent cef82a2e14
commit 6cd059f401
3 files changed
+138 -102

No files matched your search

+21 -16
View File
@@ -1,7 +1,9 @@
use crate::*;
pub trait Kernel {
fn convolve(&self, img: &image::Image) -> image::Image;
fn convolve<P>(&self, img: &image::Image<P>) -> image::Image<P>
where
P: image::Pixel;
}
fn sum<const N: usize>(kernel: &[[f32; N]; N]) -> f32 {
@@ -15,9 +17,12 @@ fn sum<const N: usize>(kernel: &[[f32; N]; N]) -> f32 {
}
impl<const N: usize> Kernel for [[f32; N]; N] {
fn convolve(&self, img: &image::Image) -> image::Image {
let l = N as u32 / 2;
let mag = sum(self);
fn convolve<P>(&self, img: &image::Image<P>) -> image::Image<P>
where
P: image::Pixel,
{
let l = N / 2;
let mag = sum(self);
let extent = image::Extent {
x: img.extent.x - 2 * l,
@@ -26,8 +31,8 @@ impl<const N: usize> Kernel for [[f32; N]; N] {
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 = image::Pixel::default();
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;
@@ -52,7 +57,7 @@ mod tests {
fn size_of_result_img() {
let input = image::Image {
extent: image::Extent { x: 6, y: 10 },
pixels: vec![image::Pixel::default(); 60],
pixels: vec![0.0; 60],
};
let kernel = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]];
let output = kernel.convolve(&input);
@@ -65,15 +70,15 @@ mod tests {
let input = image::Image {
extent: image::Extent { x: 3, y: 3 },
pixels: vec![
image::Pixel::rgba(0.1, 0.0, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.2, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.0, 0.3, 1.0),
image::Pixel::rgba(0.2, 0.0, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.3, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.0, 0.1, 1.0),
image::Pixel::rgba(0.3, 0.0, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.1, 0.0, 1.0),
image::Pixel::rgba(0.0, 0.0, 0.2, 1.0),
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),
],
};
let kernel = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]];