leptonica 0.4.0

Rust port of Leptonica image processing library
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
//! Coverage tests for morph functions
//!
//! Tests for:
//! - pixMorphSequenceByComponent / pixMorphSequenceByRegion (morphapp.c)
//! - pixGenerateSelBoundary / pixGenerateSelWithRuns / pixGenerateSelRandom (selgen.c)
//! - pixGetRunCentersOnLine / pixGetRunsOnLine / pixSubsampleBoundaryPixels (selgen.c)
//! - selaCreateFromColorPixa (sel1.c)
//! - pixaThinConnected (ccthin.c)
//!
//! # See also
//!
//! C Leptonica: `morphapp.c`, `selgen.c`, `sel1.c`, `ccthin.c`

use leptonica::morph::MorphOpType;
use leptonica::morph::morphapp::{
    RunDirection, RunType, ScaleDirection, TophatType, display_matched_pattern, fast_tophat,
    h_dome, morph_sequence_by_component, morph_sequence_by_region, pixa_extend_by_morph,
    pixa_extend_by_scaling, remove_matched_pattern, run_histogram_morph, selective_conn_comp_fill,
};
use leptonica::morph::sel::SelElement;
use leptonica::morph::selgen::{
    generate_sel_boundary, generate_sel_random, generate_sel_with_runs, get_run_centers_on_line,
    get_runs_on_line, subsample_boundary_pixels,
};
use leptonica::morph::thin::pixa_thin_connected;
use leptonica::morph::{Connectivity, ThinType};
use leptonica::{Pix, Pixa, PixelDepth, Sarray};

