first commit

This commit is contained in:
Romulus21 committed 2026-09-30 16:49:11 +02:00
commit 253206e6c5
8 files changed
+2960

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
mod boxes;
mod fetch;
mod ocr;
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::{Context, Result};
use image::{Rgb, RgbImage};
use boxes::{BBox, find_blue_boxes};
use ocr::DigitReader;
const DEBUG_DIR: &str = "debug";
fn main() -> ExitCode {
match run() {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::from(2),
Err(e) => {
eprintln!("error: {e:#}");
ExitCode::FAILURE
}
}
}
/// Returns whether every box could be read.
fn run() -> Result<bool> {
dotenvy::dotenv().ok();
let debug = std::env::args().skip(1).any(|a| a == "--debug");
let url = std::env::var("WATERMETER_URL").context("WATERMETER_URL is not set")?;
let models_dir = std::env::var_os("OCRS_MODELS_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("models"));
let img = fetch::fetch_image(&url)?.into_rgb8();
let boxes: Vec<BBox> = find_blue_boxes(&img)
.iter()
.filter_map(BBox::interior)
.collect();
anyhow::ensure!(!boxes.is_empty(), "no blue box found in image");
let reader = DigitReader::new(&models_dir)?;
let digits = reader.read_boxes(&img, &boxes)?;
if debug {
save_debug(&img, &boxes, &digits)?;
}
let reading: String = digits
.iter()
.map(|d| d.as_deref().unwrap_or("?"))
.collect();
println!("{reading}");
Ok(digits.iter().all(Option::is_some))
}
fn save_debug(img: &RgbImage, boxes: &[BBox], digits: &[Option<String>]) -> Result<()> {
std::fs::create_dir_all(DEBUG_DIR)?;
let mut annotated = img.clone();
for (i, (b, d)) in boxes.iter().zip(digits).enumerate() {
image::imageops::crop_imm(img, b.x, b.y, b.w, b.h)
.to_image()
.save(format!("{DEBUG_DIR}/box_{i}.png"))?;
draw_rect(&mut annotated, b, Rgb([255, 0, 0]));
eprintln!("box {i}: {b:?} -> {}", d.as_deref().unwrap_or("?"));
}
annotated.save(format!("{DEBUG_DIR}/full.png"))?;
Ok(())
}
fn draw_rect(img: &mut RgbImage, b: &BBox, color: Rgb<u8>) {
let (x1, y1) = (b.x + b.w - 1, b.y + b.h - 1);
for x in b.x..=x1 {
img.put_pixel(x, b.y, color);
img.put_pixel(x, y1, color);
}
for y in b.y..=y1 {
img.put_pixel(b.x, y, color);
img.put_pixel(x1, y, color);
}
}