small improvements

This commit is contained in:
Sander Hautvast 2022-01-27 17:34:36 +01:00
parent 9e42ad0f36
commit 76a555596c
3 changed files with 18 additions and 28 deletions

2
Cargo.lock generated
View file

@ -371,7 +371,7 @@ dependencies = [
] ]
[[package]] [[package]]
name = "octo" name = "octtreequantizer"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"image", "image",

View file

@ -1,5 +1,5 @@
[package] [package]
name = "octo" name = "octtreequantizer"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
@ -8,6 +8,3 @@ edition = "2021"
[dependencies] [dependencies]
image="0.23.14" image="0.23.14"
imageproc="0.22.0" imageproc="0.22.0"
[profile.release]
debug = true

View file

@ -1,6 +1,6 @@
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use image::{GenericImageView, Pixel, RgbImage, Rgb}; use image::{Pixel, Rgb, RgbImage};
use imageproc::definitions::Image; use imageproc::definitions::Image;
const MAX_LEVEL: usize = 5; const MAX_LEVEL: usize = 5;
@ -41,37 +41,30 @@ impl OctTreeQuantizer {
where where
P: Pixel<Subpixel = u8> + 'static, P: Pixel<Subpixel = u8> + 'static,
{ {
for y in 0..image.height() { for pixel in image.pixels() {
for x in 0..image.width() { self.insert_color(pixel, Rc::clone(&self.root));
let p = image.get_pixel(x, y);
self.insert_color(p, Rc::clone(&self.root));
if self.colors > self.reduce_colors { if self.colors > self.reduce_colors {
self.reduce_tree(self.reduce_colors); self.reduce_tree(self.reduce_colors);
//reduce sets to None and the code below actually removes nodes from the list //reduce sets to None and the code below actually removes nodes from the list
for level in &mut self.color_list { for level in &mut self.color_list {
level.retain(|c| c.is_some()); level.retain(|c| c.is_some());
}
} }
} }
} }
let table = self.build_color_table(); let table = self.build_color_table();
let mut out = RgbImage::new(image.width(), image.height()); let mut imgbuf = RgbImage::new(image.width(), image.height());
for y in 0..image.height() { for (x, y, pixel) in image.enumerate_pixels() {
for x in 0..image.width() { if let Some(index) = self.get_index_for_color(pixel, &self.root) {
unsafe { //safe because bounds are checked let color = &table[index];
let pixel = image.unsafe_get_pixel(x, y); if let Some(color) = color {
if let Some(index) = self.get_index_for_color(&pixel, &self.root) { imgbuf.put_pixel(x, y, *color);
let color = table.get(index).unwrap();
if let Some(color) = color {
out.put_pixel(x, y, *color);
}
}
} }
} }
} }
out
imgbuf
} }
fn get_index_for_color<P>(&self, color: &P, node: &Rc<RefCell<OctTreeNode>>) -> Option<usize> fn get_index_for_color<P>(&self, color: &P, node: &Rc<RefCell<OctTreeNode>>) -> Option<usize>