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
//! Tesseract-style blob detection and analysis
//!
//! This module implements Tesseract's blob detection algorithms:
//! - C_OUTLINE: Chain-coded outlines
//! - TBLOB: Text blobs with outlines
//! - BLOBNBOX: Blob bounding boxes with analysis

use crate::core::geometry::{ICoord, TBox};
use crate::utils::Result;
use image::GrayImage;

/// Direction codes for chain coding (4-directional)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainDir {
    Left = 0,  // (-1, 0)
    Up = 1,    // (0, -1)
    Right = 2, // (1, 0)
    Down = 3,  // (0, 1)
}

impl ChainDir {
    /// Convert to coordinate offset
    pub fn to_offset(self) -> (i32, i32) {
        match self {
            ChainDir::Left => (-1, 0),
            ChainDir::Up => (0, -1),
            ChainDir::Right => (1, 0),
            ChainDir::Down => (0, 1),
        }
    }

    /// Get direction from offset
    pub fn from_offset(dx: i32, dy: i32) -> Option<Self> {
        match (dx, dy) {
            (-1, 0) => Some(ChainDir::Left),
            (0, -1) => Some(ChainDir::Up),
            (1, 0) => Some(ChainDir::Right),
            (0, 1) => Some(ChainDir::Down),
            _ => None,
        }
    }
}

/// Chain-coded outline (equivalent to Tesseract's C_OUTLINE)
#[derive(Debug, Clone)]
pub struct ChainOutline {
    /// Starting position
    pub start: ICoord,
    /// Chain code steps (4-directional)
    pub steps: Vec<ChainDir>,
    /// Bounding box
    pub bounding_box: TBox,
    /// Child outlines (holes)
    pub children: Vec<ChainOutline>,
    /// Is this an inverse outline (white on black)?
    pub is_inverse: bool,
}

impl ChainOutline {
    /// Create a new chain outline
    pub fn new(start: ICoord, steps: Vec<ChainDir>, is_inverse: bool) -> Self {
        let mut bbox = TBox::new(start.x, start.y, start.x, start.y);
        let mut pos = start;

        for &step in &steps {
            let (dx, dy) = step.to_offset();
            pos = ICoord::new(pos.x + dx, pos.y + dy);
            bbox = bbox.union(&TBox::new(pos.x, pos.y, pos.x, pos.y));
        }

        Self {
            start,
            steps,
            bounding_box: bbox,
            children: Vec::new(),
            is_inverse,
        }
    }

    /// Get bounding box
    pub fn bounding_box(&self) -> &TBox {
        &self.bounding_box
    }

    /// Get path length
    pub fn path_length(&self) -> usize {
        self.steps.len()
    }

    /// Get perimeter
    pub fn perimeter(&self) -> f32 {
        self.steps.len() as f32
    }

    /// Get area (using shoelace formula)
    pub fn area(&self) -> f32 {
        if self.steps.len() < 3 {
            return 0.0;
        }

        let mut area = 0.0;
        let mut pos = self.start;

        for &step in &self.steps {
            let next_pos = {
                let (dx, dy) = step.to_offset();
                ICoord::new(pos.x + dx, pos.y + dy)
            };

            // Shoelace formula
            area += (pos.x as f32) * (next_pos.y as f32);
            area -= (next_pos.x as f32) * (pos.y as f32);

            pos = next_pos;
        }

        area.abs() / 2.0
    }

    /// Add child outline (hole)
    pub fn add_child(&mut self, child: ChainOutline) {
        self.children.push(child);
    }
}

/// Text blob with outlines (equivalent to Tesseract's TBLOB)
#[derive(Debug, Clone)]
pub struct TBlob {
    /// Outer outlines
    outlines: Vec<ChainOutline>,
    /// Bounding box
    bounding_box: TBox,
}

impl TBlob {
    /// Create a new blob from outlines
    pub fn new(outlines: Vec<ChainOutline>) -> Self {
        let mut bbox = if let Some(first) = outlines.first() {
            first.bounding_box().clone()
        } else {
            TBox::new(0, 0, 0, 0)
        };

        for outline in &outlines {
            bbox = bbox.union(outline.bounding_box());
        }

        Self {
            outlines,
            bounding_box: bbox,
        }
    }

    /// Get bounding box
    pub fn bounding_box(&self) -> &TBox {
        &self.bounding_box
    }

    /// Get outlines
    pub fn outlines(&self) -> &[ChainOutline] {
        &self.outlines
    }

    /// Compute blob area
    pub fn area(&self) -> f32 {
        let mut total_area = 0.0;

        for outline in &self.outlines {
            total_area += outline.area();
            // Subtract holes
            for child in &outline.children {
                total_area -= child.area();
            }
        }

        total_area
    }

    /// Compute blob perimeter
    pub fn perimeter(&self) -> f32 {
        self.outlines.iter().map(|o| o.perimeter()).sum()
    }
}

/// Blob bounding box with analysis (equivalent to Tesseract's BLOBNBOX)
#[derive(Debug, Clone)]
pub struct BlobNBox {
    /// The blob
    blob: TBlob,
    /// Bounding box
    bounding_box: TBox,
    /// Area
    area: f32,
    /// Perimeter
    perimeter: f32,
    /// Stroke width (estimated)
    stroke_width: f32,
    /// Aspect ratio
    aspect_ratio: f32,
    /// Is this a diacritic?
    is_diacritic: bool,
    /// Is this joined to another blob?
    joined: bool,
}

