ocr 0.1.1

A pure Rust CLI OCR tool for printed text extraction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Tesseract-style text line detection
//!
//! This module implements Tesseract's text line detection algorithms:
//! - TextlineProjection: Projection profile-based line detection
//! - Row making: Grouping blobs into text rows
//! - Baseline fitting: Fitting baselines to rows

use crate::core::geometry::TBox;
use crate::recognition::tesseract_blob::BlobNBox;
use crate::utils::Result;

/// Text line projection (equivalent to Tesseract's TextlineProjection)
///
/// Builds a projection map representing local textline density by smearing
/// connected components horizontally and counting overlaps.
pub struct TextlineProjection {
    /// Scale factor (to achieve ~100 ppi resolution)
    scale_factor: u32,
    /// Projection image (scaled down)
    projection: Vec<Vec<u32>>,
    /// X origin in image coordinates
    x_origin: i32,
    /// Y origin in image coordinates
    y_origin: i32,
    /// Image width
    image_width: u32,
    /// Image height
    image_height: u32,
}

impl TextlineProjection {
    /// Create a new textline projection
    pub fn new(resolution: u32) -> Self {
        // Scale factor to achieve ~100 ppi
        let scale_factor = (resolution / 100).max(1);

        Self {
            scale_factor,
            projection: Vec::new(),
            x_origin: 0,
            y_origin: 0,
            image_width: 0,
            image_height: 0,
        }
    }

    /// Build projection profile from blobs
    pub fn construct_projection(
        &mut self,
        blobs: &[BlobNBox],
        image_width: u32,
        image_height: u32,
    ) -> Result<()> {
        self.image_width = image_width;
        self.image_height = image_height;
        self.x_origin = 0;
        self.y_origin = image_height as i32;

        // Calculate projection dimensions
        let proj_width = (image_width + self.scale_factor - 1) / self.scale_factor;
        let proj_height = (image_height + self.scale_factor - 1) / self.scale_factor;

        // Initialize projection
        self.projection = vec![vec![0; proj_width as usize]; proj_height as usize];

        // Project blobs onto the projection map
        for blob in blobs {
            self.project_blob(blob);
        }

        // Smooth the projection (block convolution)
        self.smooth_projection();

        Ok(())
    }

    /// Project a single blob onto the projection map
    fn project_blob(&mut self, blob: &BlobNBox) {
        let bbox = blob.bounding_box();
        let width = bbox.width() as u32;

        // Project blob horizontally (smear by width)
        let top = self.image_y_to_projection_y(bbox.top() as u32);
        let bottom = self.image_y_to_projection_y(bbox.bottom() as u32);

        for y in bottom..=top {
            if y < self.projection.len() as u32 {
                let left = self.image_x_to_projection_x(bbox.left() as u32);
                let right = self.image_x_to_projection_x(bbox.right() as u32);

                for x in left..=right {
                    if x < self.projection[y as usize].len() as u32 {
                        // Weight by blob width (like Tesseract)
                        self.projection[y as usize][x as usize] += width;
                    }
                }
            }
        }
    }

    /// Smooth projection using block convolution
    fn smooth_projection(&mut self) {
        if self.projection.is_empty() {
            return;
        }

        let height = self.projection.len();
        let width = if height > 0 {
            self.projection[0].len()
        } else {
            0
        };

        // Simple 3x3 box filter (blockconv)
        let mut smoothed = vec![vec![0u32; width]; height];

        for y in 0..height {
            for x in 0..width {
                let mut sum = 0u32;
                let mut count = 0u32;

                for dy in -1..=1 {
                    for dx in -1..=1 {
                        let ny = (y as i32 + dy).max(0).min(height as i32 - 1) as usize;
                        let nx = (x as i32 + dx).max(0).min(width as i32 - 1) as usize;
                        sum += self.projection[ny][nx];
                        count += 1;
                    }
                }

                smoothed[y][x] = if count > 0 { sum / count } else { 0 };
            }
        }

        self.projection = smoothed;
    }

    /// Convert image X coordinate to projection X coordinate
    fn image_x_to_projection_x(&self, x: u32) -> u32 {
        (x / self.scale_factor).min(self.projection[0].len() as u32 - 1)
    }