/// Create a binary image with two separate rectangles (two components).
fn make_two_rects(w: u32, h: u32) -> Pix {
    let pix = Pix::new(w, h, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    // Component 1: top-left rectangle
    for y in 2..10 {
        for x in 2..10 {
            pm.set_pixel_unchecked(x, y, 1);
        }
    }
    // Component 2: bottom-right rectangle
    for y in 20..30 {
        for x in 20..30 {
            pm.set_pixel_unchecked(x, y, 1);
        }
    }
    pm.into()
}

/// Create a binary image with a single filled rectangle.
fn make_rect(w: u32, h: u32, x0: u32, y0: u32, x1: u32, y1: u32) -> Pix {
    let pix = Pix::new(w, h, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    for y in y0..y1 {
        for x in x0..x1 {
            pm.set_pixel_unchecked(x, y, 1);
        }
    }
    pm.into()
}

/// Create a binary image with alternating foreground/background runs on a row.
fn make_run_pattern() -> Pix {
    // 40 wide, 10 tall. Row 5 has runs: 5 bg, 10 fg, 5 bg, 10 fg, 10 bg
    let pix = Pix::new(40, 10, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    for x in 5..15 {
        pm.set_pixel_unchecked(x, 5, 1);
    }
    for x in 20..30 {
        pm.set_pixel_unchecked(x, 5, 1);
    }
    pm.into()
}

// ============================================================================
// morph_sequence_by_component (pixMorphSequenceByComponent)
// ============================================================================

#[test]
fn test_morph_sequence_by_component_basic() {
    let pix = make_two_rects(40, 40);
    let result = morph_sequence_by_component(&pix, "d3.3", 0, 0, 4).unwrap();
    // Dilation applied per component; result is still 1bpp with same dimensions
    assert_eq!(result.depth(), PixelDepth::Bit1);
    assert_eq!(result.width(), 40);
    assert_eq!(result.height(), 40);
    // Both components should still be present
    assert!(result.count_pixels() >= pix.count_pixels());
}

#[test]
fn test_morph_sequence_by_component_min_size_filter() {
    let pix = make_two_rects(40, 40);
    // Set min size to filter out the smaller component (8x8)
    let result = morph_sequence_by_component(&pix, "d3.3", 9, 9, 4).unwrap();
    // Only the larger component (10x10) should be processed and present
    assert!(result.count_pixels() > 0);
    // Top-left area should have no foreground (small component filtered)
    let top_left_count: u64 = (2..10u32)
        .flat_map(|y| (2..10u32).map(move |x| (x, y)))
        .filter(|&(x, y)| result.get_pixel_unchecked(x, y) != 0)
        .count() as u64;
    assert_eq!(top_left_count, 0);
}

#[test]
fn test_morph_sequence_by_component_requires_1bpp() {
    let pix = Pix::new(40, 40, PixelDepth::Bit8).unwrap();
    assert!(morph_sequence_by_component(&pix, "d3.3", 0, 0, 4).is_err());
}

// ============================================================================
// morph_sequence_by_region (pixMorphSequenceByRegion)
// ============================================================================

#[test]
fn test_morph_sequence_by_region_basic() {
    let pix = make_two_rects(40, 40);
    let mask = make_two_rects(40, 40);
    let result = morph_sequence_by_region(&pix, &mask, "d3.3", 4, 0, 0).unwrap();
    assert_eq!(result.depth(), PixelDepth::Bit1);
    assert_eq!(result.width(), 40);
    assert_eq!(result.height(), 40);
    assert!(result.count_pixels() > 0);
}

#[test]
fn test_morph_sequence_by_region_requires_1bpp() {
    let pix = Pix::new(40, 40, PixelDepth::Bit8).unwrap();
    let mask = make_two_rects(40, 40);
    assert!(morph_sequence_by_region(&pix, &mask, "d3.3", 4, 0, 0).is_err());
}

#[test]
fn test_selective_conn_comp_fill_fills_hole() {
    let pix = Pix::new(24, 24, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    for y in 4..20u32 {
        for x in 4..20u32 {
            pm.set_pixel_unchecked(x, y, 1);
        }
    }
    for y in 10..14u32 {
        for x in 10..14u32 {
            pm.set_pixel_unchecked(x, y, 0);
        }
    }
    let pix: Pix = pm.into();

    let out = selective_conn_comp_fill(&pix, 8, 1, 1).unwrap();
    assert_eq!(out.get_pixel_unchecked(12, 12), 1);
}

#[test]
fn test_remove_and_display_matched_pattern() {
    let pix = Pix::new(12, 12, PixelDepth::Bit1).unwrap();
    let mut sm = pix.try_into_mut().unwrap();
    sm.set_pixel_unchecked(6, 7, 1);
    let src: Pix = sm.into();

    let pattern = Pix::new(1, 1, PixelDepth::Bit1).unwrap();
    let mut pm = pattern.try_into_mut().unwrap();
    pm.set_pixel_unchecked(0, 0, 1);
    let pattern: Pix = pm.into();

    let matches = Pix::new(12, 12, PixelDepth::Bit1).unwrap();
    let mut mm = matches.try_into_mut().unwrap();
    mm.set_pixel_unchecked(6, 7, 1);
    let matches: Pix = mm.into();

    let removed = remove_matched_pattern(&src, &pattern, &matches, 0, 0, 0).unwrap();
    assert_eq!(removed.get_pixel_unchecked(6, 7), 0);

    let color = 0x00ff00ff;
    let shown = display_matched_pattern(&src, &pattern, &matches, 0, 0, color, 1.0).unwrap();
    assert_eq!(shown.depth(), PixelDepth::Bit32);
    assert_eq!(shown.get_pixel_unchecked(6, 7), color);
}

#[test]
fn test_pixa_extend_by_morph_and_scaling() {
    let pix = Pix::new(10, 6, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    pm.set_pixel_unchecked(5, 3, 1);
    let mut pixa = Pixa::new();
    pixa.push(pm.into());

    let extm = pixa_extend_by_morph(&pixa, MorphOpType::Dilate, 2, None, true).unwrap();
    assert_eq!(extm.len(), 3);
    assert!(extm.get(2).unwrap().count_pixels() >= extm.get(1).unwrap().count_pixels());

    let exts =
        pixa_extend_by_scaling(&pixa, &[0.5, 2.0], ScaleDirection::BothDirections, false).unwrap();
    assert_eq!(exts.len(), 2);
    assert_eq!(exts.get(0).unwrap().width(), 5);
    assert_eq!(exts.get(1).unwrap().height(), 12);
}

#[test]
fn test_run_histogram_morph_and_gray_ops() {
    let pix = Pix::new(8, 1, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    for x in 2..6u32 {
        pm.set_pixel_unchecked(x, 0, 1);
    }
    let pix: Pix = pm.into();

    let na = run_histogram_morph(&pix, RunType::On, RunDirection::Horizontal, 4).unwrap();
    assert!(!na.is_empty());
    assert_eq!(na.get(0), Some(0.0));

    let gray = Pix::new(16, 16, PixelDepth::Bit8).unwrap();
    let mut gm = gray.try_into_mut().unwrap();
    for y in 0..16u32 {
        for x in 0..16u32 {
            gm.set_pixel_unchecked(x, y, 80);
        }
    }
    gm.set_pixel_unchecked(8, 8, 130);
    let gray: Pix = gm.into();

    let dome = h_dome(&gray, 20, 4).unwrap();
    assert!(dome.get_pixel_unchecked(8, 8) > 0);
    let tophat = fast_tophat(&gray, 3, 3, TophatType::White).unwrap();
    assert_eq!(tophat.depth(), PixelDepth::Bit8);
}

// ============================================================================
// generate_sel_boundary (pixGenerateSelBoundary)
// ============================================================================

#[test]
fn test_generate_sel_boundary_basic() {
    let pix = make_rect(20, 20, 5, 5, 15, 15);
    let sel = generate_sel_boundary(&pix, 1, 1, 0, 0, true, true, true, true).unwrap();
    // Should produce a hit-miss Sel
    assert!(sel.hit_count() > 0);
    assert!(sel.miss_count() > 0);
}

#[test]
fn test_generate_sel_boundary_skip_hits() {
    let pix = make_rect(20, 20, 5, 5, 15, 15);
    // Skip=2 means subsample boundary pixels
    let sel = generate_sel_boundary(&pix, 1, 1, 2, 2, true, true, true, true).unwrap();
    assert!(sel.hit_count() > 0);
}

#[test]
fn test_generate_sel_boundary_requires_1bpp() {
    let pix = Pix::new(20, 20, PixelDepth::Bit8).unwrap();
    assert!(generate_sel_boundary(&pix, 1, 1, 0, 0, true, true, true, true).is_err());
}

// ============================================================================
// generate_sel_with_runs (pixGenerateSelWithRuns)
// ============================================================================

#[test]
fn test_generate_sel_with_runs_basic() {
    let pix = make_rect(30, 30, 5, 5, 25, 25);
    let sel = generate_sel_with_runs(&pix, 2, 2, 1, 1, 0, 0, 0, 0).unwrap();
    assert!(sel.hit_count() > 0);
}

#[test]
fn test_generate_sel_with_runs_requires_1bpp() {
    let pix = Pix::new(30, 30, PixelDepth::Bit8).unwrap();
    assert!(generate_sel_with_runs(&pix, 2, 2, 1, 1, 0, 0, 0, 0).is_err());
}

// ============================================================================
// generate_sel_random (pixGenerateSelRandom)
// ============================================================================

#[test]
fn test_generate_sel_random_basic() {
    let pix = make_rect(30, 30, 5, 5, 25, 25);
    let sel = generate_sel_random(&pix, 0.5, 0.5, 1, 0, 0, 0, 0).unwrap();
    assert!(sel.hit_count() > 0);
}

#[test]
fn test_generate_sel_random_requires_1bpp() {
    let pix = Pix::new(30, 30, PixelDepth::Bit8).unwrap();
    assert!(generate_sel_random(&pix, 0.5, 0.5, 1, 0, 0, 0, 0).is_err());
}

// ============================================================================
// get_run_centers_on_line (pixGetRunCentersOnLine)
// ============================================================================

#[test]
fn test_get_run_centers_on_line_horizontal() {
    let pix = make_run_pattern();
    // Horizontal line at y=5: runs are 5bg, 10fg, 5bg, 10fg, 10bg
    let centers = get_run_centers_on_line(&pix, -1, 5, 1).unwrap();
    // Two foreground runs with length >= 1 → 2 centers
    assert_eq!(centers.len(), 2);
    // First run center: pixels 5..15, center ≈ 10
    let c0 = centers.get(0).unwrap() as u32;
    assert!((9..=10).contains(&c0));
    // Second run center: pixels 20..30, center ≈ 25
    let c1 = centers.get(1).unwrap() as u32;
    assert!((24..=25).contains(&c1));
}

#[test]
fn test_get_run_centers_on_line_vertical() {
    // Vertical: set x=10, scan column
    let pix = make_run_pattern();
    // At x=10, only y=5 is foreground
    let centers = get_run_centers_on_line(&pix, 10, -1, 1).unwrap();
    assert_eq!(centers.len(), 1);
}

#[test]
fn test_get_run_centers_on_line_min_length_filter() {
    let pix = make_run_pattern();
    // Only runs with length >= 15 (none qualifies since runs are length 10)
    let centers = get_run_centers_on_line(&pix, -1, 5, 15).unwrap();
    assert_eq!(centers.len(), 0);
}

// ============================================================================
// get_runs_on_line (pixGetRunsOnLine)
// ============================================================================

#[test]
fn test_get_runs_on_line_horizontal() {
    let pix = make_run_pattern();
    // Horizontal line at y=5
    let runs = get_runs_on_line(&pix, 0, 5, 39, 5).unwrap();
    // Alternating bg/fg: 5bg, 10fg, 5bg, 10fg, 10bg → 5 runs
    assert!(runs.len() >= 5);
    // First run is background (5 pixels)
    assert!((runs.get(0).unwrap() - 5.0).abs() < 0.01);
    // Second run is foreground (10 pixels)
    assert!((runs.get(1).unwrap() - 10.0).abs() < 0.01);
}

#[test]
fn test_get_runs_on_line_single_pixel_line() {
    let pix = Pix::new(1, 1, PixelDepth::Bit1).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    pm.set_pixel_unchecked(0, 0, 1);
    let pix: Pix = pm.into();
    let runs = get_runs_on_line(&pix, 0, 0, 0, 0).unwrap();
    // Single foreground pixel: bg_run=0, fg_run=1
    assert!(runs.len() >= 2);
}

// ============================================================================
// subsample_boundary_pixels (pixSubsampleBoundaryPixels)
// ============================================================================

#[test]
fn test_subsample_boundary_pixels_skip_0() {
    let pix = make_rect(20, 20, 5, 5, 15, 15);
    let boundary =
        leptonica::morph::extract_boundary(&pix, leptonica::morph::BoundaryType::Inner).unwrap();
    let pta = subsample_boundary_pixels(&boundary, 0).unwrap();
    // skip=0 returns all foreground pixels
    assert!(!pta.is_empty());
}

#[test]
fn test_subsample_boundary_pixels_skip_2() {
    let pix = make_rect(20, 20, 5, 5, 15, 15);
    let boundary =
        leptonica::morph::extract_boundary(&pix, leptonica::morph::BoundaryType::Inner).unwrap();
    let all = subsample_boundary_pixels(&boundary, 0).unwrap();
    let sampled = subsample_boundary_pixels(&boundary, 2).unwrap();
    // Subsampled should have fewer or equal points
    assert!(sampled.len() <= all.len());
    assert!(!sampled.is_empty());
}

// ============================================================================
// sela_create_from_color_pixa (selaCreateFromColorPixa)
// ============================================================================

#[test]
fn test_sela_create_from_color_pixa_basic() {
    use leptonica::morph::sel::sela_create_from_color_pixa;

    // Create a 3x3 color image: green=hit, red=miss, white=don't care
    let pix = Pix::new(3, 3, PixelDepth::Bit32).unwrap();
    let mut pm = pix.try_into_mut().unwrap();
    // Fill white
    for y in 0..3u32 {
        for x in 0..3u32 {
            pm.set_pixel_unchecked(x, y, 0xFFFFFF00);
        }
    }
    // Center = green (hit)
    pm.set_pixel_unchecked(1, 1, 0x00FF0000);
    // Corner = red (miss)
    pm.set_pixel_unchecked(0, 0, 0xFF000000);
    let pix: Pix = pm.into();

    let mut pixa = Pixa::new();
    pixa.push(pix);

    let mut sa = Sarray::new();
    sa.push("test_sel");

    let sela = sela_create_from_color_pixa(&pixa, &sa).unwrap();
    assert_eq!(sela.count(), 1);
    let sel = sela.get(0).unwrap();
    assert_eq!(sel.get_element(1, 1), Some(SelElement::Hit));
    assert_eq!(sel.get_element(0, 0), Some(SelElement::Miss));
}

#[test]
fn test_sela_create_from_color_pixa_mismatched_lengths() {
    use leptonica::morph::sel::sela_create_from_color_pixa;

    let pixa = Pixa::new();
    let mut sa = Sarray::new();
    sa.push("extra_name");
    assert!(sela_create_from_color_pixa(&pixa, &sa).is_err());
}

// ============================================================================
// pixa_thin_connected (pixaThinConnected)
// ============================================================================

#[test]
fn test_pixa_thin_connected_basic() {
    // Create a Pixa with thick rectangles
    let mut pixa = Pixa::new();
    pixa.push(make_rect(20, 20, 2, 5, 18, 15));
    pixa.push(make_rect(30, 30, 3, 3, 27, 27));

    let result = pixa_thin_connected(&pixa, ThinType::Foreground, Connectivity::Four, 0).unwrap();
    assert_eq!(result.len(), 2);
    // Each thinned image should have fewer pixels than original
    for i in 0..result.len() {
        let orig = pixa.get(i).unwrap();
        let thinned = result.get(i).unwrap();
        assert_eq!(thinned.depth(), PixelDepth::Bit1);
        assert!(thinned.count_pixels() <= orig.count_pixels());
        assert!(thinned.count_pixels() > 0);
    }
}

#[test]
fn test_pixa_thin_connected_requires_1bpp() {
    let mut pixa = Pixa::new();
    pixa.push(Pix::new(10, 10, PixelDepth::Bit8).unwrap());
    assert!(pixa_thin_connected(&pixa, ThinType::Foreground, Connectivity::Four, 0).is_err());
}

#[test]
fn test_pixa_thin_connected_empty_pixa() {
    let pixa = Pixa::new();
    let result = pixa_thin_connected(&pixa, ThinType::Foreground, Connectivity::Four, 0).unwrap();
    assert_eq!(result.len(), 0);
}