Found the perfect value

This commit is contained in:
Jurn Wubben 2025-10-08 10:59:43 +02:00
parent 66659c61d4
commit 313a3563db
4 changed files with 24 additions and 5 deletions

BIN
out.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

BIN
small.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 475 KiB

View file

@ -1,7 +1,25 @@
use image::{
DynamicImage, GrayImage,
imageops::{self, colorops},
DynamicImage, GrayImage, Luma,
imageops::{self, BiLevel, colorops, colorops::ColorMap, index_colors},
};
struct CustomLevel {
threshold: u8,
}
impl ColorMap for CustomLevel {
type Color = Luma<u8>;
fn index_of(&self, color: &Self::Color) -> usize {
let v = color.0[0];
if v >= self.threshold { 1 } else { 0 }
}
fn map_color(&self, color: &mut Self::Color) {
color.0[0] = if color.0[0] >= self.threshold { 255 } else { 0 };
}
}
pub fn auto_brighten(gray: &mut GrayImage) -> () {
let avg = gray.pixels().map(|p| p.0[0] as u32).sum::<u32>() / gray.len() as u32;
@ -14,7 +32,8 @@ pub fn auto_brighten(gray: &mut GrayImage) -> () {
}
pub fn dither(gray: &mut GrayImage) -> Vec<u8> {
imageops::dither(gray, &imageops::colorops::BiLevel);
let level = CustomLevel { threshold: 175 };
let bw: image::ImageBuffer<Luma<u8>, Vec<u8>> = index_colors(&gray, &level);
let (w, h) = (gray.width() as usize, gray.height() as usize);
let pitch = (w + 7) >> 3;
@ -24,7 +43,7 @@ pub fn dither(gray: &mut GrayImage) -> Vec<u8> {
for x in 0..w {
let byte = y * pitch + (x >> 3);
let bit = 7 - (x & 7);
if gray[(x as u32, y as u32)].0[0] == 0 {
if bw[(x as u32, y as u32)].0[0] == 0 {
bits[byte] |= 1 << bit;
}
}

View file

@ -30,7 +30,7 @@ pub fn escpos_raster(
let img = img.resize(w, h, FilterType::Triangle);
let mut gray = img.to_luma8();
auto_brighten(&mut gray);
// auto_brighten(&mut gray);
let mono = dither(&mut gray);
let (width_px, height_px) = (img.width() as u16, img.height() as u16);