    /// Convert image Y coordinate to projection Y coordinate
    fn image_y_to_projection_y(&self, y: u32) -> u32 {
        let proj_height = self.projection.len() as u32;
        // Y is inverted (0 at top in image, but we store bottom-up)
        let inverted_y = self.image_height - 1 - y;
        (inverted_y / self.scale_factor).min(proj_height - 1)
    }

    /// Evaluate if a box sits well on a textline
    pub fn evaluate_box(&self, bbox: &TBox) -> i32 {
        // Compute gradients at box edges
        let top_gradient = self.best_mean_gradient_in_row(
            bbox.left() as u32,
            bbox.right() as u32,
            bbox.top() as u32,
            true,
        );
        let bottom_gradient = -self.best_mean_gradient_in_row(
            bbox.left() as u32,
            bbox.right() as u32,
            bbox.bottom() as u32,
            false,
        );
        let left_gradient = self.best_mean_gradient_in_column(
            bbox.left() as u32,
            bbox.bottom() as u32,
            bbox.top() as u32,
            true,
        );
        let right_gradient = -self.best_mean_gradient_in_column(
            bbox.right() as u32,
            bbox.bottom() as u32,
            bbox.top() as u32,
            false,
        );

        // Clamp gradients to non-negative
        let top_clipped = top_gradient.max(0);
        let bottom_clipped = bottom_gradient.max(0);
        let left_clipped = left_gradient.max(0);
        let right_clipped = right_gradient.max(0);

        // Result is max vertical gradient minus max horizontal gradient
        // Positive means blob sits well on a horizontal textline
        std::cmp::max(top_clipped, bottom_clipped) - std::cmp::max(left_clipped, right_clipped)
    }

    /// Find best mean gradient in a horizontal row
    fn best_mean_gradient_in_row(&self, x1: u32, x2: u32, y: u32, increasing: bool) -> i32 {
        let proj_y = self.image_y_to_projection_y(y);
        if proj_y >= self.projection.len() as u32 {
            return 0;
        }

        let proj_x1 = self.image_x_to_projection_x(x1);
        let proj_x2 = self.image_x_to_projection_x(x2);

        if proj_x1 >= self.projection[proj_y as usize].len() as u32
            || proj_x2 >= self.projection[proj_y as usize].len() as u32
        {
            return 0;
        }

        // Sample gradient at multiple offsets
        let mut best_gradient = 0i32;

        for offset in -2..=2 {
            let sample_y = if proj_y as i32 + offset >= 0
                && (proj_y as i32 + offset) < self.projection.len() as i32
            {
                (proj_y as i32 + offset) as usize
            } else {
                continue;
            };

            let mut gradient_sum = 0i32;
            let mut count = 0;

            for x in proj_x1..=proj_x2 {
                if x < self.projection[sample_y].len() as u32 {
                    let value = self.projection[sample_y][x as usize] as i32;
                    if increasing {
                        gradient_sum += value;
                    } else {
                        gradient_sum -= value;
                    }
                    count += 1;
                }
            }

            if count > 0 {
                let gradient = gradient_sum / count as i32;
                if gradient.abs() > best_gradient.abs() {
                    best_gradient = gradient;
                }
            }
        }

        best_gradient
    }

    /// Find best mean gradient in a vertical column
    fn best_mean_gradient_in_column(&self, x: u32, y1: u32, y2: u32, increasing: bool) -> i32 {
        let proj_x = self.image_x_to_projection_x(x);
        if proj_x >= self.projection[0].len() as u32 {
            return 0;
        }

        let proj_y1 = self.image_y_to_projection_y(y1);
        let proj_y2 = self.image_y_to_projection_y(y2);

        let mut gradient_sum = 0i32;
        let mut count = 0;

        let start_y = proj_y1.min(proj_y2);
        let end_y = proj_y1.max(proj_y2);

        for y in start_y..=end_y {
            if y < self.projection.len() as u32 && proj_x < self.projection[y as usize].len() as u32
            {
                let value = self.projection[y as usize][proj_x as usize] as i32;
                if increasing {
                    gradient_sum += value;
                } else {
                    gradient_sum -= value;
                }
                count += 1;
            }
        }

        if count > 0 {
            gradient_sum / count as i32
        } else {
            0
        }
    }

