Changed out dithering algorithm and added auto brighting

This commit is contained in:
Jurn Wubben 2025-09-26 13:42:16 +02:00
parent 322a951d51
commit 66659c61d4
4 changed files with 32 additions and 29 deletions

View file

@ -1,35 +1,32 @@
use image::{DynamicImage, imageops};
use image::{
DynamicImage, GrayImage,
imageops::{self, colorops},
};
pub fn auto_brighten(gray: &mut GrayImage) -> () {
let avg = gray.pixels().map(|p| p.0[0] as u32).sum::<u32>() / gray.len() as u32;
pub fn atkinson_mono(img: &DynamicImage) -> Vec<u8> {
let mut gray = img.to_luma8();
imageops::dither(&mut gray, &imageops::colorops::BiLevel);
if avg < 100 {
colorops::brighten_in_place(gray, 40);
colorops::contrast_in_place(gray, 25.0);
} else if avg > 180 {
colorops::brighten_in_place(gray, -15);
}
}
pub fn dither(gray: &mut GrayImage) -> Vec<u8> {
imageops::dither(gray, &imageops::colorops::BiLevel);
let (w, h) = (gray.width() as usize, gray.height() as usize);
let stride = (w + 7) >> 3;
let mut bits = vec![0u8; stride * h];
let pix = gray.as_raw();
let pitch = (w + 7) >> 3;
let mut bits = vec![0u8; pitch * h];
for y in 0..h {
let row_off = y * w;
let bit_off = y * stride;
let chunks = w >> 3;
let tail = w & 7;
for x8 in 0..chunks {
let p = &pix[row_off + (x8 << 3)..][..8];
let mut byte = 0u8;
for (bit, &v) in p.iter().enumerate() {
byte |= ((v < 128) as u8) << (7 - bit);
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 {
bits[byte] |= 1 << bit;
}
bits[bit_off + x8] = byte;
}
if tail != 0 {
let mut last = 0u8;
for (bit, &v) in pix[row_off + (chunks << 3)..][..tail].iter().enumerate() {
last |= ((v < 128) as u8) << (7 - bit);
}
bits[bit_off + chunks] = last;
}
}
bits