Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[rust] Add OCR text crops and angle classification

laurenspriem927fe4c518a7
diff --git a/rust/crates/ml/examples/ocr.rs b/rust/crates/ml/examples/ocr.rs
index f368d39a35..4ae088696e 100644
--- a/rust/crates/ml/examples/ocr.rs
+++ b/rust/crates/ml/examples/ocr.rs
@@ -9,8 +9,8 @@ use anyhow::{Context, Result, bail};
use ente_assets::AssetStore;
use ente_image::decode::decode_image_from_path;
use ente_ml::ocr::{
- DetectRegionsRequest, OcrEngine, OcrModelPaths, Point, ProbabilityMap, RegionDetectionDebug,
- TextRegion, assets,
+ CropDebug, DetectRegionsRequest, OcrEngine, OcrModelPaths, Orientation, Point, ProbabilityMap,
+ RegionDetectionDebug, TextRegion, assets,
};
use image::{GrayImage, Rgb, RgbImage};
use imageproc::drawing::draw_line_segment_mut;
@@ -99,7 +99,9 @@ fn detect_regions(engine: &OcrEngine, image_path: &str, dump_dir: Option<&Path>)
println!(" {}", format_region(region));
}
if let Some(dir) = dump_dir {
- dump(dir, image_path, &debug)?;
+ let target = dump_target(dir, image_path)?;
+ dump(&target, image_path, &debug)?;
+ dump_crops(engine, image_path, &target)?;
}
Ok(())
}
@@ -114,13 +116,17 @@ fn format_region(region: &TextRegion) -> String {
format!("[{:.3}] {corners}", region.confidence)
}
-fn dump(dir: &Path, image_path: &str, debug: &RegionDetectionDebug) -> Result<()> {
+fn dump_target(dir: &Path, image_path: &str) -> Result<PathBuf> {
let stem = Path::new(image_path)
.file_stem()
.and_then(|stem| stem.to_str())
.with_context(|| format!("no file stem in {image_path}"))?;
let target = dir.join(stem);
std::fs::create_dir_all(&target).with_context(|| format!("create {}", target.display()))?;
+ Ok(target)
+}
+
+fn dump(target: &Path, image_path: &str, debug: &RegionDetectionDebug) -> Result<()> {
probability_map_image(&debug.probability_map)?
.save(target.join("probmap.png"))
.context("write probmap.png")?;
@@ -131,6 +137,62 @@ fn dump(dir: &Path, image_path: &str, debug: &RegionDetectionDebug) -> Result<()
Ok(())
}
+fn dump_crops(engine: &OcrEngine, image_path: &str, target: &Path) -> Result<()> {
+ let debug = engine.detect_and_crop_debug(&DetectRegionsRequest {
+ image_path: image_path.to_string(),
+ request_id: None,
+ })?;
+ let crops_dir = target.join("crops");
+ std::fs::create_dir_all(&crops_dir)
+ .with_context(|| format!("create {}", crops_dir.display()))?;
+ for (index, crop) in debug.crops.iter().enumerate() {
+ println!(" {}", format_crop(index, crop));
+ let name = crop_file_name(index, crop);
+ crop_image(crop)?
+ .save(crops_dir.join(&name))
+ .with_context(|| format!("write {name}"))?;
+ }
+ println!(
+ " wrote {} crops for {} candidates to {}",
+ debug.crops.len(),
+ debug.candidates.len(),
+ crops_dir.display()
+ );
+ Ok(())
+}
+
+fn orientation_label(orientation: Orientation) -> &'static str {
+ match orientation {
+ Orientation::Horizontal => "horizontal",
+ Orientation::Vertical => "vertical",
+ }
+}
+
+fn format_crop(index: usize, crop: &CropDebug) -> String {
+ let rotated = if crop.rotated { " rotated" } else { "" };
+ format!(
+ "{index:03} {}x{} {} p180={:.3}{rotated}",
+ crop.width,
+ crop.height,
+ orientation_label(crop.orientation),
+ crop.p180
+ )
+}
+
+fn crop_file_name(index: usize, crop: &CropDebug) -> String {
+ let rotated = if crop.rotated { "_rot180" } else { "" };
+ format!(
+ "{index:03}_{}_{:.2}{rotated}.png",
+ orientation_label(crop.orientation),
+ crop.p180
+ )
+}
+
+fn crop_image(crop: &CropDebug) -> Result<RgbImage> {
+ RgbImage::from_raw(crop.width, crop.height, crop.rgb.clone())
+ .context("crop size does not match its buffer")
+}
+
fn probability_map_image(map: &ProbabilityMap) -> Result<GrayImage> {
let pixels = map
.values
diff --git a/rust/crates/ml/src/ocr/classify.rs b/rust/crates/ml/src/ocr/classify.rs
new file mode 100644
index 0000000000..759ed4fad3
--- /dev/null
+++ b/rust/crates/ml/src/ocr/classify.rs
@@ -0,0 +1,234 @@
+use std::sync::{Mutex, PoisonError};
+
+use super::tensor::{BgrNormalization, write_bgr_planes};
+use crate::cv;
+use crate::cv::image::ImageU8;
+use crate::error::{MlError, MlResult};
+use crate::onnx::{ExecutionMode, OnnxSession, PreparedF32Input, SessionRunError, run_f32};
+
+const MODEL_NAMESPACE: &str = "ocr-classification";
+const BATCH_SIZE: usize = 6;
+const INPUT_HEIGHT: i32 = 48;
+const INPUT_WIDTH: i32 = 192;
+const CLASS_COUNT: usize = 2;
+const ROTATION_THRESHOLD: f32 = 0.9;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct AngleScores {
+ pub(crate) p0: f32,
+ pub(crate) p180: f32,
+}
+
+impl AngleScores {
+ fn needs_rotation(self) -> bool {
+ self.p180 > self.p0 && self.p180 > ROTATION_THRESHOLD
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct AngleDecision {
+ pub(crate) rotated: bool,
+ pub(crate) scores: AngleScores,
+}
+
+pub(crate) struct AngleClassifier {
+ session: Mutex<OnnxSession>,
+}
+
+impl AngleClassifier {
+ pub(crate) fn new(model_path: &str) -> Self {
+ Self {
+ session: Mutex::new(
+ OnnxSession::new(model_path, MODEL_NAMESPACE, ExecutionMode::CpuAccelerated)
+ .with_unvalidated_acceleration(),
+ ),
+ }
+ }
+
+ pub(crate) fn classify(&self, crops: &mut [ImageU8]) -> MlResult<Vec<AngleDecision>> {
+ classify_in_batches(crops, |batch| self.score_batch(batch))
+ }
+
+ fn score_batch(&self, batch: &[ImageU8]) -> MlResult<Vec<AngleScores>> {
+ let input = PreparedF32Input::new(batch_tensor(batch)?);
+ let count = batch.len() as i64;
+ let expected_shape = [count, CLASS_COUNT as i64];
+ let mut session = self.session.lock().unwrap_or_else(PoisonError::into_inner);
+ let (values, _usage) = session.run(|session| {
+ let (shape, values) = run_f32(
+ session,
+ &input,
+ [count, 3, i64::from(INPUT_HEIGHT), i64::from(INPUT_WIDTH)],
+ )?;
+ if shape != expected_shape {
+ return Err(SessionRunError::from(MlError::CorruptModel(format!(
+ "angle classifier produced output shape {shape:?}, expected {expected_shape:?}"
+ ))));
+ }
+ Ok(values)
+ })?;
+ Ok(values
+ .as_chunks::<CLASS_COUNT>()
+ .0
+ .iter()
+ .map(|&[p0, p180]| AngleScores { p0, p180 })
+ .collect())
+ }
+}
+
+fn classify_in_batches(
+ crops: &mut [ImageU8],
+ mut score_batch: impl FnMut(&[ImageU8]) -> MlResult<Vec<AngleScores>>,
+) -> MlResult<Vec<AngleDecision>> {
+ let mut decisions = Vec::with_capacity(crops.len());
+ for batch in crops.chunks_mut(BATCH_SIZE) {
+ let scores = score_batch(batch)?;
+ if scores.len() != batch.len() {
+ return Err(MlError::CorruptModel(format!(
+ "angle classifier scored {} crops out of {}",
+ scores.len(),
+ batch.len()
+ )));
+ }
+ for (crop, scores) in batch.iter_mut().zip(scores) {
+ decisions.push(apply_decision(crop, scores)?);
+ }
+ }
+ Ok(decisions)
+}
+
+fn apply_decision(crop: &mut ImageU8, scores: AngleScores) -> MlResult<AngleDecision> {
+ let rotated = scores.needs_rotation();
+ if rotated {
+ *crop = cv::rotate_u8(crop, 180).map_err(MlError::Postprocess)?;
+ }
+ Ok(AngleDecision { rotated, scores })
+}
+
+fn batch_tensor(batch: &[ImageU8]) -> MlResult<Vec<f32>> {
+ let plane = (INPUT_WIDTH * INPUT_HEIGHT) as usize;
+ let mut tensor = vec![0.0f32; batch.len() * 3 * plane];
+ for (crop, slot) in batch.iter().zip(tensor.chunks_exact_mut(3 * plane)) {
+ write_crop_planes(crop, slot)?;
+ }
+ Ok(tensor)
+}
+
+fn write_crop_planes(crop: &ImageU8, slot: &mut [f32]) -> MlResult<()> {
+ let width = resized_width(crop.width, crop.height);
+ let resized = cv::resize_u8(crop, width, INPUT_HEIGHT, cv::Interp::Bilinear)
+ .map_err(MlError::Preprocess)?;
+ write_bgr_planes(
+ &resized,
+ slot,
+ INPUT_WIDTH as usize,
+ BgrNormalization::CENTERED,
+ )
+}
+
+fn resized_width(width: i32, height: i32) -> i32 {
+ let scaled = (INPUT_HEIGHT as f32 * width as f32 / height as f32).ceil() as i32;
+ scaled.min(INPUT_WIDTH)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn solid(width: i32, height: i32, rgb: [u8; 3]) -> ImageU8 {
+ let data = std::iter::repeat_n(rgb, (width * height) as usize)
+ .flatten()
+ .collect();
+ ImageU8::new(width, height, 3, data).unwrap()
+ }
+
+ fn scores(p0: f32, p180: f32) -> AngleScores {
+ AngleScores { p0, p180 }
+ }
+
+ #[test]
+ fn a_crop_narrower_than_the_input_is_left_aligned_and_zero_padded_per_plane() {
+ let crop = solid(100, 48, [10, 20, 30]);
+ let plane = (INPUT_WIDTH * INPUT_HEIGHT) as usize;
+
+ let tensor = batch_tensor(std::slice::from_ref(&crop)).unwrap();
+
+ assert_eq!(tensor.len(), 3 * plane);
+ let centered = |value: f32| (value / 255.0 - 0.5) / 0.5;
+ let expected = [centered(30.0), centered(20.0), centered(10.0)];
+ for (channel, expected) in expected.into_iter().enumerate() {
+ let values = &tensor[channel * plane..(channel + 1) * plane];
+ for y in 0..INPUT_HEIGHT as usize {
+ let row = &values[y * INPUT_WIDTH as usize..(y + 1) * INPUT_WIDTH as usize];
+ assert!(
+ row[..100].iter().all(|&v| (v - expected).abs() <= 1e-6),
+ "channel {channel} row {y} content"
+ );
+ assert!(
+ row[100..].iter().all(|&v| v == 0.0),
+ "channel {channel} row {y} padding"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn resized_width_scales_to_the_input_height_and_caps_at_the_input_width() {
+ assert_eq!(resized_width(100, 48), 100);
+ assert_eq!(resized_width(50, 24), 100);
+ assert_eq!(resized_width(1000, 48), INPUT_WIDTH);
+ assert_eq!(resized_width(10, 48), 10);
+ assert_eq!(resized_width(1, 4096), 1);
+ assert_eq!(resized_width(7, 3), 112);
+ }
+
+ #[test]
+ fn rotation_needs_the_flipped_class_to_win_with_high_confidence() {
+ assert!(!scores(0.95, 0.05).needs_rotation());
+ assert!(scores(0.05, 0.95).needs_rotation());
+ assert!(!scores(0.15, 0.85).needs_rotation());
+ }
+
+ #[test]
+ fn decisions_rotate_only_flagged_crops_in_place() {
+ let mut crop = ImageU8::new(2, 1, 3, vec![1, 2, 3, 4, 5, 6]).unwrap();
+
+ let kept = apply_decision(&mut crop, scores(0.8, 0.2)).unwrap();
+ assert!(!kept.rotated);
+ assert_eq!(crop.data, [1, 2, 3, 4, 5, 6]);
+
+ let flipped = apply_decision(&mut crop, scores(0.02, 0.98)).unwrap();
+ assert!(flipped.rotated);
+ assert_eq!(flipped.scores, scores(0.02, 0.98));
+ assert_eq!(crop.data, [4, 5, 6, 1, 2, 3]);
+ }
+
+ #[test]
+ fn seven_crops_are_scored_in_two_ordered_batches() {
+ let mut crops: Vec<ImageU8> = (1..=7).map(|w| solid(w, 1, [w as u8; 3])).collect();
+ let mut batch_sizes = Vec::new();
+
+ let decisions = classify_in_batches(&mut crops, |batch| {
+ batch_sizes.push(batch.len());
+ Ok(batch
+ .iter()
+ .map(|crop| scores(1.0 - crop.width as f32 / 100.0, crop.width as f32 / 100.0))
+ .collect())
+ })
+ .unwrap();
+
+ assert_eq!(batch_sizes, [6, 1]);
+ let p180: Vec<f32> = decisions.iter().map(|d| d.scores.p180).collect();
+ assert_eq!(p180, [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]);
+ assert!(decisions.iter().all(|d| !d.rotated));
+ }
+
+ #[test]
+ fn a_short_score_list_is_reported_as_a_corrupt_model() {
+ let mut crops = vec![solid(4, 4, [0; 3]), solid(4, 4, [0; 3])];
+
+ let error = classify_in_batches(&mut crops, |_| Ok(vec![scores(1.0, 0.0)])).unwrap_err();
+
+ assert!(matches!(error, MlError::CorruptModel(_)), "{error}");
+ }
+}
diff --git a/rust/crates/ml/src/ocr/crop.rs b/rust/crates/ml/src/ocr/crop.rs
new file mode 100644
index 0000000000..d2ddaea64f
--- /dev/null
+++ b/rust/crates/ml/src/ocr/crop.rs
@@ -0,0 +1,177 @@
+use super::Point;
+use crate::cv;
+use crate::cv::image::ImageU8;
+use crate::error::{MlError, MlResult};
+
+const VERTICAL_ASPECT: f32 = 1.5;
+const COUNTER_CLOCKWISE_DEGREES: i32 = 270;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Orientation {
+ Horizontal,
+ Vertical,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct TextCrop {
+ pub(crate) image: ImageU8,
+ pub(crate) orientation: Orientation,
+}
+
+pub(crate) fn crop_text(working: &ImageU8, quad: &[Point; 4]) -> MlResult<TextCrop> {
+ let (width, height) = crop_size(quad);
+ let warped = warp_to_rectangle(working, quad, width, height)?;
+ if is_vertical(width, height) {
+ Ok(TextCrop {
+ image: rotate_counter_clockwise(&warped)?,
+ orientation: Orientation::Vertical,
+ })
+ } else {
+ Ok(TextCrop {
+ image: warped,
+ orientation: Orientation::Horizontal,
+ })
+ }
+}
+
+pub(crate) fn crop_size(quad: &[Point; 4]) -> (i32, i32) {
+ let [tl, tr, br, bl] = *quad;
+ let width = tl.distance(tr).max(bl.distance(br));
+ let height = tl.distance(bl).max(tr.distance(br));
+ (truncated_side(width), truncated_side(height))
+}
+
+fn truncated_side(length: f32) -> i32 {
+ (length.trunc() as i32).max(1)
+}
+
+fn is_vertical(width: i32, height: i32) -> bool {
+ height as f32 / width as f32 >= VERTICAL_ASPECT
+}
+
+fn warp_to_rectangle(
+ working: &ImageU8,
+ quad: &[Point; 4],
+ width: i32,
+ height: i32,
+) -> MlResult<ImageU8> {
+ let source_corners = quad.map(|p| (f64::from(p.x), f64::from(p.y)));
+ let (w, h) = (f64::from(width), f64::from(height));
+ let target_corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)];
+ cv::warp_perspective(working, source_corners, target_corners, width, height)
+ .map_err(MlError::Preprocess)
+}
+
+fn rotate_counter_clockwise(image: &ImageU8) -> MlResult<ImageU8> {
+ cv::rotate_u8(image, COUNTER_CLOCKWISE_DEGREES).map_err(MlError::Preprocess)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn quad(points: [(f32, f32); 4]) -> [Point; 4] {
+ points.map(|(x, y)| Point::new(x, y))
+ }
+
+ fn gradient_image(width: i32, height: i32) -> ImageU8 {
+ let data = (0..height)
+ .flat_map(|y| (0..width).flat_map(move |x| [x as u8, y as u8, (x + y) as u8]))
+ .collect();
+ ImageU8::new(width, height, 3, data).unwrap()
+ }
+
+ fn pixel(image: &ImageU8, x: i32, y: i32) -> [u8; 3] {
+ let offset = ((y * image.width + x) * 3) as usize;
+ [
+ image.data[offset],
+ image.data[offset + 1],
+ image.data[offset + 2],
+ ]
+ }
+
+ #[test]
+ fn crop_size_truncates_the_longer_opposite_edges() {
+ let size = crop_size(&quad([
+ (10.0, 10.0),
+ (110.7, 10.0),
+ (110.7, 30.2),
+ (10.0, 29.5),
+ ]));
+ assert_eq!(size, (100, 20));
+ }
+
+ #[test]
+ fn crop_size_never_collapses_below_one_pixel() {
+ let size = crop_size(&quad([(5.0, 5.0), (5.4, 5.0), (5.4, 5.3), (5.0, 5.3)]));
+ assert_eq!(size, (1, 1));
+ }
+
+ #[test]
+ fn axis_aligned_crop_reproduces_the_source_pixels() {
+ let source = gradient_image(40, 30);
+ let crop = crop_text(
+ &source,
+ &quad([(8.0, 5.0), (28.0, 5.0), (28.0, 17.0), (8.0, 17.0)]),
+ )
+ .unwrap();
+ assert_eq!(crop.orientation, Orientation::Horizontal);
+ assert_eq!((crop.image.width, crop.image.height), (20, 12));
+ for y in 0..12 {
+ for x in 0..20 {
+ assert_eq!(
+ pixel(&crop.image, x, y),
+ pixel(&source, x + 8, y + 5),
+ "pixel ({x}, {y})"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn tall_crop_is_rotated_so_its_right_edge_becomes_the_top() {
+ let source = gradient_image(40, 60);
+ let crop = crop_text(
+ &source,
+ &quad([(4.0, 2.0), (6.0, 2.0), (6.0, 5.0), (4.0, 5.0)]),
+ )
+ .unwrap();
+ assert_eq!(crop.orientation, Orientation::Vertical);
+ assert_eq!((crop.image.width, crop.image.height), (3, 2));
+ assert_eq!(pixel(&crop.image, 0, 0), pixel(&source, 5, 2));
+ assert_eq!(pixel(&crop.image, 2, 0), pixel(&source, 5, 4));
+ assert_eq!(pixel(&crop.image, 0, 1), pixel(&source, 4, 2));
+ assert_eq!(pixel(&crop.image, 2, 1), pixel(&source, 4, 4));
+ }
+
+ #[test]
+ fn aspect_of_exactly_one_and_a_half_counts_as_vertical() {
+ assert!(is_vertical(2, 3));
+ assert!(!is_vertical(3, 4));
+ assert!(!is_vertical(1, 1));
+ }
+
+ #[test]
+ fn counter_clockwise_rotation_moves_the_top_right_corner_to_the_top_left() {
+ let [a, b, c, d, e, f] = [1u8, 2, 3, 4, 5, 6];
+ let source = ImageU8::new(
+ 2,
+ 3,
+ 3,
+ [a, b, c, d, e, f].iter().flat_map(|&v| [v, v, v]).collect(),
+ )
+ .unwrap();
+
+ let rotated = rotate_counter_clockwise(&source).unwrap();
+
+ assert_eq!((rotated.width, rotated.height), (3, 2));
+ let values: Vec<u8> = rotated
+ .data
+ .as_chunks::<3>()
+ .0
+ .iter()
+ .map(|px| px[0])
+ .collect();
+ assert_eq!(values, [b, d, f, a, c, e]);
+ }
+}
diff --git a/rust/crates/ml/src/ocr/detect.rs b/rust/crates/ml/src/ocr/detect.rs
index 896cfae879..6f7e1561ce 100644
--- a/rust/crates/ml/src/ocr/detect.rs
+++ b/rust/crates/ml/src/ocr/detect.rs
@@ -4,6 +4,7 @@ use super::Point;
use super::geometry::{
clip_to_bounds, mean_inside_quad, min_area_rect, min_edge, order_corners, scale_points, unclip,
};
+use super::tensor::{BgrNormalization, write_bgr_planes};
use crate::cv;
use crate::cv::image::{Contour, ImageU8};
use crate::error::{MlError, MlResult};
@@ -12,8 +13,6 @@ use crate::onnx::{ExecutionMode, OnnxSession, PreparedF32Input, SessionRunError,
const MODEL_NAMESPACE: &str = "ocr-detection";
const MAX_INPUT_SIDE: i32 = 960;
const INPUT_STRIDE: i32 = 32;
-const CHANNEL_MEAN_BGR: [f32; 3] = [0.485, 0.456, 0.406];
-const CHANNEL_STD_BGR: [f32; 3] = [0.229, 0.224, 0.225];
const BITMAP_THRESHOLD: f32 = 0.3;
const BOX_SCORE_THRESHOLD: f32 = 0.6;
const UNCLIP_RATIO: f32 = 1.5;
@@ -58,7 +57,7 @@ impl TextDetector {
let (input_width, input_height) = detector_input_size(working.width, working.height);
let resized = cv::resize_u8(working, input_width, input_height, cv::Interp::Bilinear)
.map_err(MlError::Preprocess)?;
- let input = PreparedF32Input::new(normalized_bgr_planes(&resized));
+ let input = PreparedF32Input::new(normalized_bgr_planes(&resized)?);
let values = self.infer(&input, input_width, input_height)?;
let probability_map = ProbabilityMap {
width: input_width as usize,
@@ -114,20 +113,15 @@ fn rounded_to_stride(side: f64) -> i32 {
((side.trunc() / stride).round_ties_even() as i32 * INPUT_STRIDE).max(INPUT_STRIDE)
}
-fn normalized_bgr_planes(rgb: &ImageU8) -> Vec<f32> {
- let pixels = rgb.width as usize * rgb.height as usize;
- let mut planes = vec![0.0f32; pixels * 3];
- let (blue, rest) = planes.split_at_mut(pixels);
- let (green, red) = rest.split_at_mut(pixels);
- let normalize = |channel: usize, value: u8| {
- (value as f32 / 255.0 - CHANNEL_MEAN_BGR[channel]) / CHANNEL_STD_BGR[channel]
- };
- for (index, px) in rgb.data.as_chunks::<3>().0.iter().enumerate() {
- blue[index] = normalize(0, px[2]);
- green[index] = normalize(1, px[1]);
- red[index] = normalize(2, px[0]);
- }
- planes
+fn normalized_bgr_planes(rgb: &ImageU8) -> MlResult<Vec<f32>> {
+ let mut planes = vec![0.0f32; rgb.width as usize * rgb.height as usize * 3];
+ write_bgr_planes(
+ rgb,
+ &mut planes,
+ rgb.width as usize,
+ BgrNormalization::IMAGENET,
+ )?;
+ Ok(planes)
}
impl DetectionCandidate {
@@ -466,7 +460,7 @@ mod tests {
#[test]
fn detector_planes_are_bgr_and_normalised_per_channel() {
let pixel = ImageU8::new(1, 1, 3, vec![10, 20, 30]).unwrap();
- let planes = normalized_bgr_planes(&pixel);
+ let planes = normalized_bgr_planes(&pixel).unwrap();
let expected = [
(30.0 / 255.0 - 0.485) / 0.229,
(20.0 / 255.0 - 0.456) / 0.224,
@@ -481,7 +475,7 @@ mod tests {
#[test]
fn detector_planes_are_laid_out_plane_by_plane() {
let two_pixels = ImageU8::new(2, 1, 3, vec![255, 0, 0, 0, 0, 255]).unwrap();
- let planes = normalized_bgr_planes(&two_pixels);
+ let planes = normalized_bgr_planes(&two_pixels).unwrap();
let blue_of = |value: f32| (value / 255.0 - 0.485) / 0.229;
let red_of = |value: f32| (value / 255.0 - 0.406) / 0.225;
assert!((planes[0] - blue_of(0.0)).abs() <= 1e-6);
diff --git a/rust/crates/ml/src/ocr/mod.rs b/rust/crates/ml/src/ocr/mod.rs
index 5c8c69cc26..fb6ae9bfe4 100644
--- a/rust/crates/ml/src/ocr/mod.rs
+++ b/rust/crates/ml/src/ocr/mod.rs
@@ -1,10 +1,14 @@
pub mod assets;
mod cancel;
+mod classify;
+mod crop;
mod detect;
mod dictionary;
mod geometry;
mod source;
+mod tensor;
+pub use crop::Orientation;
pub use detect::ProbabilityMap;
pub use dictionary::load_dictionary;
pub use geometry::Point;
@@ -14,10 +18,13 @@ use std::time::Instant;
use thiserror::Error;
use cancel::RequestRegistry;
+use classify::{AngleClassifier, AngleDecision};
+use crop::crop_text;
use detect::{DetectionCandidate, TextDetector};
use geometry::scale_points;
use source::{REGIONS_CAP, SourceImage, load_source};
+use crate::cv::image::ImageU8;
use crate::error::{MlError, MlResult};
const REGION_MIN_SCORE: f32 = 0.5;
@@ -87,6 +94,25 @@ pub struct RegionDetectionDebug {
pub probability_map: ProbabilityMap,
}
+#[derive(Clone, Debug, PartialEq)]
+pub struct CropDebug {
+ pub width: u32,
+ pub height: u32,
+ pub rgb: Vec<u8>,
+ pub orientation: Orientation,
+ pub rotated: bool,
+ pub p0: f32,
+ pub p180: f32,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct CropDetectionDebug {
+ pub image_width: u32,
+ pub image_height: u32,
+ pub candidates: Vec<TextRegion>,
+ pub crops: Vec<CropDebug>,
+}
+
#[derive(Debug, Error)]
pub enum OcrError {
#[error("image not found: {0}")]
@@ -99,6 +125,7 @@ pub enum OcrError {
pub struct OcrEngine {
detector: TextDetector,
+ classifier: Option<AngleClassifier>,
requests: RequestRegistry,
}
@@ -109,12 +136,21 @@ impl OcrEngine {
"OCR detection model path is empty".to_string(),
));
}
+ let classifier =
+ (!paths.classification.is_empty()).then(|| AngleClassifier::new(&paths.classification));
Ok(Self {
detector: TextDetector::new(&paths.detection),
+ classifier,
requests: RequestRegistry::default(),
})
}
+ fn classifier(&self) -> MlResult<&AngleClassifier> {
+ self.classifier.as_ref().ok_or_else(|| {
+ MlError::InvalidRequest("OCR classification model path is empty".to_string())
+ })
+ }
+
pub fn detect_text_regions(
&self,
req: &DetectRegionsRequest,
@@ -158,28 +194,112 @@ impl OcrEngine {
})
}
+ pub fn detect_and_crop_debug(
+ &self,
+ req: &DetectRegionsRequest,
+ ) -> Result<CropDetectionDebug, OcrError> {
+ let classifier = self.classifier()?;
+ let started = Instant::now();
+ let request = self.requests.begin(req.request_id.as_deref());
+ let source = load_source(&req.image_path, REGIONS_CAP)?;
+ request.check()?;
+ let detection_started = Instant::now();
+ let detection = self.detector.detect(&source.working)?;
+ let detection_ms = detection_started.elapsed().as_millis();
+ request.check()?;
+ let (mut images, orientations) = crop_candidates(&source.working, &detection.candidates)?;
+ request.check()?;
+ let classification_started = Instant::now();
+ let decisions = classifier.classify(&mut images)?;
+ let classification_ms = classification_started.elapsed().as_millis();
+ request.check()?;
+ let crops = crop_debug_entries(images, orientations, &decisions);
+ log::info!(
+ "ocr detect_and_crop_debug: {}x{} -> {}x{}, det {} boxes in {detection_ms}ms, cls {} crops in {classification_ms}ms, rotated {}, total {}ms",
+ source.decoded_width,
+ source.decoded_height,
+ source.working.width,
+ source.working.height,
+ detection.candidates.len(),
+ crops.len(),
+ decisions.iter().filter(|d| d.rotated).count(),
+ started.elapsed().as_millis()
+ );
+ Ok(CropDetectionDebug {
+ image_width: source.decoded_width,
+ image_height: source.decoded_height,
+ candidates: candidates_in_decoded_pixels(&detection.candidates, &source),
+ crops,
+ })
+ }
+
pub fn cancel(&self, request_id: &str) {
self.requests.cancel(request_id);
}
}
+fn crop_candidates(
+ working: &ImageU8,
+ candidates: &[DetectionCandidate],
+) -> MlResult<(Vec<ImageU8>, Vec<Orientation>)> {
+ candidates
+ .iter()
+ .map(|candidate| {
+ crop_text(working, &candidate.points).map(|crop| (crop.image, crop.orientation))
+ })
+ .collect()
+}
+
+fn crop_debug_entries(
+ images: Vec<ImageU8>,
+ orientations: Vec<Orientation>,
+ decisions: &[AngleDecision],
+) -> Vec<CropDebug> {
+ images
+ .into_iter()
+ .zip(orientations)
+ .zip(decisions)
+ .map(|((image, orientation), decision)| CropDebug {
+ width: image.width as u32,
+ height: image.height as u32,
+ rgb: image.data,
+ orientation,
+ rotated: decision.rotated,
+ p0: decision.scores.p0,
+ p180: decision.scores.p180,
+ })
+ .collect()
+}
+
fn regions_in_decoded_pixels(
candidates: &[DetectionCandidate],
source: &SourceImage,
) -> Vec<TextRegion> {
- let scale_x = source.decoded_width as f32 / source.working.width as f32;
- let scale_y = source.decoded_height as f32 / source.working.height as f32;
+ let to_region = decoded_region_of(source);
candidates
.iter()
.filter(|candidate| candidate.score >= REGION_MIN_SCORE)
.take(MAX_REGIONS)
- .map(|candidate| TextRegion {
- confidence: candidate.score,
- points: scale_points(&candidate.points, scale_x, scale_y),
- })
+ .map(to_region)
.collect()
}
+fn candidates_in_decoded_pixels(
+ candidates: &[DetectionCandidate],
+ source: &SourceImage,
+) -> Vec<TextRegion> {
+ candidates.iter().map(decoded_region_of(source)).collect()
+}
+
+fn decoded_region_of(source: &SourceImage) -> impl Fn(&DetectionCandidate) -> TextRegion {
+ let scale_x = source.decoded_width as f32 / source.working.width as f32;
+ let scale_y = source.decoded_height as f32 / source.working.height as f32;
+ move |candidate| TextRegion {
+ confidence: candidate.score,
+ points: scale_points(&candidate.points, scale_x, scale_y),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/crates/ml/src/ocr/tensor.rs b/rust/crates/ml/src/ocr/tensor.rs
new file mode 100644
index 0000000000..aa8d6bdeba
--- /dev/null
+++ b/rust/crates/ml/src/ocr/tensor.rs
@@ -0,0 +1,130 @@
+use crate::cv::image::ImageU8;
+use crate::error::{MlError, MlResult};
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct BgrNormalization {
+ mean: [f32; 3],
+ std: [f32; 3],
+}
+
+impl BgrNormalization {
+ pub(crate) const IMAGENET: Self = Self {
+ mean: [0.485, 0.456, 0.406],
+ std: [0.229, 0.224, 0.225],
+ };
+
+ pub(crate) const CENTERED: Self = Self {
+ mean: [0.5; 3],
+ std: [0.5; 3],
+ };
+
+ fn apply(self, channel: usize, value: u8) -> f32 {
+ (value as f32 / 255.0 - self.mean[channel]) / self.std[channel]
+ }
+}
+
+pub(crate) fn write_bgr_planes(
+ rgb: &ImageU8,
+ planes: &mut [f32],
+ plane_width: usize,
+ normalization: BgrNormalization,
+) -> MlResult<()> {
+ let width = rgb.width as usize;
+ let height = rgb.height as usize;
+ let plane = plane_width * height;
+ if rgb.channels != 3 || width > plane_width || planes.len() != 3 * plane {
+ return Err(MlError::Preprocess(format!(
+ "cannot write a {width}x{height}x{} image into {} values as {plane_width}-wide BGR planes",
+ rgb.channels,
+ planes.len()
+ )));
+ }
+ let (blue, rest) = planes.split_at_mut(plane);
+ let (green, red) = rest.split_at_mut(plane);
+ for (y, row) in rgb.data.chunks_exact(width * 3).enumerate() {
+ let offset = y * plane_width;
+ for (x, px) in row.as_chunks::<3>().0.iter().enumerate() {
+ blue[offset + x] = normalization.apply(0, px[2]);
+ green[offset + x] = normalization.apply(1, px[1]);
+ red[offset + x] = normalization.apply(2, px[0]);
+ }
+ let padding = offset + width..offset + plane_width;
+ blue[padding.clone()].fill(0.0);
+ green[padding.clone()].fill(0.0);
+ red[padding].fill(0.0);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn centered(value: u8) -> f32 {
+ (value as f32 / 255.0 - 0.5) / 0.5
+ }
+
+ #[test]
+ fn planes_are_bgr_left_aligned_per_row_and_zero_padded() {
+ let rgb = ImageU8::new(
+ 2,
+ 2,
+ 3,
+ vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
+ )
+ .unwrap();
+ let mut planes = vec![f32::NAN; 3 * 3 * 2];
+
+ write_bgr_planes(&rgb, &mut planes, 3, BgrNormalization::CENTERED).unwrap();
+
+ let expected = [
+ [30, 60, 0, 90, 120, 0],
+ [20, 50, 0, 80, 110, 0],
+ [10, 40, 0, 70, 100, 0],
+ ];
+ for (channel, values) in expected.into_iter().enumerate() {
+ for (x, value) in values.into_iter().enumerate() {
+ let expected = if x % 3 == 2 { 0.0 } else { centered(value) };
+ let actual = planes[channel * 6 + x];
+ assert!(
+ (actual - expected).abs() <= 1e-6,
+ "channel {channel} index {x}: {actual} != {expected}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn imagenet_normalization_uses_the_bgr_channel_statistics() {
+ let rgb = ImageU8::new(1, 1, 3, vec![10, 20, 30]).unwrap();
+ let mut planes = vec![0.0f32; 3];
+
+ write_bgr_planes(&rgb, &mut planes, 1, BgrNormalization::IMAGENET).unwrap();
+
+ let expected = [
+ (30.0 / 255.0 - 0.485) / 0.229,
+ (20.0 / 255.0 - 0.456) / 0.224,
+ (10.0 / 255.0 - 0.406) / 0.225,
+ ];
+ for (actual, expected) in planes.iter().zip(expected) {
+ assert!((actual - expected).abs() <= 1e-6, "{planes:?}");
+ }
+ }
+
+ #[test]
+ fn images_that_do_not_fit_the_planes_are_rejected() {
+ let rgb = ImageU8::new(4, 1, 3, vec![0; 12]).unwrap();
+ let mut planes = vec![0.0f32; 3 * 3];
+
+ let too_wide = write_bgr_planes(&rgb, &mut planes, 3, BgrNormalization::CENTERED);
+ assert!(matches!(too_wide, Err(MlError::Preprocess(_))));
+
+ let too_short = write_bgr_planes(&rgb, &mut planes, 4, BgrNormalization::CENTERED);
+ assert!(matches!(too_short, Err(MlError::Preprocess(_))));
+
+ let gray = ImageU8::new(1, 1, 1, vec![0]).unwrap();
+ let wrong_channels =
+ write_bgr_planes(&gray, &mut planes[..3], 1, BgrNormalization::CENTERED);
+ assert!(matches!(wrong_channels, Err(MlError::Preprocess(_))));
+ }
+}