    /// Find peaks in projection (text line centers)
    pub fn find_line_centers(&self, threshold_ratio: f32) -> Vec<u32> {
        if self.projection.is_empty() {
            return Vec::new();
        }

        // Find max value in projection
        let max_value = self
            .projection
            .iter()
            .flat_map(|row| row.iter())
            .max()
            .copied()
            .unwrap_or(0) as f32;

        let threshold = (max_value * threshold_ratio) as u32;

        let mut peaks = Vec::new();
        let height = self.projection.len();

        // Find peaks in each column (vertical projection)
        for x in 0..self.projection[0].len() {
            let mut in_peak = false;
            let mut peak_max = 0u32;
            let mut peak_max_y = 0usize;

            for y in 0..height {
                let value = self.projection[y][x];

                if value >= threshold {
                    if !in_peak {
                        in_peak = true;
                        peak_max = value;
                        peak_max_y = y;
                    } else if value > peak_max {
                        peak_max = value;
                        peak_max_y = y;
                    }
                } else if in_peak {
                    // End of peak
                    let image_y = self.projection_y_to_image_y(peak_max_y as u32);
                    peaks.push(image_y);
                    in_peak = false;
                }
            }

            // Handle peak at end
            if in_peak {
                let image_y = self.projection_y_to_image_y(peak_max_y as u32);
                peaks.push(image_y);
            }
        }

        // Remove duplicates and sort
        peaks.sort();
        peaks.dedup();

        peaks
    }

    /// Convert projection Y coordinate back to image Y coordinate
    fn projection_y_to_image_y(&self, proj_y: u32) -> u32 {
        let inverted_y = proj_y * self.scale_factor;
        self.image_height - 1 - inverted_y
    }
}

/// Text row (equivalent to Tesseract's TO_ROW)
#[derive(Debug, Clone)]
pub struct TextRow {
    /// Blobs in this row
    blobs: Vec<BlobNBox>,
    /// Baseline (y = mx + c)
    baseline_m: f32,
    baseline_c: f32,
    /// Mean blob height
    mean_height: f32,
    /// Line spacing
    line_spacing: f32,
    /// X-height (height of lowercase letters)
    x_height: f32,
}

impl TextRow {
    /// Create a new text row
    pub fn new() -> Self {
        Self {
            blobs: Vec::new(),
            baseline_m: 0.0,
            baseline_c: 0.0,
            mean_height: 0.0,
            line_spacing: 0.0,
            x_height: 0.0,
        }
    }

    /// Add a blob to this row
    pub fn add_blob(&mut self, blob: BlobNBox) {
        self.blobs.push(blob);
    }

    /// Fit baseline using least median squares (LMS)
    pub fn fit_baseline(&mut self) -> Result<()> {
        if self.blobs.is_empty() {
            return Ok(());
        }

        // Collect blob bottom centers
        let mut points = Vec::new();
        for blob in &self.blobs {
            let bbox = blob.bounding_box();
            let x = (bbox.left() + bbox.right()) / 2;
            let y = bbox.bottom();
            points.push((x as f32, y as f32));
        }

        // Simple linear regression for baseline
        let n = points.len() as f32;
        let sum_x: f32 = points.iter().map(|(x, _)| x).sum();
        let sum_y: f32 = points.iter().map(|(_, y)| y).sum();
        let sum_xy: f32 = points.iter().map(|(x, y)| x * y).sum();
        let sum_x2: f32 = points.iter().map(|(x, _)| x * x).sum();

        let denominator = n * sum_x2 - sum_x * sum_x;
        if denominator.abs() < 1e-6 {
            self.baseline_m = 0.0;
            self.baseline_c = sum_y / n;
        } else {
            self.baseline_m = (n * sum_xy - sum_x * sum_y) / denominator;
            self.baseline_c = (sum_y * sum_x2 - sum_x * sum_xy) / denominator;
        }

        // Calculate mean height
        let heights: Vec<f32> = self
            .blobs
            .iter()
            .map(|b| b.bounding_box().height() as f32)
            .collect();
        self.mean_height = heights.iter().sum::<f32>() / heights.len() as f32;

        // Estimate x-height (simplified)
        self.x_height = self.mean_height * 0.7;
        self.line_spacing = self.mean_height * 1.5;

        Ok(())
    }

