Commit bc852c42 for tesseract
commit bc852c4265edef3e6ece70266a534e06f0de4e3e
Author: Stefan Weil <sw@weilnetz.de>
Date: Fri Nov 20 20:05:24 2026 +0100
Estimate bold and italic for words recognized by LSTM
The legacy engine gets the font of a word from its character
classifier. LSTM has no such information, so WordFontAttributes
reported neither bold nor italic for its words, and the hOCR output
had no <strong> and <em> elements.
Add the parameter lstm_font_attributes (default off). With it, a new
pass estimates both attributes from the binary image of each word
which has no font:
- Italic is the slant of the strokes relative to the baseline. The
word image is sheared in steps of a quarter pixel per row, and the
slant with the sharpest column sums wins. Letters with diagonal
strokes like v, w and y are erased first, using the recognized text
and the character boxes, because their strokes look like the stems
of italic text.
- Bold is the stroke width (the median length of the horizontal runs)
relative to the x-height, compared with the median of the page.
- Words with fewer than three letters or digits take the attributes
of their neighbours in the text line where these agree.
The result is stored like a font of the legacy engine: the word gets
a FontInfo, here one of four entries without a name. Therefore
WordFontAttributes now reports the attributes of a font without a name
(it returns nullptr and the font id -1), and FontInfo can be compared
without a name. A font classifier for LSTM can fill the same field
later. fontinfo.h is now also needed without the legacy engine.
Results per word for 42 rendered pages with mixed styles (14 fonts,
8, 10 and 12 pt at 300 dpi, about 8900 words, tessdata_fast eng):
italic with 98.9 % precision and 97.7 % recall, bold with 99.8 %
precision and 93.6 % recall. The same pages with a skew of 1.5
degrees, scaled to 60 % or blurred give 98 to 99 % and 96 to 98 % for
italic, and 96 to 100 % and 88 to 95 % for bold. The run time does
not change measurably.
The thresholds were only tuned with rendered pages, not with scans.
A page which is bold throughout gets no bold words, and text in
rotated blocks gets no attributes.
Assisted-by: Claude Fable 5.2 (Anthropic)
Signed-off-by: Stefan Weil <sw@weilnetz.de>
diff --git a/Makefile.am b/Makefile.am
index 129ede5f..457a8d40 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -234,6 +234,7 @@ libtesseract_la_SOURCES += src/arch/simddetect.cpp
# Rules for src/ccmain.
noinst_HEADERS += src/ccmain/control.h
+noinst_HEADERS += src/ccmain/fontstyle.h
noinst_HEADERS += src/ccmain/mutableiterator.h
noinst_HEADERS += src/ccmain/output.h
noinst_HEADERS += src/ccmain/paragraphs.h
@@ -253,6 +254,7 @@ endif
libtesseract_la_SOURCES += src/ccmain/applybox.cpp
libtesseract_la_SOURCES += src/ccmain/control.cpp
+libtesseract_la_SOURCES += src/ccmain/fontstyle.cpp
libtesseract_la_SOURCES += src/ccmain/linerec.cpp
libtesseract_la_SOURCES += src/ccmain/ltrresultiterator.cpp
libtesseract_la_SOURCES += src/ccmain/mutableiterator.cpp
@@ -300,6 +302,7 @@ noinst_HEADERS += src/ccstruct/crakedge.h
noinst_HEADERS += src/ccstruct/debugpixa.h
noinst_HEADERS += src/ccstruct/detlinefit.h
noinst_HEADERS += src/ccstruct/dppoint.h
+noinst_HEADERS += src/ccstruct/fontinfo.h
noinst_HEADERS += src/ccstruct/image.h
noinst_HEADERS += src/ccstruct/imagedata.h
noinst_HEADERS += src/ccstruct/linlsq.h
@@ -326,7 +329,6 @@ noinst_HEADERS += src/ccstruct/statistc.h
noinst_HEADERS += src/ccstruct/stepblob.h
noinst_HEADERS += src/ccstruct/werd.h
if !DISABLED_LEGACY_ENGINE
-noinst_HEADERS += src/ccstruct/fontinfo.h
noinst_HEADERS += src/ccstruct/params_training_featdef.h
endif
@@ -1177,6 +1179,7 @@ check_PROGRAMS += equationdetect_test
endif # !DISABLED_LEGACY_ENGINE
check_PROGRAMS += fileio_test
check_PROGRAMS += fontattributes_test
+check_PROGRAMS += fontstyle_test
check_PROGRAMS += fullyconnected_test
check_PROGRAMS += functions_test
check_PROGRAMS += genericvector_test
@@ -1356,6 +1359,10 @@ fontattributes_test_SOURCES = unittest/fontattributes_test.cc
fontattributes_test_CPPFLAGS = $(unittest_CPPFLAGS)
fontattributes_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS)
+fontstyle_test_SOURCES = unittest/fontstyle_test.cc
+fontstyle_test_CPPFLAGS = $(unittest_CPPFLAGS)
+fontstyle_test_LDADD = $(TESS_LIBS) $(LEPTONICA_LIBS)
+
fullyconnected_test_SOURCES = unittest/fullyconnected_test.cc
fullyconnected_test_CPPFLAGS = $(unittest_CPPFLAGS)
fullyconnected_test_LDADD = $(TESS_LIBS)
diff --git a/cmake/SourceLists.cmake b/cmake/SourceLists.cmake
index c2bca5ac..c413163e 100644
--- a/cmake/SourceLists.cmake
+++ b/cmake/SourceLists.cmake
@@ -56,6 +56,7 @@ set(TESSERACT_SRC_CCMAIN
src/ccmain/applybox.cpp
src/ccmain/control.cpp
src/ccmain/docqual.cpp
+ src/ccmain/fontstyle.cpp
src/ccmain/equationdetect.cpp
src/ccmain/fixspace.cpp
src/ccmain/fixxht.cpp
@@ -375,6 +376,7 @@ set(TESSERACT_HDR_INTERNAL
src/ccmain/docqual.h
src/ccmain/equationdetect.h
src/ccmain/fixspace.h
+ src/ccmain/fontstyle.h
src/ccmain/mutableiterator.h
src/ccmain/output.h
src/ccmain/paragraphs.h
diff --git a/doc/tesseract.1.asc b/doc/tesseract.1.asc
index a9da4839..bac5d245 100644
--- a/doc/tesseract.1.asc
+++ b/doc/tesseract.1.asc
@@ -440,8 +440,8 @@ OUTPUT FORMAT PARAMETERS
Add per-word font metadata to hOCR output. When enabled, each word span
includes `x_font` (font name) and `x_fsize` (point size) attributes in its
`title` field. Font information is derived from the recognition results and
- is most reliable with the Legacy OCR engine; the LSTM engine may produce
- less precise font names.
+ is most reliable with the Legacy OCR engine; the LSTM engine reports no
+ font names. See also *lstm_font_attributes*.
*hocr_char_boxes* (bool, default: 0) [Both]::
Add per-character bounding-box coordinates to hOCR output as `ocrx_cinfo`
@@ -658,6 +658,20 @@ These parameters are only meaningful when using the LSTM OCR engine
Number of cascading beam-search iterations used when *lstm_choice_mode* is
non-zero.
+*lstm_font_attributes* (bool, default: 0) [LSTM]::
+ Estimate the font attributes bold and italic for the words recognized by
+ the LSTM engine, which does not detect fonts. Italic is derived from the
+ slant of the strokes in the binary image relative to the baseline; letters
+ with diagonal strokes such as v, w and y are left out. Bold is derived
+ from the width of the strokes relative to the x-height and to the typical
+ word of the page, so a page which is bold throughout is not reported as
+ bold. Words with fewer than three letters or digits take the attributes
+ of their neighbours in the text line where these agree. Text in rotated
+ blocks gets no attributes. The result has no font name; it is used for
+ the `<strong>` and `<em>` elements of the hOCR output and returned by the
+ API function `WordFontAttributes`. With *tessedit_debug_fonts* the
+ measurements of each word are printed.
+
*lstm_rating_coefficient* (double, default: 5) [LSTM]::
Scaling factor applied to LSTM character ratings. Smaller values produce
higher (better) confidence scores and preserve more information before the
diff --git a/include/tesseract/ltrresultiterator.h b/include/tesseract/ltrresultiterator.h
index 6ca0a98e..7353030b 100644
--- a/include/tesseract/ltrresultiterator.h
+++ b/include/tesseract/ltrresultiterator.h
@@ -100,6 +100,10 @@ public:
// to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as
// the iterator itself, ie rendered invalid by various members of
// TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI.
+ // The return value is nullptr if the font name is not known. The attributes
+ // can be set nevertheless: with the parameter lstm_font_attributes, bold
+ // and italic are estimated for words recognized by LSTM, which have no font
+ // name and the font_id -1.
// Pointsize is returned in printers points (1/72 inch.)
const char *WordFontAttributes(bool *is_bold, bool *is_italic,
bool *is_underlined, bool *is_monospace,
diff --git a/src/ccmain/control.cpp b/src/ccmain/control.cpp
index 235186fd..6b81b17f 100644
--- a/src/ccmain/control.cpp
+++ b/src/ccmain/control.cpp
@@ -461,6 +461,12 @@ bool Tesseract::recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor,
#endif // ndef DISABLED_LEGACY_ENGINE
+ // The words which LSTM recognized have no font. Estimate bold and italic
+ // for them from the image.
+ if (lstm_font_attributes && AnyLSTMLang()) {
+ font_style_pass(page_res);
+ }
+
// Write results pass.
// This is now redundant, but retained commented so show how to obtain
// bounding boxes and style information.
diff --git a/src/ccmain/fontstyle.cpp b/src/ccmain/fontstyle.cpp
new file mode 100644
index 00000000..788f855f
--- /dev/null
+++ b/src/ccmain/fontstyle.cpp
@@ -0,0 +1,397 @@
+///////////////////////////////////////////////////////////////////////
+// File: fontstyle.cpp
+// Description: Estimation of font style attributes (bold, italic) from
+// the image of a word.
+//
+// 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 "fontstyle.h"
+
+#include "boxword.h"
+#include "fontinfo.h"
+#include "pageres.h"
+#include "tesseractclass.h"
+#include "tprintf.h"
+
+#include <allheaders.h>
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <cstring> // for strchr
+#include <vector>
+
+namespace tesseract {
+
+// Range of the slants of upright and italic text, as tangents of the slant
+// angle. Strokes outside this range are diagonal strokes like those of v, w
+// and y.
+const float kMinTextSlant = -0.1f;
+const float kMaxTextSlant = 0.35f;
+// The slants are tested in these steps. The test includes one more slant on
+// each side of the range to see whether a maximum at its limit is a real one,
+// so kNumSlants is (kMaxTextSlant - kMinTextSlant) / kSlantStep + 3.
+const float kSlantStep = 0.05f;
+const int kNumSlants = 12;
+// Resolution of the shear in fractions of a pixel.
+const int kSubPixels = 4;
+
+// A word is italic if its slant is at least this value.
+const float kItalicSlant = 0.07f;
+// A word is bold if its strokes are at least this much wider than those of
+// the typical word of the page, relative to the x-height.
+const float kBoldFactor = 1.25f;
+// A word needs this number of letters and digits for a decision of its own.
+const int kMinStyleLetters = 3;
+// Letters and symbols with diagonal strokes which can have the slant of the
+// stems of italic text. They are left out when the slant is measured.
+const char kDiagonalLetters[] = "AMVWXYvwxy/";
+
+namespace {
+
+// A horizontal run of text pixels: row y, columns start to end - 1.
+struct PixelRun {
+ int y;
+ int start;
+ int end;
+};
+
+} // namespace
+
+bool MeasureTextShape(Image pix, TextShape *shape) {
+ if (pix == nullptr || pixGetDepth(pix) != 1) {
+ return false;
+ }
+ const int width = pixGetWidth(pix);
+ const int height = pixGetHeight(pix);
+ if (width <= 0 || height <= 0) {
+ return false;
+ }
+
+ // Collect the runs of text pixels and count them by their length.
+ std::vector<PixelRun> runs;
+ std::vector<int> num_runs(width + 1);
+ const l_uint32 *data = pixGetData(pix);
+ const int wpl = pixGetWpl(pix);
+ for (int y = 0; y < height; ++y) {
+ const l_uint32 *line = data + static_cast<size_t>(y) * wpl;
+ int start = -1;
+ for (int x = 0; x <= width; ++x) {
+ const bool text = x < width && GET_DATA_BIT(line, x) != 0;
+ if (text) {
+ if (start < 0) {
+ start = x;
+ }
+ } else if (start >= 0) {
+ runs.push_back({y, start, x});
+ ++num_runs[x - start];
+ start = -1;
+ }
+ }
+ }
+ if (runs.empty()) {
+ return false;
+ }
+
+ // Most runs cross a single stroke, so the median of their lengths is the
+ // stroke width. The runs of the length l count as spread evenly from
+ // l - 0.5 to l + 0.5, which gives a median between the integer lengths.
+ const double half = 0.5 * runs.size();
+ double shorter = 0.0;
+ int length = 1;
+ while (shorter + num_runs[length] < half) {
+ shorter += num_runs[length++];
+ }
+ shape->stroke_width = length - 0.5f + static_cast<float>((half - shorter) / num_runs[length]);
+
+ // Shear the text by a slant and add up the pixels in each column. The sum
+ // of the squares of the column sums has a maximum where strokes are vertical.
+ // The rows are shifted in steps of 1 / kSubPixels pixel, because whole
+ // pixels cannot show a slant of less than one pixel over the height of a
+ // stroke.
+ const float y_center = 0.5f * (height - 1);
+ const float max_slant = std::max(kSlantStep - kMinTextSlant, kMaxTextSlant + kSlantStep);
+ const int pad = static_cast<int>(std::ceil(max_slant * y_center)) + 1;
+ // The columns hold the differences between neighbouring column sums.
+ std::vector<int> columns(kSubPixels * (width + 2 * pad) + 1);
+ auto score_of = [&](float slant) {
+ std::fill(columns.begin(), columns.end(), 0);
+ int y = -1;
+ int offset = 0;
+ for (const auto &run : runs) {
+ if (run.y != y) {
+ y = run.y;
+ offset = static_cast<int>(std::lround(kSubPixels * (pad + slant * (y - y_center))));
+ }
+ ++columns[kSubPixels * run.start + offset];
+ --columns[kSubPixels * run.end + offset];
+ }
+ double score = 0.0;
+ int sum = 0;
+ for (int delta : columns) {
+ sum += delta;
+ score += static_cast<double>(sum) * sum;
+ }
+ return score;
+ };
+ const float first_slant = kMinTextSlant - kSlantStep;
+ std::array<double, kNumSlants> scores;
+ for (int i = 0; i < kNumSlants; ++i) {
+ scores[i] = score_of(first_slant + i * kSlantStep);
+ }
+ // The text has a slant if the best score is in the range of upright and
+ // italic text. If it is at one of the two slants outside the range, the
+ // strongest strokes are diagonal ones.
+ const int best =
+ static_cast<int>(std::max_element(scores.begin(), scores.end()) - scores.begin());
+ shape->has_slant = best > 0 && best + 1 < kNumSlants;
+ shape->slant = 0.0f;
+ if (shape->has_slant) {
+ // Refine the maximum: test the slants half a step away from it, and fit a
+ // parabola to the best of the three and its two neighbours.
+ const float half_step = 0.5f * kSlantStep;
+ float slant = first_slant + best * kSlantStep;
+ double below = score_of(slant - half_step);
+ double peak = scores[best];
+ double above = score_of(slant + half_step);
+ if (below > peak && below >= above) {
+ slant -= half_step;
+ above = peak;
+ peak = below;
+ below = scores[best - 1];
+ } else if (above > peak) {
+ slant += half_step;
+ below = peak;
+ peak = above;
+ above = scores[best + 1];
+ }
+ const double curvature = below - 2.0 * peak + above;
+ if (curvature < 0.0) {
+ slant += static_cast<float>(half_step * 0.5 * (below - above) / curvature);
+ }
+ shape->slant = slant;
+ }
+ return true;
+}
+
+const FontInfo *NamelessFont(bool bold, bool italic) {
+ static const std::array<FontInfo, 4> fonts = [] {
+ std::array<FontInfo, 4> table;
+ for (unsigned i = 0; i < table.size(); ++i) {
+ // The properties are those of FontInfo: 1 = italic, 2 = bold.
+ table[i].properties = i;
+ table[i].universal_id = -1;
+ }
+ return table;
+ }();
+ return &fonts[(italic ? 1 : 0) | (bold ? 2 : 0)];
+}
+
+namespace {
+
+// Style measurements and decisions for one word.
+struct WordStyle {
+ WERD_RES *word = nullptr;
+ const ROW *row = nullptr;
+ // Slant of the text relative to the perpendicular of the baseline.
+ float slant = 0.0f;
+ // Stroke width relative to the x-height of the row.
+ float weight = 0.0f;
+ // The word has enough text for a decision of its own on bold.
+ bool bold_reliable = false;
+ // The same for italic, which also needs strokes with a slant.
+ bool italic_reliable = false;
+ bool bold = false;
+ bool italic = false;
+};
+
+} // namespace
+
+// Returns the value which a word with too little text gets for a style
+// attribute: the value of its reliable neighbours in the same row if they
+// agree or if there is only one, else the value from its own measurement.
+static bool StyleFromNeighbours(const std::vector<WordStyle> &styles, size_t index,
+ bool WordStyle::*attribute, bool WordStyle::*reliable) {
+ const WordStyle &style = styles[index];
+ const WordStyle *prev = nullptr;
+ const WordStyle *next = nullptr;
+ for (size_t i = index; i > 0 && styles[i - 1].row == style.row && prev == nullptr; --i) {
+ if (styles[i - 1].*reliable) {
+ prev = &styles[i - 1];
+ }
+ }
+ for (size_t i = index + 1; i < styles.size() && styles[i].row == style.row && next == nullptr;
+ ++i) {
+ if (styles[i].*reliable) {
+ next = &styles[i];
+ }
+ }
+ if (prev != nullptr && (next == nullptr || prev->*attribute == next->*attribute)) {
+ return prev->*attribute;
+ }
+ if (next != nullptr && prev == nullptr) {
+ return next->*attribute;
+ }
+ return style.*attribute;
+}
+
+/**
+ * font_style_pass
+ *
+ * Estimate bold and italic for the words which have no font, which are those
+ * recognized by LSTM, from the binary image.
+ */
+void Tesseract::font_style_pass(PAGE_RES *page_res) {
+ Image pix = pix_binary();
+ if (pix == nullptr) {
+ return;
+ }
+ const TBOX image_box(0, 0, pixGetWidth(pix), pixGetHeight(pix));
+ std::vector<WordStyle> styles;
+ PAGE_RES_IT page_res_it(page_res);
+ for (page_res_it.restart_page(); page_res_it.word() != nullptr; page_res_it.forward()) {
+ WERD_RES *word = page_res_it.word();
+ if (word->fontinfo != nullptr || word->best_choice == nullptr || word->word == nullptr) {
+ continue;
+ }
+ const BLOCK *block = page_res_it.block()->block;
+ const ROW *row = page_res_it.row()->row;
+ if (block == nullptr || row == nullptr || row->x_height() <= 0.0f) {
+ continue;
+ }
+ if (block->re_rotation().x() <= 0.0f || block->re_rotation().y() != 0.0f) {
+ // The block is rotated, so its boxes do not refer to the image.
+ continue;
+ }
+ const TBOX box = word->word->bounding_box().intersection(image_box);
+ if (box.null_box()) {
+ continue;
+ }
+ Box *clip_box =
+ boxCreate(box.left(), image_box.top() - box.top(), box.width(), box.height());
+ Image word_pix = pixClipRectangle(pix, clip_box, nullptr);
+ boxDestroy(&clip_box);
+ if (word_pix == nullptr) {
+ continue;
+ }
+ // Invert white text on black. Such text has more set pixels than others,
+ // but so can heavy bold text. The upper and lower edge of the box are
+ // above and below the text, so they must show the background, too.
+ l_int32 num_set = 0;
+ l_int32 num_top = 0;
+ l_int32 num_bottom = 0;
+ pixCountPixels(word_pix, &num_set, nullptr);
+ pixCountPixelsInRow(word_pix, 0, &num_top, nullptr);
+ pixCountPixelsInRow(word_pix, box.height() - 1, &num_bottom, nullptr);
+ if (2 * static_cast<int64_t>(num_set) > static_cast<int64_t>(box.width()) * box.height() &&
+ num_top + num_bottom > box.width()) {
+ pixInvert(word_pix, word_pix);
+ }
+ TextShape shape;
+ if (!MeasureTextShape(word_pix, &shape)) {
+ word_pix.destroy();
+ continue;
+ }
+ // Measure the slant again without the letters which have diagonal strokes.
+ const WERD_CHOICE &choice = *word->best_choice;
+ if (word->box_word != nullptr && word->box_word->length() == choice.length()) {
+ bool erased = false;
+ for (unsigned i = 0; i < choice.length(); ++i) {
+ const char *unichar = word->uch_set->id_to_unichar(choice.unichar_id(i));
+ if (unichar[0] == '\0' || strchr(kDiagonalLetters, unichar[0]) == nullptr) {
+ continue;
+ }
+ const TBOX letter_box = word->box_word->BlobBox(i).intersection(box);
+ if (letter_box.null_box()) {
+ continue;
+ }
+ Box *letter = boxCreate(letter_box.left() - box.left(), 0, letter_box.width(),
+ box.height());
+ pixClearInRect(word_pix, letter);
+ boxDestroy(&letter);
+ erased = true;
+ }
+ if (erased) {
+ TextShape stem_shape;
+ shape.has_slant = MeasureTextShape(word_pix, &stem_shape) && stem_shape.has_slant;
+ shape.slant = stem_shape.slant;
+ }
+ }
+ word_pix.destroy();
+ WordStyle style;
+ style.word = word;
+ style.row = row;
+ // Upright text on a baseline with the gradient g has the slant -g.
+ const float gradient = box.width() > 0
+ ? (row->base_line(box.right()) - row->base_line(box.left())) /
+ box.width()
+ : 0.0f;
+ style.slant = shape.slant + gradient;
+ style.weight = shape.stroke_width / row->x_height();
+ int num_letters = 0;
+ for (unsigned i = 0; i < choice.length(); ++i) {
+ if (word->uch_set->get_isalpha(choice.unichar_id(i)) ||
+ word->uch_set->get_isdigit(choice.unichar_id(i))) {
+ ++num_letters;
+ }
+ }
+ style.bold_reliable = num_letters >= kMinStyleLetters;
+ style.italic_reliable = style.bold_reliable && shape.has_slant;
+ style.italic = shape.has_slant && style.slant >= kItalicSlant;
+ styles.push_back(style);
+ }
+ if (styles.empty()) {
+ return;
+ }
+
+ // The weight of the typical word of the page is the reference for bold.
+ std::vector<float> weights;
+ for (const auto &style : styles) {
+ if (style.bold_reliable) {
+ weights.push_back(style.weight);
+ }
+ }
+ if (weights.empty()) {
+ for (const auto &style : styles) {
+ weights.push_back(style.weight);
+ }
+ }
+ auto median = weights.begin() + weights.size() / 2;
+ std::nth_element(weights.begin(), median, weights.end());
+ const float bold_weight = kBoldFactor * *median;
+
+ for (auto &style : styles) {
+ style.bold = style.weight >= bold_weight;
+ }
+ for (size_t i = 0; i < styles.size(); ++i) {
+ const WordStyle &style = styles[i];
+ bool bold = style.bold;
+ bool italic = style.italic;
+ if (!style.bold_reliable) {
+ bold = StyleFromNeighbours(styles, i, &WordStyle::bold, &WordStyle::bold_reliable);
+ }
+ if (!style.italic_reliable) {
+ italic = StyleFromNeighbours(styles, i, &WordStyle::italic, &WordStyle::italic_reliable);
+ }
+ style.word->fontinfo = NamelessFont(bold, italic);
+ style.word->fontinfo_id_count = 1;
+ if (tessedit_debug_fonts) {
+ // reliable: 1 = for bold, 2 = for italic, 3 = for both.
+ tprintf("Word style: slant=%.3f weight=%.3f (page %.3f) reliable=%d bold=%d italic=%d %s\n",
+ style.slant, style.weight, *median, style.bold_reliable + 2 * style.italic_reliable,
+ bold, italic, style.word->best_choice->unichar_string().c_str());
+ }
+ }
+}
+
+} // namespace tesseract
diff --git a/src/ccmain/fontstyle.h b/src/ccmain/fontstyle.h
new file mode 100644
index 00000000..4e12aba7
--- /dev/null
+++ b/src/ccmain/fontstyle.h
@@ -0,0 +1,59 @@
+///////////////////////////////////////////////////////////////////////
+// File: fontstyle.h
+// Description: Estimation of font style attributes (bold, italic) from
+// the image of a word.
+//
+// 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.
+///////////////////////////////////////////////////////////////////////
+
+#ifndef TESSERACT_CCMAIN_FONTSTYLE_H_
+#define TESSERACT_CCMAIN_FONTSTYLE_H_
+
+#include "image.h"
+
+#include <tesseract/export.h> // for TESS_API
+
+namespace tesseract {
+
+struct FontInfo;
+
+// Shape of the text in a binary image, measured without any knowledge of the
+// characters.
+struct TextShape {
+ // Horizontal shear which makes the strokes of the text vertical. It is the
+ // tangent of the slant angle and positive for text which leans to the right,
+ // so about 0 for upright and 0.1 to 0.3 for italic text.
+ float slant = 0.0f;
+ // False if the strongest strokes of the text have a slant outside the range
+ // of upright and italic text, which is from -0.1 to 0.35. That is the case
+ // for text with mainly diagonal strokes, for example "wavy". The slant is 0
+ // then.
+ bool has_slant = false;
+ // Typical width of the strokes in pixels, measured along the pixel rows.
+ float stroke_width = 0.0f;
+};
+
+// Measures the shape of the text in the given image, which must have a depth
+// of 1 bit. The set pixels are the text. Returns false and leaves the shape
+// untouched if the image is not usable or contains no text.
+TESS_API
+bool MeasureTextShape(Image pix, TextShape *shape);
+
+// Returns the entry of a table of fonts without a name for the given style.
+// The entries have the font id -1 and stay valid until the program ends.
+// They are used for words which get their font attributes from an estimation
+// instead of from a font classifier.
+TESS_API
+const FontInfo *NamelessFont(bool bold, bool italic);
+
+} // namespace tesseract
+
+#endif // TESSERACT_CCMAIN_FONTSTYLE_H_
diff --git a/src/ccmain/ltrresultiterator.cpp b/src/ccmain/ltrresultiterator.cpp
index 576b86f9..6500684c 100644
--- a/src/ccmain/ltrresultiterator.cpp
+++ b/src/ccmain/ltrresultiterator.cpp
@@ -19,6 +19,7 @@
#include <tesseract/ltrresultiterator.h>
+#include "fontinfo.h" // for FontInfo
#include "helpers.h" // for copy_string
#include "pageres.h"
#include "tesseractclass.h"
@@ -172,12 +173,17 @@ float LTRResultIterator::Confidence(PageIteratorLevel level) const {
// to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as
// the iterator itself, ie rendered invalid by various members of
// TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI.
+// The return value is nullptr if the font name is not known. The attributes
+// can be set nevertheless: with the parameter lstm_font_attributes, bold
+// and italic are estimated for words recognized by LSTM, which have no font
+// name and the font_id -1.
// Pointsize is returned in printers points (1/72 inch.)
const char *LTRResultIterator::WordFontAttributes(bool *is_bold, bool *is_italic,
bool *is_underlined, bool *is_monospace,
bool *is_serif, bool *is_smallcaps,
int *pointsize, int *font_id) const {
const char *result = nullptr;
+ const FontInfo *font_info = nullptr;
if (it_->word() == nullptr) {
// Already at the end!
@@ -189,10 +195,10 @@ const char *LTRResultIterator::WordFontAttributes(bool *is_bold, bool *is_italic
*pointsize =
scaled_yres_ > 0 ? static_cast<int>(row_height * kPointsPerInch / scaled_yres_ + 0.5) : 0;
-#ifndef DISABLED_LEGACY_ENGINE
- const FontInfo *font_info = it_->word()->fontinfo;
+ font_info = it_->word()->fontinfo;
if (font_info) {
- // Font information available.
+ // Font information available. The font has no name if the attributes
+ // come from an estimation instead of from a font classifier.
*font_id = font_info->universal_id;
*is_bold = font_info->is_bold();
*is_italic = font_info->is_italic();
@@ -201,12 +207,11 @@ const char *LTRResultIterator::WordFontAttributes(bool *is_bold, bool *is_italic
*is_serif = font_info->is_serif();
result = font_info->name;
}
-#endif // ndef DISABLED_LEGACY_ENGINE
*is_smallcaps = it_->word()->small_caps;
}
- if (!result) {
+ if (!font_info) {
*is_bold = false;
*is_italic = false;
*is_underlined = false;
diff --git a/src/ccmain/tesseractclass.cpp b/src/ccmain/tesseractclass.cpp
index ce896a84..44683109 100644
--- a/src/ccmain/tesseractclass.cpp
+++ b/src/ccmain/tesseractclass.cpp
@@ -439,6 +439,9 @@ Tesseract::Tesseract()
"lstm_choice_mode. Note that lstm_choice_mode must be set to a "
"value greater than 0 to produce results.",
this->params())
+ , BOOL_MEMBER(lstm_font_attributes, false,
+ "Estimate bold and italic for the words recognized by LSTM.",
+ this->params())
, double_MEMBER(lstm_rating_coefficient, 5,
"Sets the rating coefficient for the lstm choices. The smaller the "
"coefficient, the better are the ratings for each choice and less "
diff --git a/src/ccmain/tesseractclass.h b/src/ccmain/tesseractclass.h
index f026bf94..999de634 100644
--- a/src/ccmain/tesseractclass.h
+++ b/src/ccmain/tesseractclass.h
@@ -463,6 +463,8 @@ public:
// Set fonts of this word.
void set_word_fonts(WERD_RES *word);
void font_recognition_pass(PAGE_RES *page_res);
+ // Estimates bold and italic from the image for the words without a font.
+ void font_style_pass(PAGE_RES *page_res);
void dictionary_correction_pass(PAGE_RES *page_res);
bool check_debug_pt(WERD_RES *word, int location);
@@ -968,6 +970,7 @@ public:
STRING_VAR_H(page_separator);
INT_VAR_H(lstm_choice_mode);
INT_VAR_H(lstm_choice_iterations);
+ BOOL_VAR_H(lstm_font_attributes);
double_VAR_H(lstm_rating_coefficient);
BOOL_VAR_H(pageseg_apply_music_mask);
diff --git a/src/ccstruct/fontinfo.h b/src/ccstruct/fontinfo.h
index cfb19e06..701691a8 100644
--- a/src/ccstruct/fontinfo.h
+++ b/src/ccstruct/fontinfo.h
@@ -66,6 +66,10 @@ struct FontInfo {
~FontInfo() = default;
bool operator==(const FontInfo &rhs) const {
+ // Fonts without a name are only equal to themselves.
+ if (name == nullptr || rhs.name == nullptr) {
+ return this == &rhs;
+ }
return strcmp(name, rhs.name) == 0;
}
diff --git a/unittest/fontstyle_test.cc b/unittest/fontstyle_test.cc
new file mode 100644
index 00000000..e2232f82
--- /dev/null
+++ b/unittest/fontstyle_test.cc
@@ -0,0 +1,363 @@
+///////////////////////////////////////////////////////////////////////
+// File: fontstyle_test.cc
+// Description: Unit tests for the estimation of bold and italic from
+// the image of a word (parameter lstm_font_attributes):
+// the measurement of slant and stroke width, the fonts
+// without a name, and the attributes which the API
+// reports for words recognized by LSTM.
+//
+// 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 "fontinfo.h"
+#include "fontstyle.h"
+#include "image.h"
+
+#include <allheaders.h>
+#include <tesseract/baseapi.h>
+#include <tesseract/resultiterator.h>
+
+#include <array>
+#include <cmath>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace tesseract {
+
+// Returns a binary image with four vertical bars of the given width. A
+// positive slant shifts the upper end of the bars to the right.
+static Image MakeBars(int stroke_width, float slant) {
+ const int kWidth = 200;
+ const int kHeight = 60;
+ Image pix = pixCreate(kWidth, kHeight, 1);
+ for (int y = 0; y < kHeight; ++y) {
+ const int shift = static_cast<int>(std::lround(slant * (kHeight - 1 - y)));
+ for (int left = 40; left < 140; left += 25) {
+ for (int x = 0; x < stroke_width; ++x) {
+ pixSetPixel(pix, left + shift + x, y, 1);
+ }
+ }
+ }
+ return pix;
+}
+
+TEST(FontStyleTest, MeasuresSlant) {
+ for (float slant : {-0.1f, -0.03f, 0.0f, 0.03f, 0.1f, 0.2f, 0.3f, 0.35f}) {
+ Image pix = MakeBars(4, slant);
+ TextShape shape;
+ ASSERT_TRUE(MeasureTextShape(pix, &shape));
+ EXPECT_TRUE(shape.has_slant) << "slant " << slant;
+ EXPECT_NEAR(shape.slant, slant, 0.015f) << "slant " << slant;
+ pix.destroy();
+ }
+}
+
+// Strokes which are steeper than those of italic text are diagonal strokes
+// and give no slant.
+TEST(FontStyleTest, DiagonalStrokesHaveNoSlant) {
+ for (float slant : {-0.3f, 0.5f}) {
+ Image pix = MakeBars(4, slant);
+ TextShape shape;
+ ASSERT_TRUE(MeasureTextShape(pix, &shape));
+ EXPECT_FALSE(shape.has_slant) << "slant " << slant;
+ EXPECT_EQ(shape.slant, 0.0f) << "slant " << slant;
+ EXPECT_FLOAT_EQ(shape.stroke_width, 4.0f) << "slant " << slant;
+ pix.destroy();
+ }
+}
+
+// The stroke width is measured along the pixel rows, so it does not depend
+// on the slant.
+TEST(FontStyleTest, MeasuresStrokeWidth) {
+ for (int stroke_width : {1, 2, 3, 5, 8}) {
+ for (float slant : {0.0f, 0.25f}) {
+ Image pix = MakeBars(stroke_width, slant);
+ TextShape shape;
+ ASSERT_TRUE(MeasureTextShape(pix, &shape));
+ EXPECT_FLOAT_EQ(shape.stroke_width, stroke_width)
+ << "stroke width " << stroke_width << ", slant " << slant;
+ pix.destroy();
+ }
+ }
+}
+
+// Strokes of two widths give a median between the widths, which moves with
+// the share of each width.
+TEST(FontStyleTest, StrokeWidthBetweenPixels) {
+ const int kHeight = 40;
+ float last_width = 0.0f;
+ for (int wide_rows : {8, 16, 24, 32}) {
+ Image pix = pixCreate(40, kHeight, 1);
+ for (int y = 0; y < kHeight; ++y) {
+ const int stroke_width = y < wide_rows ? 4 : 3;
+ for (int x = 0; x < stroke_width; ++x) {
+ pixSetPixel(pix, 10 + x, y, 1);
+ }
+ }
+ TextShape shape;
+ ASSERT_TRUE(MeasureTextShape(pix, &shape));
+ EXPECT_GT(shape.stroke_width, 2.5f);
+ EXPECT_LT(shape.stroke_width, 4.5f);
+ EXPECT_GT(shape.stroke_width, last_width) << wide_rows << " wide rows";
+ last_width = shape.stroke_width;
+ pix.destroy();
+ }
+}
+
+TEST(FontStyleTest, RejectsUnusableImages) {
+ TextShape shape;
+ shape.slant = 7.0f;
+ EXPECT_FALSE(MeasureTextShape(nullptr, &shape));
+ Image empty = pixCreate(50, 20, 1);
+ EXPECT_FALSE(MeasureTextShape(empty, &shape));
+ empty.destroy();
+ Image grey = pixCreate(50, 20, 8);
+ EXPECT_FALSE(MeasureTextShape(grey, &shape));
+ grey.destroy();
+ // A failed measurement does not change the shape.
+ EXPECT_EQ(shape.slant, 7.0f);
+}
+
+TEST(FontStyleTest, NamelessFonts) {
+ for (bool bold : {false, true}) {
+ for (bool italic : {false, true}) {
+ const FontInfo *font = NamelessFont(bold, italic);
+ ASSERT_NE(font, nullptr);
+ EXPECT_EQ(font->name, nullptr);
+ EXPECT_EQ(font->universal_id, -1);
+ EXPECT_EQ(font->is_bold(), bold);
+ EXPECT_EQ(font->is_italic(), italic);
+ EXPECT_FALSE(font->is_fixed_pitch());
+ EXPECT_FALSE(font->is_serif());
+ EXPECT_FALSE(font->is_fraktur());
+ // The same style always gives the same font.
+ EXPECT_EQ(font, NamelessFont(bold, italic));
+ }
+ }
+ // Fonts without a name can be compared, and differ from each other and
+ // from fonts with a name.
+ const FontInfo ®ular = *NamelessFont(false, false);
+ const FontInfo &bold = *NamelessFont(true, false);
+ EXPECT_TRUE(regular == regular);
+ EXPECT_FALSE(regular == bold);
+ char name[] = "Arial";
+ FontInfo named;
+ named.name = name;
+ EXPECT_FALSE(regular == named);
+ EXPECT_FALSE(named == regular);
+ EXPECT_TRUE(named == named);
+}
+
+// A word with the font attributes which the API reports for it.
+struct StyledWord {
+ std::string text;
+ // Index of the text line of the word in the unchanged image, or -1.
+ int line = -1;
+ bool bold = false;
+ bool italic = false;
+ bool has_font_name = false;
+ int font_id = 0;
+ int pointsize = 0;
+};
+
+// Tests of the attributes for words recognized by LSTM. phototest.tif has
+// eight lines of upright text of normal weight in a single font.
+class FontStyleApiTest : public testing::Test {
+protected:
+ void SetUp() override {
+ REQUIRE_TRAINEDDATA(TESSDATA_DIR, "eng");
+ if (api_.Init(TESSDATA_DIR, "eng", OEM_LSTM_ONLY) == -1) {
+ // eng.traineddata not found.
+ GTEST_SKIP();
+ }
+ api_.SetPageSegMode(PSM_AUTO);
+ pix_ = pixRead(TESTING_DIR "/phototest.tif");
+ ASSERT_TRUE(pix_ != nullptr);
+ }
+
+ void TearDown() override {
+ pix_.destroy();
+ }
+
+ // Recognizes pix_ and returns its words. The first call stores the boxes of
+ // the text lines in line_boxes_ as left, top, right, bottom. Changes of the
+ // image can add or split lines, so later calls find the line of a word by
+ // its position.
+ std::vector<StyledWord> Recognize() {
+ std::vector<StyledWord> words;
+ const bool first = line_boxes_.empty();
+ api_.SetImage(pix_);
+ EXPECT_EQ(api_.Recognize(nullptr), 0);
+ std::unique_ptr<ResultIterator> it(api_.GetIterator());
+ if (it == nullptr) {
+ ADD_FAILURE() << "No results";
+ return words;
+ }
+ do {
+ std::array<int, 4> box;
+ if (first && it->IsAtBeginningOf(RIL_TEXTLINE)) {
+ it->BoundingBox(RIL_TEXTLINE, &box[0], &box[1], &box[2], &box[3]);
+ line_boxes_.push_back(box);
+ }
+ StyledWord word;
+ std::unique_ptr<char[]> text(it->GetUTF8Text(RIL_WORD));
+ word.text = text ? text.get() : "";
+ it->BoundingBox(RIL_WORD, &box[0], &box[1], &box[2], &box[3]);
+ const int y = (box[1] + box[3]) / 2;
+ for (size_t line = 0; line < line_boxes_.size(); ++line) {
+ if (line_boxes_[line][1] <= y && y <= line_boxes_[line][3]) {
+ word.line = static_cast<int>(line);
+ }
+ }
+ bool underlined, monospace, serif, smallcaps;
+ word.has_font_name =
+ it->WordFontAttributes(&word.bold, &word.italic, &underlined, &monospace, &serif,
+ &smallcaps, &word.pointsize, &word.font_id) != nullptr;
+ EXPECT_FALSE(underlined);
+ EXPECT_FALSE(monospace);
+ EXPECT_FALSE(serif);
+ words.push_back(word);
+ } while (it->Next(RIL_WORD));
+ return words;
+ }
+
+ // Replaces the given text line of pix_ by the result of the function for
+ // the image of the line.
+ template <typename Function>
+ void ChangeLine(int line, Function change) {
+ ASSERT_LT(static_cast<size_t>(line), line_boxes_.size());
+ // Use the whole width of the image to have room for a slant.
+ const int kPadding = 2;
+ const int top = line_boxes_[line][1] - kPadding;
+ const int height = line_boxes_[line][3] - line_boxes_[line][1] + 2 * kPadding;
+ Box *box = boxCreate(0, top, pixGetWidth(pix_), height);
+ Image line_pix = pixClipRectangle(pix_, box, nullptr);
+ boxDestroy(&box);
+ ASSERT_TRUE(line_pix != nullptr);
+ Image changed = change(line_pix);
+ ASSERT_TRUE(changed != nullptr);
+ pixRasterop(pix_, 0, top, pixGetWidth(pix_), height, PIX_SRC, changed, 0, 0);
+ changed.destroy();
+ line_pix.destroy();
+ }
+
+ TessBaseAPI api_;
+ Image pix_;
+ std::vector<std::array<int, 4>> line_boxes_;
+};
+
+// Without the parameter, words recognized by LSTM have no font attributes.
+TEST_F(FontStyleApiTest, DisabledByDefault) {
+ bool enabled = true;
+ ASSERT_TRUE(api_.GetBoolVariable("lstm_font_attributes", &enabled));
+ EXPECT_FALSE(enabled);
+ // Slanted text is the best candidate for a wrong result.
+ std::vector<StyledWord> words = Recognize();
+ ChangeLine(3, [](Image line) { return Image(pixHShear(nullptr, line, pixGetHeight(line) / 2,
+ std::atan(0.25f), L_BRING_IN_WHITE)); });
+ words = Recognize();
+ ASSERT_GT(words.size(), 40u);
+ for (const auto &word : words) {
+ EXPECT_FALSE(word.bold) << word.text;
+ EXPECT_FALSE(word.italic) << word.text;
+ EXPECT_FALSE(word.has_font_name) << word.text;
+ EXPECT_EQ(word.font_id, -1) << word.text;
+ }
+}
+
+TEST_F(FontStyleApiTest, RegularTextHasNoStyle) {
+ ASSERT_TRUE(api_.SetVariable("lstm_font_attributes", "1"));
+ const std::vector<StyledWord> words = Recognize();
+ ASSERT_GT(words.size(), 40u);
+ EXPECT_EQ(line_boxes_.size(), 8u);
+ for (const auto &word : words) {
+ EXPECT_FALSE(word.bold) << word.text;
+ EXPECT_FALSE(word.italic) << word.text;
+ // The attributes are an estimation, so there is no font name.
+ EXPECT_FALSE(word.has_font_name) << word.text;
+ EXPECT_EQ(word.font_id, -1) << word.text;
+ EXPECT_GT(word.pointsize, 0) << word.text;
+ }
+}
+
+// A slanted line must be italic, a line with thicker strokes must be bold,
+// and the other lines must stay as they are.
+TEST_F(FontStyleApiTest, FindsItalicAndBoldLines) {
+ const int kItalicLine = 3;
+ const int kBoldLine = 5;
+ ASSERT_TRUE(api_.SetVariable("lstm_font_attributes", "1"));
+ std::vector<StyledWord> words = Recognize();
+ ASSERT_EQ(line_boxes_.size(), 8u);
+ ChangeLine(kItalicLine, [](Image line) {
+ return Image(pixHShear(nullptr, line, pixGetHeight(line) / 2, std::atan(0.25f),
+ L_BRING_IN_WHITE));
+ });
+ // This makes the text so heavy that it fills more than half of its box.
+ ChangeLine(kBoldLine, [](Image line) { return Image(pixDilateBrick(nullptr, line, 3, 3)); });
+ words = Recognize();
+ int num_italic_line_words = 0;
+ int num_bold_line_words = 0;
+ for (const auto &word : words) {
+ ASSERT_GE(word.line, 0) << word.text;
+ EXPECT_EQ(word.italic, word.line == kItalicLine) << word.text << " in line " << word.line;
+ EXPECT_EQ(word.bold, word.line == kBoldLine) << word.text << " in line " << word.line;
+ EXPECT_FALSE(word.has_font_name) << word.text;
+ num_italic_line_words += word.line == kItalicLine;
+ num_bold_line_words += word.line == kBoldLine;
+ }
+ EXPECT_GE(num_italic_line_words, 6);
+ EXPECT_GE(num_bold_line_words, 6);
+
+ // The hOCR output marks the words of the two lines.
+ std::unique_ptr<char[]> hocr(api_.GetHOCRText(0));
+ ASSERT_TRUE(hocr != nullptr);
+ const std::string hocr_text(hocr.get());
+ auto count = [&hocr_text](const std::string &tag) {
+ int num = 0;
+ for (size_t pos = hocr_text.find(tag); pos != std::string::npos;
+ pos = hocr_text.find(tag, pos + 1)) {
+ ++num;
+ }
+ return num;
+ };
+ EXPECT_EQ(count("<em>"), num_italic_line_words);
+ EXPECT_EQ(count("<strong>"), num_bold_line_words);
+}
+
+// White text on black must give the same attributes as black text on white.
+TEST_F(FontStyleApiTest, FindsItalicInInverseText) {
+ const int kItalicLine = 3;
+ ASSERT_TRUE(api_.SetVariable("lstm_font_attributes", "1"));
+ std::vector<StyledWord> words = Recognize();
+ ASSERT_EQ(line_boxes_.size(), 8u);
+ ChangeLine(kItalicLine, [](Image line) {
+ return Image(pixHShear(nullptr, line, pixGetHeight(line) / 2, std::atan(0.25f),
+ L_BRING_IN_WHITE));
+ });
+ pixInvert(pix_, pix_);
+ words = Recognize();
+ int num_italic_line_words = 0;
+ for (const auto &word : words) {
+ if (word.line < 0) {
+ // The black background can give words outside the text.
+ continue;
+ }
+ EXPECT_EQ(word.italic, word.line == kItalicLine) << word.text << " in line " << word.line;
+ EXPECT_FALSE(word.bold) << word.text << " in line " << word.line;
+ num_italic_line_words += word.line == kItalicLine;
+ }
+ EXPECT_GE(num_italic_line_words, 6);
+}
+
+} // namespace tesseract