impl BlobNBox {
    /// Create a new BlobNBox from a TBlob
    pub fn new(blob: TBlob) -> Self {
        let bbox = blob.bounding_box().clone();
        let area = blob.area();
        let perimeter = blob.perimeter();
        let width = bbox.width() as f32;
        let height = bbox.height() as f32;
        let aspect_ratio = if height > 0.0 { width / height } else { 1.0 };

        // Estimate stroke width (simplified)
        let stroke_width = if perimeter > 0.0 {
            (area * 2.0) / perimeter
        } else {
            1.0
        };

        Self {
            blob,
            bounding_box: bbox,
            area,
            perimeter,
            stroke_width,
            aspect_ratio,
            is_diacritic: false,
            joined: false,
        }
    }

    /// Get bounding box
    pub fn bounding_box(&self) -> &TBox {
        &self.bounding_box
    }

    /// Get blob
    pub fn blob(&self) -> &TBlob {
        &self.blob
    }

    /// Get area
    pub fn area(&self) -> f32 {
        self.area
    }

    /// Get aspect ratio
    pub fn aspect_ratio(&self) -> f32 {
        self.aspect_ratio
    }

    /// Get stroke width
    pub fn stroke_width(&self) -> f32 {
        self.stroke_width
    }

    /// Check if this is a diacritic
    pub fn is_diacritic(&self) -> bool {
        self.is_diacritic
    }

    /// Set diacritic flag
    pub fn set_diacritic(&mut self, value: bool) {
        self.is_diacritic = value;
    }

    /// Check if joined
    pub fn is_joined(&self) -> bool {
        self.joined
    }

    /// Set joined flag
    pub fn set_joined(&mut self, value: bool) {
        self.joined = value;
    }
}

/// Extract chain-coded outlines from binary image using edge following
pub fn extract_outlines(image: &GrayImage) -> Result<Vec<ChainOutline>> {
    let (width, height) = image.dimensions();
    let mut visited = vec![vec![false; height as usize]; width as usize];
    let mut outlines = Vec::new();

    // Find all outlines by following edges
    for y in 0..height {
        for x in 0..width {
            if visited[x as usize][y as usize] {
                continue;
            }

            let pixel = image.get_pixel(x, y);
            // Look for black pixels (text)
            if pixel[0] < 128 {
                if let Some(outline) = follow_edge(image, x, y, &mut visited)? {
                    outlines.push(outline);
                }
            }
        }
    }

    Ok(outlines)
}

/// Follow an edge to create a chain-coded outline
fn follow_edge(
    image: &GrayImage,
    start_x: u32,
    start_y: u32,
    visited: &mut Vec<Vec<bool>>,
) -> Result<Option<ChainOutline>> {
    let (width, height) = image.dimensions();
    let mut steps = Vec::new();
    let mut pos = ICoord::new(start_x as i32, start_y as i32);
    let start = pos;
    let mut first = true;

    // Use Moore neighborhood tracing (8-connected)
    // Simplified to 4-connected for now
    let directions = [
        ChainDir::Right,
        ChainDir::Down,
        ChainDir::Left,
        ChainDir::Up,
    ];

    loop {
        if pos.x < 0 || pos.x >= width as i32 || pos.y < 0 || pos.y >= height as i32 {
            break;
        }

        let px = pos.x as usize;
        let py = pos.y as usize;

        if visited[px][py] && !first {
            break;
        }

        visited[px][py] = true;

        if first {
            first = false;
        }

        // Find next edge pixel
        let mut found = false;
        for &dir in &directions {
            let (dx, dy) = dir.to_offset();
            let next_x = pos.x + dx;
            let next_y = pos.y + dy;

            if next_x < 0 || next_x >= width as i32 || next_y < 0 || next_y >= height as i32 {
                continue;
            }

            let next_pixel = image.get_pixel(next_x as u32, next_y as u32);

            // Check if this is an edge pixel (transition from black to white or vice versa)
            let current_pixel = image.get_pixel(pos.x as u32, pos.y as u32);
            let is_edge = (current_pixel[0] < 128) != (next_pixel[0] < 128);

            if is_edge
                && (!visited[next_x as usize][next_y as usize]
                    || (next_x == start.x && next_y == start.y))
            {
                steps.push(dir);
                pos = ICoord::new(next_x, next_y);
                found = true;
                break;
            }
        }

        if !found {
            break;
        }

        // Check if we've completed the loop
        if pos.x == start.x && pos.y == start.y && steps.len() > 2 {
            break;
        }

        // Prevent infinite loops
        if steps.len() > (width * height) as usize {
            break;
        }
    }

    if steps.len() < 4 {
        return Ok(None);
    }

    let is_inverse = {
        let pixel = image.get_pixel(start.x as u32, start.y as u32);
        pixel[0] >= 128
    };

    Ok(Some(ChainOutline::new(start, steps, is_inverse)))
}

/// Convert outlines to blobs
pub fn outlines_to_blobs(outlines: Vec<ChainOutline>) -> Vec<TBlob> {
    // Group outlines into blobs (outer outlines with their holes)
    let mut blobs = Vec::new();
    let mut used = vec![false; outlines.len()];

    for (i, outline) in outlines.iter().enumerate() {
        if used[i] || outline.is_inverse {
            continue;
        }

        used[i] = true;
        let mut blob_outlines = vec![outline.clone()];

        // Find holes (inverse outlines) inside this outline
        for (j, other) in outlines.iter().enumerate() {
            if used[j] || !other.is_inverse {
                continue;
            }

            // Check if other is inside outline
            if is_outline_inside(&outline.bounding_box, &other.bounding_box) {
                blob_outlines[0].add_child(other.clone());
                used[j] = true;
            }
        }

        blobs.push(TBlob::new(blob_outlines));
    }

    blobs
}

/// Check if one bounding box is inside another
fn is_outline_inside(outer: &TBox, inner: &TBox) -> bool {
    outer.left() <= inner.left()
        && outer.right() >= inner.right()
        && outer.top() >= inner.top()
        && outer.bottom() <= inner.bottom()
}