Commit 36a93b34 for tesseract
commit 36a93b348f90b3f1a734b565304312dbfa972734
Author: Stefan Weil <sw@weilnetz.de>
Date: Thu Nov 26 15:35:17 2026 +0100
Recognise multi-column (newspaper) pages column by column
A newspaper page whose columns run into each other (e.g. a faint or
broken gutter) can be segmented into interleaved "lines" that contain
fragments of two or more adjacent columns, which the recognizer then
reads left-to-right across the whole page and garbles.
When the new config variable textord_auto_columns is enabled
(default: off), the gutter detector first looks for the gutters
between the columns, then each full-height column is recognised
independently with its own thresholded image, so that words from
adjacent columns are never interleaved, and the per-column results
are merged back into a single page result in column-major reading
order. The column geometry is shifted into full-page coordinates and
the full-page image is restored, so all renderers produce the same
output formats as the normal flow.
All of the geometry of a column is moved: the blobs, the bounding box
and the baseline of each row, the outline and the polygon of each
block, the words which the results own (nearly all words of the LSTM
recognizer, which are not in the word list of their row) and the
boxes of the symbols. The coordinates of a block are rotated against
the image for vertical text and for a page which is not upright, so
the shift is rotated into the coordinates of each block, and the
columns of a page which is upside down are merged from right to
left, which is their reading order.
In other respects the recognition by columns behaves like the normal
flow: Recognize returns -1 if the monitor stops the recognition
(timeout, cancel) or if a column cannot be thresholded or segmented,
and the columns after it are not recognised. The resolution which
was set for the page (SetSourceResolution, user_defined_dpi) is used
for each column and is still set afterwards. Paragraphs are detected
with and without paragraph_text_based. The columns of an image with
a colormap are cut from a copy without it, in which white is known.
A page is split only in the page segmentation modes with column
finding (--psm 1 to 3). The other modes say that the page is a single
column, block, line or word, and take the blocks from a UNLV zone
file for the whole page if there is one. The modes of Recognize which
take the segmentation from a box file, make training data or show
the results are not split into columns either.
The gutter mask comes from the pipeline of Leptonica's
newspaper_reg.c: remove vertical and horizontal rules, local rank
re-binarisation, open into vertical strokes. A gutter is a narrow
group of lines through that mask which are free of text over 80 % of
the page height and which leave columns of at least 7 % of the image
width (two pages with five columns each fit on one scan); of two
gutters which are too close the weaker one is dropped, so the gaps
inside tables lose against the real gutters. The lines may be slanted
(slopes up to 0.05, about 3 degrees), because the gutters of a
scanned page are seldom exactly vertical and on the double pages of a
microfilm each column can lean a little differently: a vertical cut
through such a gutter clips the ends of the text lines at the top or
at the bottom of the column. Each column is cut out along its two
gutters: its bounding rectangle is taken and the parts which belong
to the neighbouring columns are painted white.
A projection is used and not the connected components of the mask: a
component also contains the white areas which touch the gutter (the
ends of short lines, all on the left side of a gutter), so the centre
of its bounding box lies inside the text of the left column, and two
gutters which are connected through such areas form one component.
If no gutter is found (single-column or too-irregular pages, mixed
layouts such as ads) the page is left untouched and the normal
recognition path runs, producing byte-identical output.
Measured on the 101 double pages of the ground truth
UB-Mannheim/reichsanzeiger-gt (47,065 text lines without table cells,
each compared with the nearest recognised line, reading order
ignored): character error rate 26.95 % without the column
recognition, 5.40 % with it; 59.1 % and 89.4 % of the lines are
found with at most 10 % errors. 74 pages get better by more than
10 %, 20 get worse. Known limits: a heading which spans several
columns is cut at the gutters.
Add unit tests: a page with columns (8071_093.3B.tif) is split into
at least two columns and yields recognisable text plus well-formed
hOCR boxes, and a single-column page (phototest.tif) is not split
and yields output identical to the disabled run. The geometry is
checked at all levels (a symbol lies in its word, a word in its text
line, a text line in its paragraph, and the baseline and the block
polygon are where the text is), also for the page upside down and
for a block of vertical text in a column. Further tests cover a
stopped recognition, the resolution, the other modes of Recognize,
a page segmentation mode without column finding (with a zone file),
the paragraphs without text and a skewed page with a colormap.
The public API is unchanged: RecognizeMultiColumn is a private
method of TessBaseAPI, and the number of columns of the last page is
kept in the internal Tesseract class, where the test reads it through
a test-local subclass. TessBaseAPI gets no new data member, so its
size and layout stay as they are.
unittest/CMakeLists.txt: add BEFORE to the test targets' include
directories so that an installed Tesseract (e.g. a Homebrew build
sharing the prefix with libtiff) cannot shadow the in-tree headers,
matching how libtesseract itself is compiled.
Assisted-by: OpenCode / qwen3.8-27b-thinking (Alibaba Cloud)
Assisted-by: Claude Fable 5.2 (Anthropic)
Signed-off-by: Stefan Weil <sw@weilnetz.de>
diff --git a/Makefile.am b/Makefile.am
index 457a8d40..066538d6 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1212,6 +1212,7 @@ check_PROGRAMS += mastertrainer_test
endif # !DISABLED_LEGACY_ENGINE
check_PROGRAMS += matrix_deserializesize_test
check_PROGRAMS += matrix_test
+check_PROGRAMS += multicolumn_test
check_PROGRAMS += networkio_test
if !DISABLED_LEGACY_ENGINE
check_PROGRAMS += normproto_test
@@ -1486,6 +1487,10 @@ matrix_test_SOURCES = unittest/matrix_test.cc
matrix_test_CPPFLAGS = $(unittest_CPPFLAGS)
matrix_test_LDADD = $(TESS_LIBS)
+multicolumn_test_SOURCES = unittest/multicolumn_test.cc
+multicolumn_test_CPPFLAGS = $(unittest_CPPFLAGS)
+multicolumn_test_LDADD = $(TRAINING_LIBS) $(LEPTONICA_LIBS)
+
networkio_test_SOURCES = unittest/networkio_test.cc
networkio_test_CPPFLAGS = $(unittest_CPPFLAGS)
networkio_test_LDADD = $(TESS_LIBS)
diff --git a/include/tesseract/baseapi.h b/include/tesseract/baseapi.h
index 1e0670d4..9b3cea19 100644
--- a/include/tesseract/baseapi.h
+++ b/include/tesseract/baseapi.h
@@ -820,6 +820,15 @@ private:
int timeout_millisec,
TessResultRenderer *renderer,
int tessedit_page_number);
+ // Multi-column (newspaper) recognition: automatically detect the gutters
+ // that separate columns, recognise each column independently so that
+ // words from adjacent columns are never interleaved, and merge the results
+ // back into a single page result in column-major reading order. Used as an
+ // alternative to the normal FindLines()/recog_all_words() flow when
+ // textord_auto_columns is enabled and more than one column is detected.
+ // Returns 1 if the page was recognised by columns, 0 if it was not split
+ // and -1 if the recognition failed or was stopped by the monitor.
+ int RecognizeMultiColumn(ETEXT_DESC *monitor);
}; // class TessBaseAPI.
/** Escape a char string - replace &<>"' with HTML codes. */
diff --git a/src/api/baseapi.cpp b/src/api/baseapi.cpp
index 5673f513..7f3f67ca 100644
--- a/src/api/baseapi.cpp
+++ b/src/api/baseapi.cpp
@@ -42,6 +42,8 @@
#endif
#include "mutableiterator.h" // for MutableIterator
#include "normalis.h" // for kBlnBaselineOffset, kBlnXHeight
+#include "ocrblock.h" // for BLOCK, BLOCK_IT
+#include "ocrrow.h" // for ROW, ROW_IT
#include "pageres.h" // for PAGE_RES_IT, WERD_RES, PAGE_RES, CR_DE...
#include "paragraphs.h" // for DetectParagraphs
#include "params.h" // for BoolParam, IntParam, DoubleParam, Stri...
@@ -62,6 +64,7 @@
#include <tesseract/renderer.h> // for TessResultRenderer
#include <tesseract/resultiterator.h> // for ResultIterator
+#include <algorithm> // for std::sort
#include <cmath> // for round, M_PI
#include <cstdint> // for int32_t
#include <cstring> // for strcmp, strcpy
@@ -779,6 +782,35 @@ int TessBaseAPI::Recognize(ETEXT_DESC *monitor) {
tprintf("Error: Recognize called without a loaded language. Pass a language to Init.\n");
return -1;
}
+ tesseract_->set_auto_columns_used(0);
+ // Automatic multi-column (newspaper) support: when enabled, detect the
+ // column gutters, recognise each column independently and merge the results
+ // in column-major order. If no gutter is found (single-column or irregular
+ // page) this returns 0 and we fall through to the normal path below.
+ // Only the page segmentation modes which look for columns themselves get
+ // it: the other ones say that the page has a single column, block, line or
+ // word, or take the blocks from a zone file for the whole page.
+ // The modes below which take the segmentation from a box file, make
+ // training data or show the results need the normal path.
+ bool by_columns = tesseract_->textord_auto_columns &&
+ PSM_COL_FIND_ENABLED(tesseract_->tessedit_pageseg_mode) &&
+ !tesseract_->tessedit_train_line_recognizer &&
+ !tesseract_->interactive_display_mode;
+#ifndef DISABLED_LEGACY_ENGINE
+ if (tesseract_->tessedit_resegment_from_line_boxes ||
+ tesseract_->tessedit_resegment_from_boxes ||
+ tesseract_->tessedit_make_boxes_from_boxes ||
+ tesseract_->tessedit_train_from_boxes ||
+ tesseract_->tessedit_ambigs_training) {
+ by_columns = false;
+ }
+#endif // ndef DISABLED_LEGACY_ENGINE
+ if (by_columns) {
+ const int result = RecognizeMultiColumn(monitor);
+ if (result != 0) {
+ return result > 0 ? 0 : -1;
+ }
+ }
if (FindLines() != 0) {
return -1;
}
@@ -2166,6 +2198,602 @@ int TessBaseAPI::FindLines() {
return 0;
}
+namespace {
+// Multi-column (newspaper) support. See RecognizeMultiColumn below.
+
+// A single candidate gutter: the line x + slope * (y - height / 2) in
+// full-resolution pixels (a gutter is only vertical if the page has no skew),
+// and its strength (the number of gutter pixels along that line at half
+// resolution).
+struct GutterX {
+ int x;
+ int strength;
+ double slope;
+ // The x coordinate of the gutter in row y of an image of the given height.
+ int XAtY(int y, int height) const {
+ return x + static_cast<int>(std::lround(slope * (y - height / 2)));
+ }
+};
+
+// Number of horizontal bands of the page for which the gutter pixels are
+// counted per pixel column, and the slopes (dx / dy) which are tried for a
+// gutter: up to about 3 degrees of skew.
+const int kGutterBands = 32;
+const double kMaxGutterSlope = 0.05;
+const double kGutterSlopeStep = 0.0025;
+// A gutter must be free of text over this fraction of the page height.
+// Measured on the 101 double pages of the ground truth reichsanzeiger-gt
+// (character error rate of the text lines 26.95 % without the column
+// recognition): 0.7 and 0.8 give nearly the same result (5.24 %, 5.40 %),
+// 0.9 misses gutters which are crossed by headings (6.74 %).
+const double kMinGutterHeightFraction = 0.80;
+// Minimum width of a column as a fraction of the image width. A scan of two
+// newspaper pages with five columns each has columns of about 8 %.
+const double kMinColumnWidthFraction = 0.07;
+
+// Detect the vertical gutters that separate the columns of a newspaper page,
+// working at half resolution (the morphological structuring elements are
+// scale-tuned for that). Ported from Leptonica's newspaper_reg.c: the vertical
+// and horizontal rules are opened out and removed, the remaining text image is
+// re-binarised with a local (rank) threshold -- which is what makes the
+// detection robust to faint, variable-intensity rules -- then inverted so the
+// ink-free gutters become the foreground, opened into vertical strokes,
+// and dilated. A narrow group of lines (vertical, or slanted a little for a
+// page with skew) which are gutter over most of the page height is a gutter
+// candidate; a minimum-column-width post-filter then rejects edge printing
+// artifacts, next-page slivers and the gaps inside tables, which would
+// otherwise create a too-narrow column. Returns an empty vector for a
+// single-column (or too-irregular) page.
+std::vector<GutterX> DetectColumnGutters(Pix *page) {
+ std::vector<GutterX> gutters;
+ if (page == nullptr) {
+ return gutters;
+ }
+ const int w0 = pixGetWidth(page);
+ const int h0 = pixGetHeight(page);
+ if (w0 < 100 || h0 < 100) {
+ return gutters;
+ }
+
+ // Work at half resolution.
+ Pix *half = pixScale(page, 0.5f, 0.5f);
+ int spp = pixGetSpp(half);
+ int dep = pixGetDepth(half);
+ Pix *grey = nullptr;
+ if (spp > 1) {
+ grey = pixConvertRGBToGray(half, 0.3f, 0.59f, 0.11f);
+ } else if (dep != 8) {
+ grey = pixConvertTo8(half, dep == 16);
+ } else {
+ grey = pixClone(half);
+ }
+ Pix *ink = pixThresholdToBinary(grey, 128); // dark (ink) = 1.
+ const int w = pixGetWidth(ink);
+ const int h = pixGetHeight(ink);
+
+ // Remove the vertical, then the horizontal, rules (open -> fill -> xor out).
+ Pix *vlines = pixMorphSequence(ink, "o1.50", 0);
+ Pix *vfull = pixSeedfillBinary(nullptr, vlines, ink, 8);
+ Pix *notv = pixXor(nullptr, ink, vfull);
+ Pix *hlines = pixMorphSequence(notv, "o50.1", 0);
+ Pix *hfull = pixSeedfillBinary(nullptr, hlines, notv, 8);
+ Pix *text = pixXor(nullptr, notv, hfull);
+
+ // Local (rank) re-binarisation: robust to variable-intensity rules.
+ Pix *rank = pixReduceRankBinaryCascade(text, 1, 1, 0, 0);
+ pixInvert(rank, rank); // gutters (low ink) become foreground.
+
+ // Open into vertical gutter strokes, then dilate into a mask.
+ Pix *strokes = pixMorphSequence(rank, "o1.50", 0);
+ Pix *mask = pixExpandBinaryPower2(strokes, 4);
+
+ // Gutter candidates: lines which are gutter over most of the page height,
+ // in a narrow group, not at the page edge. The gutter pixels are counted
+ // along slanted lines too, because the gutters of a page with a little skew
+ // are not vertical: a vertical line through such a gutter is free over a
+ // part of the height only and cuts off the ends of the text lines above or
+ // below. A projection is used instead of the connected components of the
+ // mask: a component also contains the white areas which touch the gutter
+ // (the ends of short lines, which are all on the left side of a gutter), so
+ // the centre of its bounding box lies inside the text of the left column,
+ // and two gutters which are connected through such areas form a single
+ // component.
+ std::vector<GutterX> cands;
+ const int emargin = (int)(0.05 * w);
+ // The mask can be a few pixels narrower than w (reduced and expanded by 4).
+ const int mask_width = pixGetWidth(mask);
+ const int mask_height = pixGetHeight(mask);
+ // Count the gutter pixels of each pixel column in horizontal bands.
+ std::vector<std::vector<int>> band_sums(kGutterBands, std::vector<int>(mask_width, 0));
+ std::vector<double> band_mid_y(kGutterBands, 0.0);
+ for (int b = 0; b < kGutterBands; ++b) {
+ const int y0 = static_cast<int>(static_cast<int64_t>(mask_height) * b / kGutterBands);
+ const int y1 = static_cast<int>(static_cast<int64_t>(mask_height) * (b + 1) / kGutterBands);
+ band_mid_y[b] = (y0 + y1) / 2.0 - mask_height / 2.0;
+ if (y1 <= y0) {
+ continue;
+ }
+ Box *band_box = boxCreate(0, y0, mask_width, y1 - y0);
+ Pix *band = pixClipRectangle(mask, band_box, nullptr);
+ Numa *sums = band != nullptr ? pixCountPixelsByColumn(band) : nullptr;
+ if (sums != nullptr) {
+ for (int x = 0; x < mask_width; ++x) {
+ l_int32 count = 0;
+ numaGetIValue(sums, x, &count);
+ band_sums[b][x] = count;
+ }
+ }
+ numaDestroy(&sums);
+ pixDestroy(&band);
+ boxDestroy(&band_box);
+ }
+ // For each pixel column (at half of the height) the best count along a
+ // line through it, and the slope of that line.
+ std::vector<int> best_count(mask_width, 0);
+ std::vector<double> best_slope(mask_width, 0.0);
+ const int num_slopes = static_cast<int>(std::lround(kMaxGutterSlope / kGutterSlopeStep));
+ std::vector<int> line_count(mask_width);
+ for (int k = 0; k <= 2 * num_slopes; ++k) {
+ // Try the slopes 0, +step, -step, +2 * step, ... so that the vertical
+ // line wins a tie.
+ const double slope = ((k + 1) / 2) * kGutterSlopeStep * ((k & 1) ? 1 : -1);
+ std::fill(line_count.begin(), line_count.end(), 0);
+ for (int b = 0; b < kGutterBands; ++b) {
+ const int shift = static_cast<int>(std::lround(slope * band_mid_y[b]));
+ const int first_x = std::max(0, -shift);
+ const int last_x = std::min(mask_width, mask_width - shift);
+ for (int x = first_x; x < last_x; ++x) {
+ line_count[x] += band_sums[b][x + shift];
+ }
+ }
+ for (int x = 0; x < mask_width; ++x) {
+ if (line_count[x] > best_count[x]) {
+ best_count[x] = line_count[x];
+ best_slope[x] = slope;
+ }
+ }
+ }
+ auto column_count = [&best_count, mask_width](int x) {
+ return x >= 0 && x < mask_width ? best_count[x] : 0;
+ };
+ const int min_count = (int)(kMinGutterHeightFraction * h);
+ for (int x = 0; x < mask_width; ++x) {
+ if (column_count(x) < min_count) {
+ continue;
+ }
+ // [x, end) is a run of gutter columns.
+ int end = x + 1;
+ int peak = column_count(x);
+ int peak_x = x;
+ while (end < mask_width && column_count(end) >= min_count) {
+ if (column_count(end) > peak) {
+ peak = column_count(end);
+ peak_x = end;
+ }
+ ++end;
+ }
+ // Cut in the middle of the columns which are (nearly) as free as the best
+ // one: the lower flanks of the run are the ends of short lines.
+ const int near_peak = peak - peak / 20;
+ int first = x;
+ while (column_count(first) < near_peak) {
+ ++first;
+ }
+ int last = end - 1;
+ while (column_count(last) < near_peak) {
+ --last;
+ }
+ x = end;
+ if (last - first + 1 > 0.05 * w) {
+ continue;
+ }
+ const int cx = (first + last + 1) / 2;
+ if (cx < emargin || cx > w - emargin) {
+ continue;
+ }
+ cands.push_back(GutterX{cx * 2, peak, best_slope[peak_x]});
+ }
+
+ // Sort by x, then drop any gutter that would leave a column narrower than
+ // the minimum real-column width (rejects edge artifacts / slivers).
+ std::sort(cands.begin(), cands.end(),
+ [](const GutterX &a, const GutterX &b) { return a.x < b.x; });
+ const double minw = kMinColumnWidthFraction * w0;
+ for (;;) {
+ if (cands.empty()) {
+ break;
+ }
+ double worst = 1e18;
+ int worst_edge = -1; // -1 => left edge, cands.size() => right edge
+ if (cands[0].x < worst) {
+ worst = cands[0].x;
+ worst_edge = -1;
+ }
+ for (size_t i = 1; i < cands.size(); ++i) {
+ double gap = cands[i].x - cands[i - 1].x;
+ if (gap < worst) {
+ worst = gap;
+ worst_edge = (int)i;
+ }
+ }
+ if (w0 - cands.back().x < worst) {
+ worst = w0 - cands.back().x;
+ worst_edge = (int)cands.size();
+ }
+ if (worst >= minw) {
+ break;
+ }
+ int drop;
+ if (worst_edge == -1) {
+ drop = 0;
+ } else if (worst_edge == (int)cands.size()) {
+ drop = (int)cands.size() - 1;
+ } else {
+ // Interior narrow gap: drop the weaker of its two gutters; on a tie
+ // drop the left one.
+ drop = (cands[worst_edge].strength < cands[worst_edge - 1].strength)
+ ? worst_edge
+ : worst_edge - 1;
+ }
+ cands.erase(cands.begin() + drop);
+ }
+
+ gutters = std::move(cands);
+
+ pixDestroy(&mask);
+ pixDestroy(&strokes);
+ pixDestroy(&rank);
+ pixDestroy(&text);
+ pixDestroy(&hfull);
+ pixDestroy(&hlines);
+ pixDestroy(¬v);
+ pixDestroy(&vfull);
+ pixDestroy(&vlines);
+ pixDestroy(&ink);
+ pixDestroy(&grey);
+ pixDestroy(&half);
+ return gutters;
+}
+
+// Move the rejected (noise) blobs of a word, which WERD::move skips but which
+// the bounding boxes of the word, its row and its block include.
+void MoveRejectedBlobs(WERD *word, const ICOORD &vec) {
+ C_BLOB_IT it(word->rej_cblob_list());
+ for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
+ it.data()->move(vec);
+ }
+}
+
+// Shift a column's recognised blocks and the results of its recognition right
+// by dx pixels in the image, so that all of its geometry is in full-page
+// coordinates. The coordinates of a block are rotated against the image if
+// its text is vertical or if the page is not upright (re_rotation() turns
+// them back), so the shift is rotated the other way for each block.
+// Moving the blobs of the words in the rows is not sufficient: a row also
+// keeps its bounding box (used for the paragraph box and the baseline) and
+// its baseline, a block keeps its outline and its polygon, and the results
+// keep the words which were made from several words of a row (nearly all
+// words of the LSTM recognizer, they are not in the word list of the row) and
+// the boxes of the symbols.
+void ShiftColumnGeometry(BLOCK_LIST *blocks, PAGE_RES *page_res, int dx) {
+ if (dx == 0) {
+ return;
+ }
+ const ICOORD image_vec(dx, 0);
+ // The shift in the coordinates of a block.
+ auto block_vec = [&image_vec](const BLOCK *block) {
+ ICOORD vec(image_vec);
+ const FCOORD re_rotation = block->re_rotation();
+ vec.rotate(FCOORD(re_rotation.x(), -re_rotation.y()));
+ return vec;
+ };
+ BLOCK_IT b_it(blocks);
+ for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
+ BLOCK *block = b_it.data();
+ const ICOORD vec = block_vec(block);
+ block->pdblk.move(vec);
+ if (block->pdblk.poly_block() != nullptr) {
+ block->pdblk.poly_block()->move(vec);
+ }
+ ROW_IT r_it(block->row_list());
+ for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
+ ROW *row = r_it.data();
+ // Moves the words, the bounding box and the baseline.
+ row->move(vec);
+ WERD_IT w_it(row->word_list());
+ for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
+ MoveRejectedBlobs(w_it.data(), vec);
+ }
+ }
+ }
+ BLOCK_RES_IT br_it(&page_res->block_res_list);
+ for (br_it.mark_cycle_pt(); !br_it.cycled_list(); br_it.forward()) {
+ const ICOORD vec = block_vec(br_it.data()->block);
+ ROW_RES_IT rr_it(&br_it.data()->row_res_list);
+ for (rr_it.mark_cycle_pt(); !rr_it.cycled_list(); rr_it.forward()) {
+ WERD_RES_IT wr_it(&rr_it.data()->word_res_list);
+ for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) {
+ WERD_RES *word_res = wr_it.data();
+ // A combination owns its word, all other words were moved with
+ // their row.
+ if (word_res->combination && word_res->word != nullptr) {
+ word_res->word->move(vec);
+ MoveRejectedBlobs(word_res->word, vec);
+ }
+ // The iterators take the boxes of the symbols as they are, in the
+ // coordinates of the image. (The legacy engine makes them so. Those
+ // of the LSTM recognizer are in the coordinates of the block, which
+ // is the same unless the block is rotated.)
+ if (word_res->box_word != nullptr) {
+ for (unsigned i = 0; i < word_res->box_word->length(); ++i) {
+ TBOX box = word_res->box_word->BlobBox(i);
+ box.move(image_vec);
+ word_res->box_word->ChangeBox(i, box);
+ }
+ }
+ }
+ }
+ }
+}
+
+// Counts the rows of a column's blocks, and those of them which are upside
+// down in the image.
+void CountUpsideDownRows(BLOCK_LIST *blocks, int *rows, int *upside_down) {
+ BLOCK_IT b_it(blocks);
+ for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
+ BLOCK *block = b_it.data();
+ const int num_rows = block->row_list()->length();
+ *rows += num_rows;
+ if (block->re_rotation().x() < -0.5f) {
+ *upside_down += num_rows;
+ }
+ }
+}
+
+} // namespace
+
+/**
+ * Multi-column (newspaper) recognition. Detects the vertical gutters that
+ * separate columns, recognises each column independently -- so that words from
+ * adjacent columns are never interleaved -- and merges the per-column results
+ * into a single page result in column-major reading order (the natural order
+ * for a newspaper body).
+ *
+ * Each column is cut out full-height along its gutters, which need not be
+ * vertical, and recognised with its own thresholded image, then its block
+ * geometry is shifted right by the left edge of the cut-out so that bounding
+ * boxes line up in full-page coordinates. The full-page
+ * thresholded image is restored before returning so the renderers convert
+ * boxes correctly.
+ *
+ * Returns 1 if the page was recognised by columns, and 0 if it was not split
+ * (no gutter is found: single-column or too-irregular page, or no column has
+ * text); in that case the caller should fall back to the normal recognition
+ * path. Returns -1 if the recognition of a column failed or was stopped by
+ * the monitor, as Recognize does for the page.
+ */
+int TessBaseAPI::RecognizeMultiColumn(ETEXT_DESC *monitor) {
+ if (tesseract_ == nullptr || thresholder_ == nullptr) {
+ return 0;
+ }
+ if (tesseract_->pix_binary() == nullptr &&
+ !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
+ return 0;
+ }
+ // Everything below works in the coordinate system of the (possibly
+ // sub-)rectangle that has been requested, because the renderers convert
+ // crop-relative boxes back to original-image coordinates by adding
+ // rect_left_/rect_top_.
+ const int rl = rect_left_;
+ const int rt = rect_top_;
+ const int rw = rect_width_;
+ const int rh = rect_height_;
+
+ std::vector<GutterX> gutters = DetectColumnGutters(tesseract_->pix_binary());
+ const int n = (int)gutters.size();
+ if (n < 1) {
+ return 0;
+ }
+
+ const int ncols = n + 1;
+
+ // The whole source image, from which the columns are cut. A column lies
+ // between two gutters which need not be vertical, so it is not a rectangle
+ // of the page: it is cut out with its bounding rectangle, and the parts of
+ // that rectangle which belong to the neighbouring columns are painted
+ // white.
+ thresholder_->SetRectangle(0, 0, image_width_, image_height_);
+ Image full_pix = thresholder_->GetPixRect();
+ // The columns are cut from an image without a colormap, in which white is
+ // known: with a colormap it can be any index.
+ Image cut_pix;
+ if (full_pix != nullptr) {
+ cut_pix = pixGetColormap(full_pix) != nullptr
+ ? Image(pixRemoveColormap(full_pix, REMOVE_CMAP_BASED_ON_SRC))
+ : full_pix.clone();
+ }
+ if (cut_pix == nullptr) {
+ full_pix.destroy();
+ thresholder_->SetRectangle(rl, rt, rw, rh);
+ return 0;
+ }
+ // SetImage takes the resolution from the image, which need not be the
+ // resolution of the page (SetSourceResolution, user_defined_dpi), so it is
+ // set again for each image.
+ const int source_yres = thresholder_->GetSourceYResolution();
+ // x coordinate (in rectangle coordinates) of the left edge of column c, or
+ // of the right edge of column c - 1, in row y.
+ auto edge_at = [&gutters, n, rw, rh](int c, int y) {
+ if (c <= 0) {
+ return 0;
+ }
+ if (c > n) {
+ return rw;
+ }
+ return ClipToRange(gutters[c - 1].XAtY(y, rh), 0, rw);
+ };
+
+ // Same one-time per-page configuration the normal flow performs.
+ tesseract_->SetBlackAndWhitelist();
+
+ std::vector<BLOCK_LIST *> col_blocks; // owns each column's recognised blocks
+ std::vector<PAGE_RES *> col_page_res; // per-column results (text in WERD_RES)
+ col_blocks.reserve(ncols);
+ col_page_res.reserve(ncols);
+ // Set if a column cannot be recognised, or if the monitor stops the
+ // recognition: the columns after it are not recognised.
+ bool failed = false;
+ int num_rows = 0;
+ int num_upside_down_rows = 0;
+
+ for (int c = 0; c < ncols && !failed; ++c) {
+ const int x0 = std::min(edge_at(c, 0), edge_at(c, rh - 1));
+ const int cw = std::max(edge_at(c + 1, 0), edge_at(c + 1, rh - 1)) - x0;
+ if (cw <= 0) {
+ continue;
+ }
+ Box *col_box = boxCreate(rl + x0, rt, cw, rh);
+ Pix *col_pix = pixClipRectangle(cut_pix, col_box, nullptr);
+ boxDestroy(&col_box);
+ if (col_pix == nullptr) {
+ continue;
+ }
+ // Paint the parts white which lie beyond the gutters.
+ const l_int32 white = pixGetDepth(col_pix) == 1 ? PIX_CLR : PIX_SET;
+ const int kRowStep = 8;
+ for (int y = 0; y < rh; y += kRowStep) {
+ const int mid_y = std::min(rh - 1, y + kRowStep / 2);
+ const int left = edge_at(c, mid_y) - x0;
+ if (left > 0) {
+ pixRasterop(col_pix, 0, y, left, kRowStep, white, nullptr, 0, 0);
+ }
+ const int right = std::max(0, edge_at(c + 1, mid_y) - x0);
+ if (right < cw) {
+ pixRasterop(col_pix, right, y, cw - right, kRowStep, white, nullptr, 0, 0);
+ }
+ }
+ // The column replaces the source image for now. ClearResults clears
+ // block_list_ / page_res_ and the working pix. block_list_ is guaranteed
+ // empty here (the previous column's blocks were extracted out below), so
+ // FindLines will re-segment.
+ thresholder_->SetImage(col_pix);
+ thresholder_->SetSourceYResolution(source_yres);
+ pixDestroy(&col_pix);
+ ClearResults();
+ if (!Threshold(&tesseract_->mutable_pix_binary()->pix_) ||
+ FindLines() != 0) {
+ failed = true;
+ break;
+ }
+ if (block_list_->empty()) {
+ continue;
+ }
+ // Recognise this column with its own (full-height) thresholded image.
+ PAGE_RES *res = new PAGE_RES(tesseract_->AnyLSTMLang(), block_list_,
+ &tesseract_->prev_word_best_choice_);
+ if (!tesseract_->recog_all_words(res, monitor, nullptr, nullptr, 0)) {
+ // Stopped by the monitor. The results of this column are kept, as the
+ // normal flow keeps those of the page.
+ failed = true;
+ }
+
+ // Move the recognised blocks out of the shared block_list_ into an owned
+ // list so they survive the next column's ClearResults (which clears the
+ // member block_list_). The PAGE_RES's WERD_RES point into these blocks.
+ BLOCK_LIST *own = new BLOCK_LIST;
+ {
+ BLOCK_IT from(block_list_);
+ BLOCK_IT to(own);
+ for (from.mark_cycle_pt(); !from.cycled_list(); from.forward()) {
+ to.add_to_end(from.extract());
+ }
+ }
+ CountUpsideDownRows(own, &num_rows, &num_upside_down_rows);
+ // Bring the column's boxes into rectangle coordinates. (Full-height crops
+ // keep y in rectangle coordinates already, so only x needs shifting.)
+ ShiftColumnGeometry(own, res, x0);
+ col_blocks.push_back(own);
+ col_page_res.push_back(res);
+ }
+ cut_pix.destroy();
+
+ // Remove what the last column left: its images, and its blocks if it could
+ // not be recognised.
+ ClearResults();
+ // Put the whole source image back, and restore the rectangle thresholded
+ // image and rect so the renderers convert boxes into the correct
+ // (rectangle) coordinates. Re-thresholding the full rectangle reproduces
+ // exactly the state the normal single-page flow leaves (full rectangle pix
+ // + rect_*), and the merged blobs are already in rectangle coordinates.
+ thresholder_->SetImage(full_pix);
+ thresholder_->SetSourceYResolution(source_yres);
+ full_pix.destroy();
+ thresholder_->SetRectangle(rl, rt, rw, rh);
+ if (!Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
+ // Without the image there is nothing which the results can be used with.
+ tesseract_->prev_word_best_choice_ = nullptr;
+ for (auto *res : col_page_res) {
+ delete res;
+ }
+ for (auto *own : col_blocks) {
+ delete own;
+ }
+ ClearResults();
+ return -1;
+ }
+ if (col_page_res.empty()) {
+ // No column has text. block_list_ is empty, so the FindLines() of the
+ // normal single-page recognition path will segment the whole page.
+ return failed ? -1 : 0;
+ }
+ // The columns of a page which is upside down are read from right to left.
+ if (2 * num_upside_down_rows > num_rows) {
+ std::reverse(col_page_res.begin(), col_page_res.end());
+ std::reverse(col_blocks.begin(), col_blocks.end());
+ }
+
+ // Merge the per-column results into a single page result, in column-major
+ // reading order (the per-column block lists are already top-to-bottom).
+ page_res_ = new PAGE_RES();
+ page_res_->prev_word_best_choice = &tesseract_->prev_word_best_choice_;
+ for (auto *res : col_page_res) {
+ {
+ BLOCK_RES_IT src(&res->block_res_list);
+ BLOCK_RES_IT dst(&page_res_->block_res_list);
+ for (src.mark_cycle_pt(); !src.cycled_list(); src.forward()) {
+ dst.add_to_end(src.extract());
+ }
+ }
+ page_res_->char_count += res->char_count;
+ page_res_->rej_count += res->rej_count;
+ delete res; // frees the per-column results; blocks live on in col_blocks.
+ }
+
+ // Hand the blocks back to the shared block_list_ so that the next
+ // ClearResults() frees them (page_res_ holds non-owning references to them).
+ for (auto *own : col_blocks) {
+ BLOCK_IT from(own);
+ BLOCK_IT to(block_list_);
+ for (from.mark_cycle_pt(); !from.cycled_list(); from.forward()) {
+ to.add_to_end(from.extract());
+ }
+ delete own;
+ }
+ recognition_done_ = true;
+ tesseract_->set_auto_columns_used(static_cast<int>(col_page_res.size()));
+ if (failed) {
+ return -1;
+ }
+ // Mirror the normal flow's paragraph detection, now run on the merged,
+ // column-major page. Without the text (paragraph_text_based off) the normal
+ // flow runs it before the recognition; it does not need the text, so it can
+ // run here too.
+ bool wait_for_text = true;
+ GetBoolVariable("paragraph_text_based", &wait_for_text);
+ DetectParagraphs(wait_for_text);
+ return 1;
+}
+
/**
* Return average gradient of lines on page.
*/
diff --git a/src/ccmain/tesseractclass.cpp b/src/ccmain/tesseractclass.cpp
index 73e75225..102a3832 100644
--- a/src/ccmain/tesseractclass.cpp
+++ b/src/ccmain/tesseractclass.cpp
@@ -402,6 +402,11 @@ Tesseract::Tesseract()
this->params())
, BOOL_MEMBER(textord_tabfind_show_vlines, false, "Debug line finding", this->params())
, BOOL_MEMBER(textord_use_cjk_fp_model, false, "Use CJK fixed pitch model", this->params())
+ , BOOL_MEMBER(textord_auto_columns, false,
+ "Automatically detect and split multi-column (newspaper) "
+ "layouts, recognising each column independently and merging "
+ "the results in column-major reading order",
+ this->params())
, BOOL_MEMBER(poly_allow_detailed_fx, false,
"Allow feature extractors to see the original outline", this->params())
, BOOL_INIT_MEMBER(tessedit_init_config_only, false,
diff --git a/src/ccmain/tesseractclass.h b/src/ccmain/tesseractclass.h
index 32fa595a..38ec4e1d 100644
--- a/src/ccmain/tesseractclass.h
+++ b/src/ccmain/tesseractclass.h
@@ -257,6 +257,14 @@ public:
void set_source_resolution(int ppi) {
source_resolution_ = ppi;
}
+ // Number of columns which the automatic multi-column recognition
+ // (textord_auto_columns) used for the last page, 0 if it did not split it.
+ int auto_columns_used() const {
+ return auto_columns_used_;
+ }
+ void set_auto_columns_used(int columns) {
+ auto_columns_used_ = columns;
+ }
int ImageWidth() const {
return pixGetWidth(pix_binary_);
}
@@ -957,6 +965,7 @@ public:
double_VAR_H(min_orientation_margin);
BOOL_VAR_H(textord_tabfind_show_vlines);
BOOL_VAR_H(textord_use_cjk_fp_model);
+ BOOL_VAR_H(textord_auto_columns);
BOOL_VAR_H(poly_allow_detailed_fx);
BOOL_VAR_H(tessedit_init_config_only);
#ifndef DISABLED_LEGACY_ENGINE
@@ -991,6 +1000,8 @@ private:
// Image used for input to layout analysis and tesseract recognition.
// May be modified by the ShiroRekhaSplitter to eliminate the top-line.
Image pix_binary_;
+ // Columns used by the last automatic multi-column recognition (0 = none).
+ int auto_columns_used_ = 0;
// The pixels of the lines which the layout analysis removed from the binary
// image, or nullptr. Kept for the font style pass, which needs them to find
// underlined words.
diff --git a/unittest/CMakeLists.txt b/unittest/CMakeLists.txt
index d7ac0106..3e65620b 100644
--- a/unittest/CMakeLists.txt
+++ b/unittest/CMakeLists.txt
@@ -116,7 +116,10 @@ foreach(test_source IN LISTS TEST_SOURCES)
target_link_libraries(${test_name} PRIVATE GTest::gmock)
endif()
target_compile_definitions(${test_name} PRIVATE ${COMMON_COMPILE_DEFINITIONS})
- target_include_directories(${test_name} PRIVATE ${COMMON_INCLUDE_DIRS})
+ # BEFORE: the in-tree include/ must take precedence over any system-installed
+ # Tesseract headers (e.g. a Homebrew tesseract in the same prefix as TIFF),
+ # matching how libtesseract itself is compiled.
+ target_include_directories(${test_name} BEFORE PRIVATE ${COMMON_INCLUDE_DIRS})
target_link_libraries(${test_name} PRIVATE ${COMMON_LINK_LIBS})
add_test(NAME ${test_name} COMMAND ${test_name})
endforeach()
diff --git a/unittest/multicolumn_test.cc b/unittest/multicolumn_test.cc
new file mode 100644
index 00000000..c7eec53a
--- /dev/null
+++ b/unittest/multicolumn_test.cc
@@ -0,0 +1,459 @@
+// (C) Copyright 2026, Tesseract contributors.
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "include_gunit.h"
+
+#include <tesseract/baseapi.h>
+#include <tesseract/renderer.h>
+#include <tesseract/resultiterator.h>
+
+#include <tesseract/ocrclass.h> // for ETEXT_DESC
+
+#include "image.h" // for Image
+#include "tesseractclass.h" // for Tesseract::auto_columns_used
+
+#include <algorithm> // for std::max, std::min
+#include <climits> // for INT_MAX, INT_MIN
+#include <memory>
+#include <string>
+
+namespace tesseract {
+
+// Test the automatic multi-column (newspaper) recognition path
+// (textord_auto_columns). It detects the vertical gutters between columns,
+// recognises each column independently and merges the per-column results back
+// into a single page. When no gutter is found it must fall back to the normal
+// single-page path and produce exactly the same output.
+//
+// These tests double as the AddressSanitizer/UndefinedBehaviorSanitizer
+// coverage for that path: Recognizing a multi-column page moves BLOCK /
+// BLOCK_RES / ROW / WERD / C_BLOB nodes between BLOCK_LIST and PAGE_RES
+// containers and restores the full-page thresholded image, which is exactly
+// the kind of intrusive-list / pix ownership handling the sanitizer build
+// wants to exercise.
+//
+// 8071_093.3B.tif is a genuine two-column newspaper page that the gutter
+// detector triggers on (it splits into two columns), which drives the full
+// split + recognise + merge path. phototest.tif is a single-column page that
+// yields no gutter, which drives the safe no-split fallback.
+class FriendlyTessBaseAPI : public tesseract::TessBaseAPI {
+ public:
+ // Expose the number of columns the automatic multi-column path used for
+ // the last recognised page, without adding anything to the public API: the
+ // count is kept in the internal Tesseract class.
+ int auto_columns_used() const {
+ return tesseract_->auto_columns_used();
+ }
+};
+
+class MultiColumnTest : public testing::Test {
+ protected:
+ static std::string TestDataNameToPath(const std::string &name) {
+ return file::JoinPath(TESTING_DIR, name);
+ }
+ static std::string TessdataPath() {
+ return TESSDATA_DIR;
+ }
+
+ void SetUp() override {
+ REQUIRE_TRAINEDDATA(TESSDATA_DIR, "eng");
+ if (api_.Init(TessdataPath().c_str(), "eng", tesseract::OEM_LSTM_ONLY) == -1) {
+ // eng.traineddata not found.
+ GTEST_SKIP();
+ }
+ api_.SetPageSegMode(tesseract::PSM_AUTO);
+ }
+
+ // Reads the named test image.
+ static Image ReadImage(const std::string &image) {
+ return pixRead(TestDataNameToPath(image).c_str());
+ }
+
+ // Gives the image to the API, with textord_auto_columns set to |enable|.
+ // Takes the image.
+ void SetPage(Image pix, const std::string &name, const std::string &enable) {
+ ASSERT_TRUE(pix) << "Could not read " << name;
+ ASSERT_TRUE(api_.SetVariable("textord_auto_columns", enable.c_str()));
+ api_.SetInputName(name.c_str());
+ api_.SetImage(pix);
+ pix.destroy(); // SetImage clones, so the caller's copy is no longer needed.
+ }
+
+ // Recognise the image with textord_auto_columns set to |enable|. Takes the
+ // image. On success (assertion failures abort the test), the UTF-8 text and
+ // the number of columns the automatic path used (0 => it fell back to the
+ // normal single-page path) are stored in last_text_ and last_columns_.
+ void Recognise(Image pix, const std::string &name,
+ const std::string &enable) {
+ SetPage(pix, name, enable);
+ ASSERT_EQ(api_.Recognize(nullptr), 0) << "Recognize failed on " << name;
+ last_columns_ = api_.auto_columns_used();
+ char *utf8 = api_.GetUTF8Text();
+ ASSERT_TRUE(utf8 != nullptr);
+ last_text_ = utf8;
+ delete[] utf8;
+ }
+
+ // The same for the named test image.
+ void Recognise(const std::string &image, const std::string &enable) {
+ Recognise(ReadImage(image), image, enable);
+ }
+
+ // Checks that the geometry of the recognised page is in the coordinates of
+ // the page, at all levels: a symbol lies in its word, a word in its text
+ // line and a text line in its paragraph (horizontally, as a column is
+ // shifted horizontally), and the baseline of a text line and the polygon
+ // of a block are where the text line and the block are.
+ // Only text blocks are checked. For a page which is not upright the symbols
+ // are left out (the boxes of the symbols which the LSTM recognizer returns
+ // for rotated text are not in the coordinates of the image, with or without
+ // columns), and a few words may lie outside of their text line (noise at
+ // the edge of a column which the recognizer takes for a word).
+ void CheckGeometry(bool upright) {
+ std::unique_ptr<ResultIterator> it(api_.GetIterator());
+ ASSERT_NE(it, nullptr);
+ ASSERT_NE(api_.GetInputImage(), nullptr);
+ const int page_width = pixGetWidth(api_.GetInputImage());
+ int para_left = 0, para_right = 0;
+ int line_left = 0, line_right = 0;
+ int word_left = 0, word_right = 0;
+ int top, bottom;
+ int num_blocks = 0, num_lines = 0, num_words = 0, num_symbols = 0;
+ int bad_polygons = 0, bad_lines = 0, bad_baselines = 0, bad_words = 0;
+ int bad_symbols = 0;
+ int words_in_right_half = 0;
+ do {
+ if (!PTIsTextType(it->BlockType())) {
+ continue;
+ }
+ if (it->IsAtBeginningOf(RIL_BLOCK)) {
+ int block_left, block_right;
+ ASSERT_TRUE(it->BoundingBox(RIL_BLOCK, &block_left, &top, &block_right,
+ &bottom));
+ Pta *polygon = it->BlockPolygon();
+ if (polygon != nullptr) {
+ int min_x = INT_MAX;
+ int max_x = INT_MIN;
+ for (int i = 0; i < ptaGetCount(polygon); ++i) {
+ int x, y;
+ ptaGetIPt(polygon, i, &x, &y);
+ min_x = std::min(min_x, x);
+ max_x = std::max(max_x, x);
+ }
+ ptaDestroy(&polygon);
+ ++num_blocks;
+ // The text of a block lies in its polygon.
+ if (block_left < min_x || block_right > max_x) {
+ ++bad_polygons;
+ }
+ }
+ }
+ if (it->IsAtBeginningOf(RIL_PARA)) {
+ ASSERT_TRUE(
+ it->BoundingBox(RIL_PARA, ¶_left, &top, ¶_right, &bottom));
+ }
+ if (it->IsAtBeginningOf(RIL_TEXTLINE)) {
+ ASSERT_TRUE(it->BoundingBox(RIL_TEXTLINE, &line_left, &top, &line_right,
+ &bottom));
+ ++num_lines;
+ if (line_left < para_left || line_right > para_right) {
+ ++bad_lines;
+ }
+ int x1, y1, x2, y2;
+ ASSERT_TRUE(it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2));
+ // The baseline and the text line overlap horizontally.
+ if (std::max(x1, x2) <= line_left || std::min(x1, x2) >= line_right) {
+ ++bad_baselines;
+ }
+ }
+ if (it->IsAtBeginningOf(RIL_WORD)) {
+ ASSERT_TRUE(
+ it->BoundingBox(RIL_WORD, &word_left, &top, &word_right, &bottom));
+ ++num_words;
+ if (word_left < line_left || word_right > line_right) {
+ ++bad_words;
+ }
+ if (word_left > page_width / 2) {
+ ++words_in_right_half;
+ }
+ }
+ int symbol_left, symbol_right;
+ if (upright && it->BoundingBox(RIL_SYMBOL, &symbol_left, &top,
+ &symbol_right, &bottom)) {
+ ++num_symbols;
+ if (symbol_left < word_left || symbol_right > word_right) {
+ ++bad_symbols;
+ }
+ }
+ } while (it->Next(RIL_SYMBOL));
+ EXPECT_GT(num_blocks, 1);
+ EXPECT_GT(num_lines, 100);
+ EXPECT_GT(num_words, 500);
+ if (upright) {
+ EXPECT_GT(num_symbols, 2000);
+ }
+ // The page has four columns of text, two of them in its right half.
+ EXPECT_GT(words_in_right_half, num_words / 4);
+ EXPECT_EQ(bad_polygons, 0) << "of " << num_blocks << " blocks";
+ EXPECT_EQ(bad_lines, 0) << "of " << num_lines << " text lines";
+ EXPECT_EQ(bad_baselines, 0) << "of " << num_lines << " text lines";
+ EXPECT_LE(bad_words, upright ? 0 : num_words / 100)
+ << "of " << num_words << " words";
+ EXPECT_EQ(bad_symbols, 0) << "of " << num_symbols << " symbols";
+ }
+
+ // Returns the number of blocks and of paragraphs of the recognised page.
+ void CountBlocksAndParagraphs(int *blocks, int *paragraphs) {
+ *blocks = 0;
+ *paragraphs = 0;
+ std::unique_ptr<ResultIterator> it(api_.GetIterator());
+ ASSERT_NE(it, nullptr);
+ do {
+ if (it->IsAtBeginningOf(RIL_BLOCK)) {
+ ++*blocks;
+ }
+ ++*paragraphs;
+ } while (it->Next(RIL_PARA));
+ }
+
+ FriendlyTessBaseAPI api_;
+ std::string last_text_;
+ int last_columns_ = 0;
+};
+
+// A genuine multi-column page must be split into more than one column, and
+// the merged result must contain recognisable text and well-formed layout.
+TEST_F(MultiColumnTest, SplitsMultiColumnPage) {
+ Recognise("8071_093.3B.tif", "1");
+ // The detector must have found a gutter, so the automatic path -- not the
+ // fallback -- ran, and it split the page into at least two columns.
+ EXPECT_GE(last_columns_, 2) << "Expected the automatic path to split 8071 into "
+ "columns, but it reported "
+ << last_columns_;
+
+ // Merged text must be non-trivial.
+ EXPECT_GE(last_text_.size(), 50u)
+ << "Multi-column page produced too little text";
+
+ // hOCR rendering walks every merged line/word box (whose coordinates were
+ // shifted into full-page space). It must succeed and emit word boxes.
+ ASSERT_TRUE(api_.SetVariable("textord_auto_columns", "1"));
+ Image pix = pixRead(TestDataNameToPath("8071_093.3B.tif").c_str());
+ ASSERT_TRUE(pix);
+ api_.SetInputName("8071_093.3B.tif");
+ api_.SetImage(pix);
+ pix.destroy();
+ ASSERT_EQ(api_.Recognize(nullptr), 0);
+ char *hocr = api_.GetHOCRText(0);
+ ASSERT_TRUE(hocr != nullptr);
+ const std::string hocr_str(hocr);
+ EXPECT_NE(hocr_str.find("class='ocr_page'"), std::string::npos)
+ << "hOCR output is missing the page element";
+ EXPECT_NE(hocr_str.find("ocrx_word"), std::string::npos)
+ << "hOCR output is missing word boxes";
+ delete[] hocr;
+}
+
+// The geometry of all columns must be in the coordinates of the page, at all
+// levels: a symbol lies in its word, a word in its text line and a text line
+// in its paragraph (horizontally, as a column is shifted horizontally), and
+// the baseline of a text line and the polygon of a block are where the text
+// line and the block are. The words of a text line which the LSTM recognizer
+// returns are not the words of the row, and the row, the block and the
+// symbols keep boxes of their own, so each of them can be left behind in the
+// coordinates of its column.
+TEST_F(MultiColumnTest, GeometryInPageCoordinates) {
+ Recognise("8071_093.3B.tif", "1");
+ ASSERT_GE(last_columns_, 2);
+ CheckGeometry(true);
+}
+
+// The same for a page which is upside down. The coordinates of its blocks
+// are rotated against the image, so a column which is shifted to the right
+// in the coordinates of its blocks moves to the left in the image. And its
+// columns are read from right to left.
+TEST_F(MultiColumnTest, GeometryOfPageUpsideDown) {
+#ifdef DISABLED_LEGACY_ENGINE
+ // The orientation detection needs the legacy engine.
+ GTEST_SKIP();
+#else
+ REQUIRE_TRAINEDDATA(TESSDATA_DIR, "osd");
+ api_.SetPageSegMode(tesseract::PSM_AUTO_OSD);
+ Image upright = ReadImage("8071_093.3B.tif");
+ ASSERT_TRUE(upright);
+ Image pix = pixRotate180(nullptr, upright);
+ upright.destroy();
+ Recognise(pix, "8071_093.3B.tif", "1");
+ ASSERT_GE(last_columns_, 2);
+ CheckGeometry(false);
+ // The text begins with the first line of the first column, which is the
+ // rightmost one in the image.
+ const size_t heading = last_text_.find("sighed");
+ ASSERT_NE(heading, std::string::npos);
+ EXPECT_LT(heading, last_text_.size() / 10);
+#endif
+}
+
+// The recognition of a page which the monitor stops must be reported as
+// failed, as it is without the columns.
+TEST_F(MultiColumnTest, CancelIsReported) {
+ for (const char *enable : {"0", "1"}) {
+ SetPage(ReadImage("8071_093.3B.tif"), "8071_093.3B.tif", enable);
+ ETEXT_DESC monitor;
+ monitor.cancel = [](void *, int) { return true; };
+ EXPECT_EQ(api_.Recognize(&monitor), -1)
+ << "with textord_auto_columns " << enable;
+ }
+}
+
+// The resolution which the application sets for the page must survive the
+// recognition of the columns, which are images of their own.
+TEST_F(MultiColumnTest, KeepsSourceResolution) {
+ for (const char *enable : {"0", "1"}) {
+ SetPage(ReadImage("8071_093.3B.tif"), "8071_093.3B.tif", enable);
+ ASSERT_NE(api_.GetSourceYResolution(), 250);
+ api_.SetSourceResolution(250);
+ ASSERT_EQ(api_.Recognize(nullptr), 0);
+ EXPECT_EQ(api_.auto_columns_used() >= 2, enable[0] == '1');
+ EXPECT_EQ(api_.GetSourceYResolution(), 250)
+ << "with textord_auto_columns " << enable;
+ }
+}
+
+// The modes of Recognize which do not recognise the page in the normal way
+// must not be replaced by the recognition of the columns. Making training
+// data for the line recognizer is such a mode: it needs a box file, which the
+// page does not have, so it fails.
+TEST_F(MultiColumnTest, OtherModesAreNotSplit) {
+ ASSERT_TRUE(api_.SetVariable("tessedit_train_line_recognizer", "1"));
+ SetPage(ReadImage("8071_093.3B.tif"), "8071_093.3B.tif", "1");
+ EXPECT_EQ(api_.Recognize(nullptr), -1);
+ EXPECT_EQ(api_.auto_columns_used(), 0);
+}
+
+// A page segmentation mode without column finding says that the page is a
+// single column, block, line or word, so the page must not be split. Such a
+// mode also takes the blocks from a zone file for the whole page if there is
+// one next to the image, as for this page.
+TEST_F(MultiColumnTest, SingleBlockModeIsNotSplit) {
+ api_.SetPageSegMode(tesseract::PSM_SINGLE_BLOCK);
+ SetPage(ReadImage("8071_093.3B.tif"), TestDataNameToPath("8071_093.3B.tif"),
+ "1");
+ EXPECT_EQ(api_.Recognize(nullptr), 0);
+ EXPECT_EQ(api_.auto_columns_used(), 0);
+}
+
+// Paragraphs must be found in the columns too when they are detected without
+// the text (paragraph_text_based off).
+TEST_F(MultiColumnTest, ParagraphsWithoutText) {
+ ASSERT_TRUE(api_.SetVariable("paragraph_text_based", "0"));
+ Recognise("8071_093.3B.tif", "1");
+ ASSERT_GE(last_columns_, 2);
+ int blocks, paragraphs;
+ CountBlocksAndParagraphs(&blocks, ¶graphs);
+ EXPECT_GT(blocks, 1);
+ // Without the detection each block is one paragraph.
+ EXPECT_GT(paragraphs, blocks);
+}
+
+// A block of vertical text in a column is rotated in the coordinates of its
+// block, so it must not be shifted to the right in these coordinates.
+TEST_F(MultiColumnTest, VerticalTextInColumn) {
+ Image page = ReadImage("8071_093.3B.tif");
+ ASSERT_TRUE(page);
+ ASSERT_EQ(pixGetDepth(page), 1);
+ // Replace the upper part of the last column by a copy of the upper part of
+ // the first column which is rotated by 90 degrees.
+ const int kLeft = 2400, kTop = 140, kWidth = 680, kHeight = 760;
+ Box *box = boxCreate(170, 150, 640, 580);
+ Image lines = pixClipRectangle(page, box, nullptr);
+ boxDestroy(&box);
+ ASSERT_TRUE(lines);
+ Image vertical = pixRotate90(lines, -1);
+ lines.destroy();
+ ASSERT_TRUE(vertical);
+ pixRasterop(page, kLeft, kTop, kWidth, kHeight, PIX_CLR, nullptr, 0, 0);
+ pixRasterop(page, kLeft + 40, kTop + 30, pixGetWidth(vertical),
+ pixGetHeight(vertical), PIX_SRC, vertical, 0, 0);
+ vertical.destroy();
+ Recognise(page, "vertical text", "1");
+ ASSERT_GE(last_columns_, 2);
+ // Count the text lines in that part of the page which are much higher than
+ // wide. The rotated copy has 14 text lines.
+ std::unique_ptr<ResultIterator> it(api_.GetIterator());
+ ASSERT_NE(it, nullptr);
+ int num_vertical_lines = 0;
+ do {
+ int left, top, right, bottom;
+ if (it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom) &&
+ bottom - top > 3 * (right - left) && left >= kLeft && top >= kTop &&
+ right <= kLeft + kWidth && bottom <= kTop + kHeight) {
+ ++num_vertical_lines;
+ }
+ } while (it->Next(RIL_TEXTLINE));
+ EXPECT_GE(num_vertical_lines, 10);
+}
+
+// A gutter of a page which is not quite upright is slanted, so the columns
+// are cut out along slanted lines and what lies beyond them is painted
+// white. White must be white for an image with a colormap too, where the
+// highest pixel value can be any colour, or no colour of the colormap at all.
+TEST_F(MultiColumnTest, SkewedPageWithColormap) {
+ Image upright = ReadImage("8071_093.3B.tif");
+ ASSERT_TRUE(upright);
+ // Rotate by one degree.
+ Image skewed =
+ pixRotate(upright, 0.0175f, L_ROTATE_SHEAR, L_BRING_IN_WHITE, 0, 0);
+ upright.destroy();
+ ASSERT_TRUE(skewed);
+ ASSERT_EQ(pixGetDepth(skewed), 1);
+ // The same page with the pixel values 0 (white) and 1 (black) and a
+ // colormap with 256 colours. The page does not use the other 254 colours,
+ // so the text must not depend on them.
+ std::string texts[2];
+ for (int i = 0; i < 2; ++i) {
+ const int unused_colour = i == 0 ? 255 : 0;
+ Image with_colormap = pixConvert1To8(nullptr, skewed, 0, 1);
+ ASSERT_TRUE(with_colormap);
+ PIXCMAP *colormap = pixcmapCreate(8);
+ pixcmapAddColor(colormap, 255, 255, 255);
+ pixcmapAddColor(colormap, 0, 0, 0);
+ for (int c = 2; c < 256; ++c) {
+ pixcmapAddColor(colormap, unused_colour, unused_colour, unused_colour);
+ }
+ ASSERT_EQ(pixSetColormap(with_colormap, colormap), 0);
+ Recognise(with_colormap, "skewed with colormap", "1");
+ ASSERT_GE(last_columns_, 2);
+ EXPECT_GE(last_text_.size(), 3000u);
+ texts[i] = last_text_;
+ }
+ skewed.destroy();
+ EXPECT_EQ(texts[0], texts[1]);
+}
+
+// On a single-column page the automatic path must not split at all and must
+// fall back to the normal path, yielding output identical to the flag-off run.
+TEST_F(MultiColumnTest, NoSplitOnSingleColumnPage) {
+ Recognise("phototest.tif", "0");
+ const std::string off_text = last_text_;
+ const int off_columns = last_columns_;
+
+ Recognise("phototest.tif", "1");
+
+ // No gutter => the automatic path fell back to the normal single-page path.
+ EXPECT_EQ(off_columns, 0) << "Expected no column split with the flag off";
+ EXPECT_EQ(last_columns_, 0) << "Expected no column split on single-column page";
+
+ // The output must be byte-for-byte identical to the disabled run.
+ EXPECT_EQ(off_text, last_text_) << "Flag-on output differs from flag-off output";
+}
+
+} // namespace tesseract