    /// Get blobs
    pub fn blobs(&self) -> &[BlobNBox] {
        &self.blobs
    }

    /// Get baseline slope
    pub fn baseline_slope(&self) -> f32 {
        self.baseline_m
    }

    /// Get baseline intercept
    pub fn baseline_intercept(&self) -> f32 {
        self.baseline_c
    }

    /// Get mean height
    pub fn mean_height(&self) -> f32 {
        self.mean_height
    }
}

impl Default for TextRow {
    fn default() -> Self {
        Self::new()
    }
}

/// Group blobs into text rows using projection profile method
pub fn group_blobs_into_rows(
    blobs: &[BlobNBox],
    image_width: u32,
    image_height: u32,
) -> Result<Vec<TextRow>> {
    if blobs.is_empty() {
        return Ok(Vec::new());
    }

    // Build projection profile
    let mut projection = TextlineProjection::new(300); // Assume 300 DPI
    projection.construct_projection(blobs, image_width, image_height)?;

    // Find line centers
    let line_centers = projection.find_line_centers(0.3);

    if line_centers.is_empty() {
        // Fallback to simple grouping
        return group_blobs_into_rows_simple(blobs);
    }

    // Group blobs by nearest line center
    let mut rows: Vec<TextRow> = vec![TextRow::new(); line_centers.len()];

    for blob in blobs {
        let bbox = blob.bounding_box();
        let blob_center_y = (bbox.top() + bbox.bottom()) / 2;

        // Find nearest line center
        let mut best_row_idx = 0;
        let mut min_distance = i32::MAX;

        for (idx, &line_y) in line_centers.iter().enumerate() {
            let distance = (blob_center_y - line_y as i32).abs();
            if distance < min_distance {
                min_distance = distance;
                best_row_idx = idx;
            }
        }

        // Check if blob is close enough to the line
        let line_y = line_centers[best_row_idx];
        let blob_height = bbox.height();
        let tolerance = blob_height.max(5) / 2;

        if (blob_center_y - line_y as i32).abs() <= tolerance as i32 {
            rows[best_row_idx].add_blob(blob.clone());
        }
    }

    // Remove empty rows and fit baselines
    let mut result_rows = Vec::new();
    for mut row in rows {
        if !row.blobs().is_empty() {
            // Sort blobs horizontally
            row.blobs
                .sort_by(|a, b| a.bounding_box().left().cmp(&b.bounding_box().left()));
            row.fit_baseline()?;
            result_rows.push(row);
        }
    }

    Ok(result_rows)
}

/// Simple row grouping fallback
fn group_blobs_into_rows_simple(blobs: &[BlobNBox]) -> Result<Vec<TextRow>> {
    if blobs.is_empty() {
        return Ok(Vec::new());
    }

    // Sort blobs by y-position
    let mut sorted_blobs = blobs.to_vec();
    sorted_blobs.sort_by(|a, b| {
        let a_center_y = (a.bounding_box().top() + a.bounding_box().bottom()) / 2;
        let b_center_y = (b.bounding_box().top() + b.bounding_box().bottom()) / 2;
        a_center_y.cmp(&b_center_y)
    });

    // Group blobs into rows
    let mut rows = Vec::new();
    let mut current_row = TextRow::new();
    let mut last_y = None;

    for blob in sorted_blobs {
        let center_y = (blob.bounding_box().top() + blob.bounding_box().bottom()) / 2;
        let height = blob.bounding_box().height();
        let tolerance = height.max(5) / 2;

        if let Some(last_y_pos) = last_y {
            if center_y > last_y_pos + tolerance {
                // New row
                if !current_row.blobs().is_empty() {
                    current_row.fit_baseline()?;
                    rows.push(current_row);
                    current_row = TextRow::new();
                }
            }
        }

        current_row.add_blob(blob);
        last_y = Some(center_y);
    }

    if !current_row.blobs().is_empty() {
        current_row.fit_baseline()?;
        rows.push(current_row);
    }

    Ok(rows)
}