Commit 83a92b25 for tesseract
commit 83a92b255cdf428aaff75a872513b0502f7095fd
Author: Stefan Weil <sw@weilnetz.de>
Date: Wed Nov 25 17:47:17 2026 +0100
Find underlined words recognized by LSTM
WordFontAttributes never reported a word as underlined: the value was
always false, with a comment that this must be fixed.
With the parameter lstm_font_attributes, the font style pass now also
looks for a line below each word recognized by LSTM. A word is
underlined if long horizontal runs of pixels next to its baseline cover
at least 80 % of its columns. The runs must be longer than the serifs
and the bars of the letters, and one of them must be longer than the
bar of any letter, so a word of one or two letters which is underlined
alone is not found.
- The search starts above the baseline, because the baseline of the
layout analysis is too low where descenders join the text and its
underline.
- A line which goes on beyond the text of the text line is a ruling,
for example that of a table, and not an underline. The text ends
where the image has its last pixels which are not part of a line,
because the layout analysis can add the end of a ruling to a word.
- The layout analysis removes long lines from the binary image. Their
pixels are kept for the font style pass if the parameter is set.
- Words in Arabic, Chinese, Japanese and Korean are not tested. Their
characters have long horizontal strokes next to the baseline, which
cannot be told from an underline.
Underlined words get the element <u> in hOCR output, the value
underline in the attribute STYLE of ALTO output and the attribute
underlined of the element TextStyle in PAGE output.
Words recognized by the legacy engine are never underlined, as before.
Results for rendered English text with 14 fonts in 3 sizes (precision
and recall): 100 % and 98.9 % for underlined runs of words, 100 % and
92.7 % for words which are underlined one by one. There is no false
underline in 17800 words of text without underlines, nor in text with
rulings below its text lines. Bold and italic do not change.
Assisted-by: Claude Fable 5.2 (Anthropic)
Signed-off-by: Stefan Weil <sw@weilnetz.de>
diff --git a/doc/tesseract.1.asc b/doc/tesseract.1.asc
index e766d825..cc8e9440 100644
--- a/doc/tesseract.1.asc
+++ b/doc/tesseract.1.asc
@@ -454,8 +454,8 @@ OUTPUT FORMAT PARAMETERS
Write ALTO XML output to a `.xml` file. ALTO (Analyzed Layout and Text
Object) is a standard XML schema for describing the layout and content of
pages. Use the *alto* config file to enable this format.
- Words which have the font attributes bold, italic or small caps get the
- attribute `STYLE`, for example `STYLE="bold italics"`.
+ Words which have the font attributes bold, italic, small caps or underlined
+ get the attribute `STYLE`, for example `STYLE="bold italics"`.
*tessedit_create_page_xml* (bool, default: 0) [Both]::
Write PAGE XML output to a `.page.xml` file. PAGE (Page Analysis and
@@ -464,9 +464,10 @@ OUTPUT FORMAT PARAMETERS
tools such as Transkribus and eScriptorium.
See https://github.com/PRImA-Research-Lab/PAGE-XML for the specification.
Use the *page* config file to enable this format.
- The font attributes bold, italic and small caps are written as an element
- `TextStyle`, for example `<TextStyle bold="true"/>`: for a text line if all
- of its words have the attribute, and for each word with *page_xml_level* 1.
+ The font attributes bold, italic, underlined and small caps are written as
+ an element `TextStyle`, for example `<TextStyle bold="true"/>`: for a text
+ line if all of its words have the attribute, and for each word with
+ *page_xml_level* 1.
*page_xml_polygon* (bool, default: 1) [Both]::
When writing PAGE XML output, create polygon outlines around text regions
@@ -659,17 +660,24 @@ These parameters are only meaningful when using the LSTM OCR engine
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 size of the text 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. The
+ Estimate the font attributes bold, italic and underlined 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 size of the
+ text 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. The
estimation is made for Latin, Cyrillic and Greek text; it is not reliable
- for Arabic, Thai, Chinese and Japanese. The result has no font name; it
- is used for the `<strong>` and `<em>` elements of the hOCR output and
+ for Arabic, Thai, Chinese and Japanese. A word is underlined if a
+ horizontal line next to the baseline covers it. The line must be longer
+ than the strokes of a letter, so a word of one or two letters which is
+ underlined alone is not found. A line which goes on beyond the text of the
+ text line is taken for a ruling, for example that of a table, and not for an
+ underline. Underlines are not searched for Arabic, Chinese, Japanese and
+ Korean text, which has such strokes in its characters. The result has no
+ font name; it is used for the `<strong>`, `<em>` and `<u>` elements of the
+ hOCR output, for the font attributes of the ALTO and PAGE output, and
returned by the API function `WordFontAttributes`. With
*tessedit_debug_fonts* the measurements of each word are printed.
diff --git a/include/tesseract/ltrresultiterator.h b/include/tesseract/ltrresultiterator.h
index 7353030b..294c0dd8 100644
--- a/include/tesseract/ltrresultiterator.h
+++ b/include/tesseract/ltrresultiterator.h
@@ -101,9 +101,9 @@ public:
// 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.
+ // can be set nevertheless: with the parameter lstm_font_attributes, bold,
+ // italic and underlined are estimated for words recognized by LSTM, which
+ // have no font name and the font_id -1. Other words are never underlined.
// 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/api/altorenderer.cpp b/src/api/altorenderer.cpp
index 064e3723..4a729324 100644
--- a/src/api/altorenderer.cpp
+++ b/src/api/altorenderer.cpp
@@ -161,6 +161,9 @@ static std::string GetWordStyle(const ResultIterator *it) {
if (smallcaps) {
style += "smallcaps ";
}
+ if (underlined) {
+ style += "underline ";
+ }
if (!style.empty()) {
style.pop_back();
}
diff --git a/src/api/hocrrenderer.cpp b/src/api/hocrrenderer.cpp
index 5a67af34..b6060089 100644
--- a/src/api/hocrrenderer.cpp
+++ b/src/api/hocrrenderer.cpp
@@ -312,6 +312,9 @@ char *TessBaseAPI::GetHOCRText(ETEXT_DESC *monitor, int page_number) {
if (italic) {
hocr_str << "<em>";
}
+ if (underlined) {
+ hocr_str << "<u>";
+ }
do {
const std::unique_ptr<const char[]> grapheme(
res_it->GetUTF8Text(RIL_SYMBOL));
@@ -377,6 +380,9 @@ char *TessBaseAPI::GetHOCRText(ETEXT_DESC *monitor, int page_number) {
}
res_it->Next(RIL_SYMBOL);
} while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
+ if (underlined) {
+ hocr_str << "</u>";
+ }
if (italic) {
hocr_str << "</em>";
}
diff --git a/src/api/pagerenderer.cpp b/src/api/pagerenderer.cpp
index 5d2485fc..fc505c06 100644
--- a/src/api/pagerenderer.cpp
+++ b/src/api/pagerenderer.cpp
@@ -610,6 +610,7 @@ static Pta *FitBaselineIntoLinePolygon(Pta *bottom_pts, Pta *baseline_pts,
struct FontStyle {
bool bold = false;
bool italic = false;
+ bool underlined = false;
bool smallcaps = false;
};
@@ -618,9 +619,9 @@ struct FontStyle {
///
static FontStyle GetWordFontStyle(const ResultIterator *it) {
FontStyle style;
- bool underlined, monospace, serif;
+ bool monospace, serif;
int pointsize, font_id;
- it->WordFontAttributes(&style.bold, &style.italic, &underlined, &monospace, &serif,
+ it->WordFontAttributes(&style.bold, &style.italic, &style.underlined, &monospace, &serif,
&style.smallcaps, &pointsize, &font_id);
return style;
}
@@ -630,7 +631,7 @@ static FontStyle GetWordFontStyle(const ResultIterator *it) {
///
static void AddTextStyleToPAGE(const FontStyle &style, const char *indent,
std::stringstream &str) {
- if (!style.bold && !style.italic && !style.smallcaps) {
+ if (!style.bold && !style.italic && !style.underlined && !style.smallcaps) {
return;
}
str << indent << "<TextStyle";
@@ -640,6 +641,9 @@ static void AddTextStyleToPAGE(const FontStyle &style, const char *indent,
if (style.italic) {
str << " italic=\"true\"";
}
+ if (style.underlined) {
+ str << " underlined=\"true\"";
+ }
if (style.smallcaps) {
str << " smallCaps=\"true\"";
}
@@ -920,6 +924,7 @@ char *TessBaseAPI::GetPAGEText(ETEXT_DESC *monitor, int /*page_number*/) {
line_conf = res_it->Confidence(RIL_TEXTLINE) / 100;
line_style.bold = true;
line_style.italic = true;
+ line_style.underlined = true;
line_style.smallcaps = true;
char *utf8text = res_it->GetUTF8Text(RIL_TEXTLINE);
std::string textline = utf8text;
@@ -954,6 +959,7 @@ char *TessBaseAPI::GetPAGEText(ETEXT_DESC *monitor, int /*page_number*/) {
const FontStyle word_style = GetWordFontStyle(res_it.get());
line_style.bold &= word_style.bold;
line_style.italic &= word_style.italic;
+ line_style.underlined &= word_style.underlined;
line_style.smallcaps &= word_style.smallcaps;
// Create word stream if word level output is active
diff --git a/src/ccmain/fontstyle.cpp b/src/ccmain/fontstyle.cpp
index 5b020f52..f5dc57d4 100644
--- a/src/ccmain/fontstyle.cpp
+++ b/src/ccmain/fontstyle.cpp
@@ -1,7 +1,7 @@
///////////////////////////////////////////////////////////////////////
// File: fontstyle.cpp
-// Description: Estimation of font style attributes (bold, italic) from
-// the image of a word.
+// Description: Estimation of font style attributes (bold, italic,
+// underlined) 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.
@@ -74,6 +74,37 @@ const float kXHeightOfCapitals = 0.7f;
const size_t kMinItalicWords = 5;
// A word needs this number of letters and digits for a decision of its own.
const int kMinStyleLetters = 3;
+// An underline is searched from this share of the x-height above the
+// baseline to this share of it below the baseline. The search starts above
+// the baseline, because the baseline of the layout analysis is too low where
+// descenders join the text and its underline.
+const float kMaxUnderlineRise = 0.3f;
+const float kMaxUnderlineOffset = 0.8f;
+// A line which was found there is followed to the neighbours of the word in
+// rows which are up to this share of the x-height further away, because the
+// baseline is not exact.
+const float kUnderlineSlack = 0.5f;
+// A line consists of horizontal runs of pixels which are at least this share
+// of the x-height long. The serifs and the bars of the letters are shorter.
+const float kMinUnderlinePiece = 0.75f;
+// One of its runs is at least this share of the x-height long, which is
+// longer than the bar of any letter, for example that of E, L or Z.
+const float kMinUnderlineRun = 1.5f;
+// A line is thicker than a line of the background which is this share of the
+// x-height.
+const float kMaxUnderlineThickness = 0.3f;
+// An underline covers at least this share of the columns of a word.
+const float kMinUnderlineCover = 0.8f;
+// A line can have gaps of this share of the x-height, for example next to a
+// descender.
+const float kMaxUnderlineGap = 0.15f;
+// A line which goes on for more than this share of the x-height beyond the
+// text is a ruling.
+const float kMaxUnderlineOverhang = 0.5f;
+// Space on both sides of a text line which is needed to see that, as a share
+// of the x-height.
+const float kUnderlineMargin = 1.0f;
+
// 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/";
@@ -408,6 +439,158 @@ void SetWordWeights(std::vector<WordStrokes> *words) {
}
}
+std::vector<bool> FindUnderlinedWords(Image pix, const std::vector<float> &baseline,
+ float x_height,
+ const std::vector<std::pair<int, int>> &words) {
+ std::vector<bool> underlined(words.size(), false);
+ if (pix == nullptr || pixGetDepth(pix) != 1 || x_height <= 0.0f || words.empty()) {
+ return underlined;
+ }
+ const int width = pixGetWidth(pix);
+ const int height = pixGetHeight(pix);
+ if (width <= 0 || height <= 0 || baseline.size() != static_cast<size_t>(width)) {
+ return underlined;
+ }
+ // The rows of each column in which a line is searched.
+ const int rise = static_cast<int>(std::ceil(kMaxUnderlineRise * x_height));
+ const int depth = static_cast<int>(std::ceil(kMaxUnderlineOffset * x_height));
+ const int slack = static_cast<int>(std::ceil(kUnderlineSlack * x_height));
+ std::vector<int> first_rows(width);
+ int first_row = height;
+ int last_row = -1;
+ for (int x = 0; x < width; ++x) {
+ first_rows[x] = static_cast<int>(std::floor(baseline[x] + 0.5f)) - rise;
+ first_row = std::min(first_row, first_rows[x] - slack);
+ last_row = std::max(last_row, first_rows[x] + rise + depth + slack);
+ }
+ first_row = std::max(first_row, 0);
+ last_row = std::min(last_row, height - 1);
+
+ // Collect the long runs of pixels in these rows: for each column the number
+ // of rows in which it is part of such a run, and the length of the longest
+ // of these runs. A line is followed in more rows than those in which it is
+ // searched.
+ const int min_piece =
+ std::max(2, static_cast<int>(std::ceil(kMinUnderlinePiece * x_height)));
+ std::vector<int> thickness(width, 0);
+ std::vector<int> longest(width, 0);
+ std::vector<bool> has_line(width, false);
+ const l_uint32 *data = pixGetData(pix);
+ const int wpl = pixGetWpl(pix);
+ for (int y = first_row; y <= last_row; ++y) {
+ const l_uint32 *line = data + static_cast<size_t>(y) * wpl;
+ int start = -1;
+ for (int x = 0; x <= width; ++x) {
+ if (x < width && GET_DATA_BIT(line, x) != 0) {
+ if (start < 0) {
+ start = x;
+ }
+ continue;
+ }
+ if (start >= 0 && x - start >= min_piece) {
+ for (int run_x = start; run_x < x; ++run_x) {
+ const int offset = y - first_rows[run_x];
+ if (offset >= 0 && offset <= rise + depth) {
+ ++thickness[run_x];
+ }
+ if (offset >= -slack && offset <= rise + depth + slack) {
+ has_line[run_x] = true;
+ longest[run_x] = std::max(longest[run_x], x - start);
+ }
+ }
+ }
+ start = -1;
+ }
+ }
+
+ // The text ends with its first and its last column which have a pixel that
+ // is not part of a line, from the top of the lowercase letters to the
+ // descenders. The words alone do not tell that, because the layout analysis
+ // can add the end of a ruling to a word.
+ int text_left = width;
+ int text_right = -1;
+ for (const auto &word : words) {
+ text_left = std::min(text_left, word.first);
+ text_right = std::max(text_right, word.second);
+ }
+ text_left = std::max(text_left, 0);
+ text_right = std::min(text_right, width - 1);
+ const int text_height = static_cast<int>(std::ceil(x_height)) - rise;
+ auto has_text = [&](int x) {
+ for (int y = std::max(first_rows[x] - text_height, 0);
+ y < first_rows[x] + 2 * rise && y < height; ++y) {
+ const l_uint32 *line = data + static_cast<size_t>(y) * wpl;
+ if (GET_DATA_BIT(line, x) == 0) {
+ continue;
+ }
+ int start = x;
+ while (start > 0 && x - start < min_piece && GET_DATA_BIT(line, start - 1) != 0) {
+ --start;
+ }
+ int end = x + 1;
+ while (end < width && end - start < min_piece && GET_DATA_BIT(line, end) != 0) {
+ ++end;
+ }
+ if (end - start < min_piece) {
+ return true;
+ }
+ }
+ return false;
+ };
+ while (text_left < text_right && !has_text(text_left)) {
+ ++text_left;
+ }
+ while (text_right > text_left && !has_text(text_right)) {
+ --text_right;
+ }
+ const int max_thickness = std::max(2, static_cast<int>(kMaxUnderlineThickness * x_height));
+ const int max_gap = static_cast<int>(kMaxUnderlineGap * x_height) + 1;
+ const float max_overhang = kMaxUnderlineOverhang * x_height;
+ for (size_t w = 0; w < words.size(); ++w) {
+ const int first = std::max(0, words[w].first);
+ const int last = std::min(width - 1, words[w].second);
+ if (first > last) {
+ continue;
+ }
+ int num_covered = 0;
+ int num_thick = 0;
+ for (int x = first; x <= last; ++x) {
+ num_covered += thickness[x] > 0;
+ num_thick += thickness[x] > max_thickness;
+ }
+ // Text on a dark background has a line which is too thick.
+ if (num_covered < kMinUnderlineCover * (last - first + 1) || 2 * num_thick > num_covered) {
+ continue;
+ }
+ // Follow the line to both sides of the word.
+ int line_left = first;
+ for (int x = first - 1, gap = 0; x >= 0 && gap <= max_gap; --x) {
+ if (has_line[x]) {
+ line_left = x;
+ gap = 0;
+ } else {
+ ++gap;
+ }
+ }
+ int line_right = last;
+ for (int x = last + 1, gap = 0; x < width && gap <= max_gap; ++x) {
+ if (has_line[x]) {
+ line_right = x;
+ gap = 0;
+ } else {
+ ++gap;
+ }
+ }
+ if (line_left < text_left - max_overhang || line_right > text_right + max_overhang) {
+ continue;
+ }
+ const int longest_run =
+ *std::max_element(longest.begin() + line_left, longest.begin() + line_right + 1);
+ underlined[w] = longest_run >= kMinUnderlineRun * x_height;
+ }
+ return underlined;
+}
+
// 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.
@@ -472,6 +655,33 @@ static bool HasUprightScript(const WERD_RES &word) {
return num_upright > num_others;
}
+// Returns true if the word has more characters of the scripts which have
+// long horizontal strokes next to the baseline than of other scripts. Those
+// are Arabic, which joins its letters there, and Chinese, Japanese and Korean.
+// Such a stroke cannot be told from an underline.
+static bool HasLineLikeStrokes(const WERD_RES &word) {
+ if (HasUprightScript(word)) {
+ return true;
+ }
+ const UNICHARSET &unicharset = *word.uch_set;
+ const WERD_CHOICE &choice = *word.best_choice;
+ const int arabic_sid = unicharset.get_script_id_from_name("Arabic");
+ if (arabic_sid == unicharset.null_sid()) {
+ return false;
+ }
+ int num_arabic = 0;
+ int num_others = 0;
+ for (unsigned i = 0; i < choice.length(); ++i) {
+ const int script = unicharset.get_script(choice.unichar_id(i));
+ if (script == arabic_sid) {
+ ++num_arabic;
+ } else if (script != unicharset.null_sid() && script != unicharset.common_sid()) {
+ ++num_others;
+ }
+ }
+ return num_arabic > num_others;
+}
+
// Measures the shape of the text in an image which needs the given number of
// clockwise quarter turns to get upright characters.
static bool MeasureTurnedText(Image pix, int turns, TextShape *shape) {
@@ -484,18 +694,146 @@ static bool MeasureTurnedText(Image pix, int turns, TextShape *shape) {
return measured;
}
+// Returns the part of the image which the given box of a block covers, turned
+// like the block, so that the text lines are horizontal. The boxes of a block
+// refer to the block, which is rotated against the image if the page is not
+// upright or if the text lines are vertical. The box is reduced to its part
+// in the image. Returns nullptr if there is none.
+static Image ClipBlockImage(Image pix, const FCOORD &re_rotation, TBOX *box) {
+ const TBOX image_box(0, 0, pixGetWidth(pix), pixGetHeight(pix));
+ TBOX image_part = *box;
+ image_part.rotate(re_rotation);
+ image_part = image_part.intersection(image_box);
+ if (image_part.null_box()) {
+ return nullptr;
+ }
+ Box *clip_box = boxCreate(image_part.left(), image_box.top() - image_part.top(),
+ image_part.width(), image_part.height());
+ Image result = pixClipRectangle(pix, clip_box, nullptr);
+ boxDestroy(&clip_box);
+ const int turns = (4 - QuarterTurns(re_rotation)) % 4;
+ if (result != nullptr && turns != 0) {
+ Image turned = pixRotateOrth(result, turns);
+ result.destroy();
+ result = turned;
+ }
+ image_part.rotate(FCOORD(re_rotation.x(), -re_rotation.y()));
+ *box = image_part;
+ return result;
+}
+
+// Marks the underlined words of the page which have no font, which are those
+// recognized by LSTM. removed_lines has the pixels of the lines which the
+// layout analysis removed from the image, or is nullptr.
+static void MarkUnderlinedWords(Image pix, Image removed_lines, PAGE_RES *page_res,
+ bool debug) {
+ PAGE_RES_IT page_res_it(page_res);
+ page_res_it.restart_page();
+ while (page_res_it.word() != nullptr) {
+ // The words of the next text line.
+ const BLOCK *block = page_res_it.block()->block;
+ const ROW *row = page_res_it.row()->row;
+ std::vector<WERD_RES *> row_words;
+ do {
+ row_words.push_back(page_res_it.word());
+ page_res_it.forward();
+ } while (page_res_it.word() != nullptr && page_res_it.row()->row == row);
+ if (block == nullptr || row == nullptr || row->x_height() <= 0.0f) {
+ continue;
+ }
+ const float x_height = row->x_height();
+ TBOX text_box;
+ bool has_candidate = false;
+ for (const WERD_RES *word : row_words) {
+ if (word->word != nullptr) {
+ text_box += word->word->bounding_box();
+ has_candidate =
+ has_candidate || (word->fontinfo == nullptr && word->best_choice != nullptr);
+ }
+ }
+ if (!has_candidate || text_box.null_box()) {
+ continue;
+ }
+ // The image of the text line from the top of its lowercase letters to
+ // the space below the baseline, with a margin on both sides.
+ const int margin = static_cast<int>(std::ceil(kUnderlineMargin * x_height));
+ const int left = text_box.left() - margin;
+ const int right = text_box.right() + margin;
+ float lowest = row->base_line(left);
+ float highest = lowest;
+ for (const int x : {(left + right) / 2, right}) {
+ lowest = std::min(lowest, row->base_line(x));
+ highest = std::max(highest, row->base_line(x));
+ }
+ const int depth =
+ static_cast<int>(std::ceil((kMaxUnderlineOffset + kUnderlineSlack) * x_height)) + 2;
+ // The lowercase letters show where the text ends.
+ const int rise = static_cast<int>(std::ceil(x_height)) + 2;
+ TBOX box(left, static_cast<int>(std::floor(lowest)) - depth, right,
+ static_cast<int>(std::ceil(highest)) + rise);
+ TBOX lines_box = box;
+ Image row_pix = ClipBlockImage(pix, block->re_rotation(), &box);
+ if (row_pix == nullptr) {
+ continue;
+ }
+ if (removed_lines != nullptr) {
+ Image row_lines = ClipBlockImage(removed_lines, block->re_rotation(), &lines_box);
+ if (row_lines != nullptr) {
+ pixOr(row_pix, row_pix, row_lines);
+ row_lines.destroy();
+ }
+ }
+ std::vector<float> baseline(box.width());
+ for (int x = 0; x < box.width(); ++x) {
+ baseline[x] = box.top() - row->base_line(box.left() + x + 0.5f);
+ }
+ std::vector<std::pair<int, int>> columns;
+ for (const WERD_RES *word : row_words) {
+ if (word->word != nullptr) {
+ const TBOX word_box = word->word->bounding_box();
+ columns.emplace_back(word_box.left() - box.left(), word_box.right() - 1 - box.left());
+ }
+ }
+ const std::vector<bool> underlined = FindUnderlinedWords(row_pix, baseline, x_height, columns);
+ row_pix.destroy();
+ size_t index = 0;
+ for (WERD_RES *word : row_words) {
+ if (word->word == nullptr) {
+ continue;
+ }
+ const bool has_line = underlined[index++];
+ if (word->fontinfo != nullptr || word->best_choice == nullptr) {
+ continue;
+ }
+ // A word needs a letter or a digit. A line below a dash or below nothing
+ // is a line of its own. And the line must not be a stroke of the word.
+ bool has_text = false;
+ const WERD_CHOICE &choice = *word->best_choice;
+ for (unsigned i = 0; i < choice.length(); ++i) {
+ const UNICHAR_ID id = choice.unichar_id(i);
+ has_text = has_text || word->uch_set->get_isalpha(id) || word->uch_set->get_isdigit(id);
+ }
+ word->underlined = has_line && has_text && !HasLineLikeStrokes(*word);
+ if (debug && has_line) {
+ tprintf("Word underline: text=%d %s\n", has_text, choice.unichar_string().c_str());
+ }
+ }
+ }
+}
+
/**
* font_style_pass
*
- * Estimate bold and italic for the words which have no font, which are those
- * recognized by LSTM, from the binary image.
+ * Estimate bold, italic and underlined 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));
+ // This needs the words without the fonts which they get below.
+ MarkUnderlinedWords(pix, pix_removed_lines_, page_res, tessedit_debug_fonts);
std::vector<WordStyle> styles;
// The measurements for bold of the same words.
std::vector<WordStrokes> strokes;
@@ -510,38 +848,19 @@ void Tesseract::font_style_pass(PAGE_RES *page_res) {
if (block == nullptr || row == nullptr || row->x_height() <= 0.0f) {
continue;
}
- // The boxes refer to the block, which is rotated against the image if the
- // page is not upright or if the text lines are vertical. Get the image of
- // the word as it is in the block, with a horizontal text line.
- const FCOORD re_rotation = block->re_rotation();
- const int block_turns = (4 - QuarterTurns(re_rotation)) % 4;
// Vertical lines of a rotated page have upright characters in the block.
// Those of Chinese, Japanese and Korean text are turned in the block, and
// the rotation for the classifier makes them upright. The block is the
// same for both, so the script of the word decides.
const int upright_turns =
HasUprightScript(*word) ? QuarterTurns(block->classify_rotation()) : 0;
+ // The image of the word as it is in the block, with a horizontal text
+ // line. From here on the box is the part of the word in the image.
TBOX box = word->word->bounding_box();
- box.rotate(re_rotation);
- box = 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 && block_turns != 0) {
- Image turned = pixRotateOrth(word_pix, block_turns);
- word_pix.destroy();
- word_pix = turned;
- }
+ Image word_pix = ClipBlockImage(pix, block->re_rotation(), &box);
if (word_pix == nullptr) {
continue;
}
- // From here on the box is the part of the word in the image, in the
- // coordinates of the block.
- box.rotate(FCOORD(re_rotation.x(), -re_rotation.y()));
// 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.
diff --git a/src/ccmain/fontstyle.h b/src/ccmain/fontstyle.h
index 95e1a94f..b8065594 100644
--- a/src/ccmain/fontstyle.h
+++ b/src/ccmain/fontstyle.h
@@ -21,6 +21,7 @@
#include <tesseract/export.h> // for TESS_API
+#include <utility> // for std::pair
#include <vector>
namespace tesseract {
@@ -85,6 +86,26 @@ struct WordStrokes {
TESS_API
void SetWordWeights(std::vector<WordStrokes> *words);
+// Finds the underlined words of a text line in an image with a depth of 1 bit,
+// which shows the text line, at least from the top of its lowercase letters,
+// and the space below it. The set pixels are the text.
+//
+// baseline has an entry for each column of the image: the distance of the
+// baseline from the upper edge of the image in pixels. x_height is the height
+// of the lowercase letters in pixels. Each word is given by its first and its
+// last column. All words of the text line must be given, because a line which
+// goes on beyond the text is a ruling, for example that of a table, and not
+// an underline. The image must therefore show some space on both sides of the
+// text, too.
+//
+// A word is underlined if a horizontal line below the baseline covers nearly
+// all of its columns. The line follows the baseline, so the text can be
+// skewed. Returns a value for each word.
+TESS_API
+std::vector<bool> FindUnderlinedWords(Image pix, const std::vector<float> &baseline,
+ float x_height,
+ const std::vector<std::pair<int, int>> &words);
+
// 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
diff --git a/src/ccmain/ltrresultiterator.cpp b/src/ccmain/ltrresultiterator.cpp
index 6500684c..ab87c36e 100644
--- a/src/ccmain/ltrresultiterator.cpp
+++ b/src/ccmain/ltrresultiterator.cpp
@@ -174,9 +174,9 @@ float LTRResultIterator::Confidence(PageIteratorLevel level) const {
// 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.
+// can be set nevertheless: with the parameter lstm_font_attributes, bold,
+// italic and underlined are estimated for words recognized by LSTM, which
+// have no font name and the font_id -1. Other words are never underlined.
// 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,
@@ -202,7 +202,7 @@ const char *LTRResultIterator::WordFontAttributes(bool *is_bold, bool *is_italic
*font_id = font_info->universal_id;
*is_bold = font_info->is_bold();
*is_italic = font_info->is_italic();
- *is_underlined = false; // TODO(rays) fix this!
+ *is_underlined = it_->word()->underlined;
*is_monospace = font_info->is_fixed_pitch();
*is_serif = font_info->is_serif();
result = font_info->name;
diff --git a/src/ccmain/pagesegmain.cpp b/src/ccmain/pagesegmain.cpp
index bcd62a48..dfe88f79 100644
--- a/src/ccmain/pagesegmain.cpp
+++ b/src/ccmain/pagesegmain.cpp
@@ -283,9 +283,17 @@ ColumnFinder *Tesseract::SetupPageSegAndDetectOrientation(PageSegMode pageseg_mo
if (tessedit_dump_pageseg_images) {
pixa_debug_.AddPix(pix_binary_, "PageSegInput");
}
- // Leptonica is used to find the rule/separator lines in the input.
+ // Leptonica is used to find the rule/separator lines in the input. The font
+ // style pass needs the removed lines, because a long underline is one of
+ // them.
+ Image pix_with_lines = lstm_font_attributes ? pix_binary_.copy() : nullptr;
LineFinder::FindAndRemoveLines(source_resolution_, textord_tabfind_show_vlines, pix_binary_,
&vertical_x, &vertical_y, music_mask_pix, &v_lines, &h_lines);
+ pix_removed_lines_.destroy();
+ if (pix_with_lines != nullptr) {
+ pixSubtract(pix_with_lines, pix_with_lines, pix_binary_);
+ pix_removed_lines_ = pix_with_lines;
+ }
if (tessedit_dump_pageseg_images) {
pixa_debug_.AddPix(pix_binary_, "NoLines");
}
diff --git a/src/ccmain/tesseractclass.cpp b/src/ccmain/tesseractclass.cpp
index 44683109..73e75225 100644
--- a/src/ccmain/tesseractclass.cpp
+++ b/src/ccmain/tesseractclass.cpp
@@ -440,7 +440,7 @@ Tesseract::Tesseract()
"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.",
+ "Estimate bold, italic and underlined 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 "
@@ -454,6 +454,7 @@ Tesseract::Tesseract()
backup_config_file_(nullptr)
, pix_binary_(nullptr)
+ , pix_removed_lines_(nullptr)
, pix_grey_(nullptr)
, pix_original_(nullptr)
, pix_thresholds_(nullptr)
@@ -495,6 +496,7 @@ void Tesseract::Clear() {
std::string debug_name = imagebasename + "_debug.pdf";
pixa_debug_.WritePDF(debug_name.c_str());
pix_binary_.destroy();
+ pix_removed_lines_.destroy();
pix_grey_.destroy();
pix_thresholds_.destroy();
deskew_ = FCOORD(1.0f, 0.0f);
diff --git a/src/ccmain/tesseractclass.h b/src/ccmain/tesseractclass.h
index 999de634..32fa595a 100644
--- a/src/ccmain/tesseractclass.h
+++ b/src/ccmain/tesseractclass.h
@@ -205,6 +205,7 @@ public:
// Destroy any existing pix and return a pointer to the pointer.
Image *mutable_pix_binary() {
pix_binary_.destroy();
+ pix_removed_lines_.destroy();
return &pix_binary_;
}
Image pix_binary() const {
@@ -990,6 +991,10 @@ 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_;
+ // 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.
+ Image pix_removed_lines_;
// Grey-level input image if the input was not binary, otherwise nullptr.
Image pix_grey_;
// Original input image. Color if the input was color.
diff --git a/src/ccstruct/pageres.cpp b/src/ccstruct/pageres.cpp
index aa8db4d3..4d096fd7 100644
--- a/src/ccstruct/pageres.cpp
+++ b/src/ccstruct/pageres.cpp
@@ -258,6 +258,7 @@ void WERD_RES::CopySimpleFields(const WERD_RES &source) {
done = source.done;
unlv_crunch_mode = source.unlv_crunch_mode;
small_caps = source.small_caps;
+ underlined = source.underlined;
odd_size = source.odd_size;
budget_skipped = source.budget_skipped;
fontinfo = source.fontinfo;
diff --git a/src/ccstruct/pageres.h b/src/ccstruct/pageres.h
index 082fd9ec..67efcf60 100644
--- a/src/ccstruct/pageres.h
+++ b/src/ccstruct/pageres.h
@@ -302,6 +302,7 @@ public:
bool tess_would_adapt = false; // Tess would adapt?
bool done = false; // ready for output?
bool small_caps = false; // word appears to be small caps
+ bool underlined = false; // word has a line below its baseline
bool odd_size = false; // word is bigger than line or leader dots.
// The result is a fake because the blob classification budget of the
// language was used up (see Wordrec::ClassificationBudgetExhausted()).
diff --git a/unittest/fontattributes_test.cc b/unittest/fontattributes_test.cc
index 55122e33..a7bd8e85 100644
--- a/unittest/fontattributes_test.cc
+++ b/unittest/fontattributes_test.cc
@@ -120,6 +120,7 @@ protected:
bool bold = false;
bool italic = false;
bool smallcaps = false;
+ bool underlined = false;
bool has_font = true;
switch (line) {
case 0:
@@ -129,7 +130,7 @@ protected:
italic = true;
break;
case 2:
- bold = italic = smallcaps = true;
+ bold = italic = smallcaps = underlined = true;
break;
case 3:
bold = word_in_line == 0;
@@ -138,18 +139,25 @@ protected:
bold = true;
italic = word_in_line % 2 == 1;
break;
+ case 5:
+ underlined = true;
+ break;
default:
has_font = false;
}
word->fontinfo = has_font ? &fonts_[(italic ? 1 : 0) | (bold ? 2 : 0)] : nullptr;
word->small_caps = smallcaps;
+ word->underlined = underlined;
+ num_underlined_ += underlined;
expected_alto_.push_back(std::string(bold ? "bold " : "") + (italic ? "italics " : "") +
- (smallcaps ? "smallcaps " : ""));
+ (smallcaps ? "smallcaps " : "") +
+ (underlined ? "underline " : ""));
if (!expected_alto_.back().empty()) {
expected_alto_.back().pop_back();
}
expected_page_.push_back(std::string(bold ? " bold=\"true\"" : "") +
(italic ? " italic=\"true\"" : "") +
+ (underlined ? " underlined=\"true\"" : "") +
(smallcaps ? " smallCaps=\"true\"" : ""));
++word_in_line;
}
@@ -157,8 +165,10 @@ protected:
// A line has the attributes which all of its words have.
expected_lines_[0] = " bold=\"true\"";
expected_lines_[1] = " italic=\"true\"";
- expected_lines_[2] = " bold=\"true\" italic=\"true\" smallCaps=\"true\"";
+ expected_lines_[2] =
+ " bold=\"true\" italic=\"true\" underlined=\"true\" smallCaps=\"true\"";
expected_lines_[4] = " bold=\"true\"";
+ expected_lines_[5] = " underlined=\"true\"";
std::unique_ptr<ResultIterator> result(api_.GetIterator());
ASSERT_NE(result, nullptr);
@@ -189,8 +199,36 @@ protected:
std::vector<std::string> expected_page_;
// The same for each text line.
std::vector<std::string> expected_lines_;
+ // Number of the underlined words.
+ int num_underlined_ = 0;
};
+// Returns how often a text contains another one.
+static int Count(const std::string &text, const std::string &part) {
+ int count = 0;
+ for (size_t pos = text.find(part); pos != std::string::npos; pos = text.find(part, pos + 1)) {
+ ++count;
+ }
+ return count;
+}
+
+TEST_F(FontAttributesTest, Hocr) {
+ ASSERT_NO_FATAL_FAILURE(Recognize());
+ if (IsSkipped()) {
+ return;
+ }
+ std::unique_ptr<char[]> hocr(api_.GetHOCRText(0));
+ ASSERT_NE(hocr, nullptr);
+ const std::string text(hocr.get());
+ ASSERT_GT(num_underlined_, 0);
+ EXPECT_EQ(Count(text, "<u>"), num_underlined_);
+ EXPECT_EQ(Count(text, "</u>"), num_underlined_);
+ // The element for underlined text is the innermost one.
+ EXPECT_NE(text.find("<strong><em><u>"), std::string::npos);
+ EXPECT_NE(text.find("</u></em></strong>"), std::string::npos);
+ EXPECT_EQ(text.find("<u><"), std::string::npos);
+}
+
TEST_F(FontAttributesTest, Alto) {
ASSERT_NO_FATAL_FAILURE(Recognize());
if (IsSkipped()) {
@@ -283,10 +321,14 @@ TEST_F(FontAttributesTest, NoAttributes) {
for (it.restart_page(); it.word() != nullptr; it.forward()) {
it.word()->fontinfo = nullptr;
it.word()->small_caps = false;
+ it.word()->underlined = false;
}
std::unique_ptr<char[]> alto(api_.GetAltoText(0));
ASSERT_NE(alto, nullptr);
EXPECT_EQ(std::string(alto.get()).find("STYLE"), std::string::npos);
+ std::unique_ptr<char[]> hocr(api_.GetHOCRText(0));
+ ASSERT_NE(hocr, nullptr);
+ EXPECT_EQ(std::string(hocr.get()).find("<u>"), std::string::npos);
for (const char *level : {"0", "1"}) {
ASSERT_TRUE(api_.SetVariable("page_xml_level", level));
std::unique_ptr<char[]> page(api_.GetPAGEText(0));
diff --git a/unittest/fontstyle_test.cc b/unittest/fontstyle_test.cc
index ecbbb2c1..6ce8a843 100644
--- a/unittest/fontstyle_test.cc
+++ b/unittest/fontstyle_test.cc
@@ -31,6 +31,7 @@
#include <cmath>
#include <memory>
#include <string>
+#include <utility>
#include <vector>
namespace tesseract {
@@ -321,6 +322,192 @@ TEST(FontStyleTest, NamelessFonts) {
EXPECT_TRUE(named == named);
}
+// A text line for the search of underlines: an image with words of vertical
+// bars, which stand for the stems of letters with the x-height kXHeight. The
+// baseline rises by the given number of rows from the left to the right.
+class UnderlineTest : public testing::Test {
+protected:
+ static const int kWidth = 600;
+ static const int kHeight = 90;
+ static const int kXHeight = 20;
+ // Row below the stems at the left edge of the image.
+ static const int kBaseline = 50;
+
+ void SetUp() override {
+ pix_ = pixCreate(kWidth, kHeight, 1);
+ ASSERT_TRUE(pix_ != nullptr);
+ }
+
+ void TearDown() override {
+ pix_.destroy();
+ }
+
+ // Sets the baseline. Call this before the words are added.
+ void SetRise(int rise) {
+ baseline_.resize(kWidth);
+ for (int x = 0; x < kWidth; ++x) {
+ baseline_[x] = kBaseline - static_cast<float>(rise) * x / (kWidth - 1);
+ }
+ }
+
+ // Returns the first row below the baseline in the given column.
+ int Row(int x) const {
+ return static_cast<int>(std::floor(baseline_[x] + 0.5f));
+ }
+
+ // Adds a word from the column left to the column right.
+ void AddWord(int left, int right) {
+ if (baseline_.empty()) {
+ SetRise(0);
+ }
+ for (int stem = left; stem + 3 <= right + 1; stem += 9) {
+ for (int x = stem; x < stem + 3; ++x) {
+ for (int y = Row(x) - kXHeight; y < Row(x); ++y) {
+ pixSetPixel(pix_, x, y, 1);
+ }
+ }
+ }
+ words_.emplace_back(left, right);
+ }
+
+ // Draws a line from the column left to the column right which is parallel
+ // to the baseline. offset is the distance of its upper edge from the first
+ // row below the baseline.
+ void AddLine(int left, int right, int offset, int thickness) {
+ for (int x = left; x <= right; ++x) {
+ for (int y = Row(x) + offset; y < Row(x) + offset + thickness; ++y) {
+ pixSetPixel(pix_, x, y, 1);
+ }
+ }
+ }
+
+ std::vector<bool> Find() const {
+ return FindUnderlinedWords(pix_, baseline_, kXHeight, words_);
+ }
+
+ Image pix_;
+ std::vector<float> baseline_;
+ std::vector<std::pair<int, int>> words_;
+};
+
+TEST_F(UnderlineTest, FindsUnderlinedWord) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddWord(280, 380);
+ EXPECT_EQ(Find(), std::vector<bool>({false, false, false}));
+ AddLine(160, 260, 4, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({false, true, false}));
+}
+
+// A line below several words underlines all of them, also the short ones.
+TEST_F(UnderlineTest, FindsUnderlinedRun) {
+ AddWord(60, 140);
+ AddWord(160, 172);
+ AddWord(190, 290);
+ AddWord(310, 400);
+ AddLine(160, 290, 5, 3);
+ EXPECT_EQ(Find(), std::vector<bool>({false, true, true, false}));
+}
+
+// The line of a short word alone could be a part of a letter.
+TEST_F(UnderlineTest, IgnoresShortLines) {
+ AddWord(60, 140);
+ AddWord(160, 172);
+ AddWord(190, 290);
+ AddLine(160, 172, 4, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({false, false, false}));
+}
+
+// The baseline of the layout analysis is too low where descenders join the
+// text and its underline, so the line can be on it.
+TEST_F(UnderlineTest, FindsLineOnBaseline) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddLine(160, 260, -3, 3);
+ EXPECT_EQ(Find(), std::vector<bool>({false, true}));
+}
+
+TEST_F(UnderlineTest, FindsLineOfSkewedText) {
+ SetRise(24);
+ AddWord(60, 140);
+ AddWord(160, 300);
+ AddWord(320, 420);
+ AddLine(160, 300, 4, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({false, true, false}));
+}
+
+// A line which goes on beyond the text is a ruling, for example of a table.
+TEST_F(UnderlineTest, RulingIsNoUnderline) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddWord(280, 380);
+ AddLine(60, 380, 6, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({true, true, true}));
+ AddLine(381, 420, 6, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({false, false, false}));
+}
+
+// The same if the layout analysis added the end of the ruling to a word.
+TEST_F(UnderlineTest, RulingInWordIsNoUnderline) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddLine(20, 300, 6, 2);
+ words_[0].first = 20;
+ words_[1].second = 300;
+ EXPECT_EQ(Find(), std::vector<bool>({false, false}));
+}
+
+// A full stop has no pixels at the height of the letters, but it is text, so
+// the line below it does not go on beyond the text.
+TEST_F(UnderlineTest, LowPunctuationIsText) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddLine(272, 275, -4, 4);
+ words_[1].second = 275;
+ AddLine(160, 275, 4, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({false, true}));
+}
+
+// The feet of the letters are short lines on the baseline.
+TEST_F(UnderlineTest, SerifsAreNoUnderline) {
+ AddWord(60, 240);
+ for (int stem = 60; stem + 3 <= 241; stem += 9) {
+ AddLine(stem - 2, stem + 4, -2, 2);
+ }
+ EXPECT_EQ(Find(), std::vector<bool>({false}));
+}
+
+// Neither is the bar of a wide letter, which is shorter than a line.
+TEST_F(UnderlineTest, LetterBarIsNoUnderline) {
+ AddWord(60, 84);
+ AddLine(60, 84, -3, 3);
+ EXPECT_EQ(Find(), std::vector<bool>({false}));
+}
+
+// Text on a dark background has no line below it.
+TEST_F(UnderlineTest, DarkBackgroundIsNoUnderline) {
+ AddWord(60, 140);
+ AddWord(160, 260);
+ AddLine(60, 260, 2, 30);
+ EXPECT_EQ(Find(), std::vector<bool>({false, false}));
+}
+
+TEST_F(UnderlineTest, RejectsUnusableInput) {
+ AddWord(60, 140);
+ AddLine(60, 140, 4, 2);
+ EXPECT_EQ(Find(), std::vector<bool>({true}));
+ EXPECT_EQ(FindUnderlinedWords(nullptr, baseline_, kXHeight, words_), std::vector<bool>({false}));
+ EXPECT_EQ(FindUnderlinedWords(pix_, baseline_, 0.0f, words_), std::vector<bool>({false}));
+ baseline_.pop_back();
+ EXPECT_EQ(Find(), std::vector<bool>({false}));
+ Image grey = pixCreate(kWidth, kHeight, 8);
+ baseline_.push_back(kBaseline);
+ EXPECT_EQ(FindUnderlinedWords(grey, baseline_, kXHeight, words_), std::vector<bool>({false}));
+ grey.destroy();
+ words_.clear();
+ EXPECT_TRUE(Find().empty());
+}
+
// A word with the font attributes which the API reports for it.
struct StyledWord {
std::string text;
@@ -328,6 +515,7 @@ struct StyledWord {
int line = -1;
bool bold = false;
bool italic = false;
+ bool underlined = false;
bool has_font_name = false;
int font_id = 0;
int pointsize = 0;
@@ -382,11 +570,10 @@ protected:
word.line = static_cast<int>(line);
}
}
- bool underlined, monospace, serif, smallcaps;
+ bool monospace, serif, smallcaps;
word.has_font_name =
- it->WordFontAttributes(&word.bold, &word.italic, &underlined, &monospace, &serif,
+ it->WordFontAttributes(&word.bold, &word.italic, &word.underlined, &monospace, &serif,
&smallcaps, &word.pointsize, &word.font_id) != nullptr;
- EXPECT_FALSE(underlined);
EXPECT_FALSE(monospace);
EXPECT_FALSE(serif);
words.push_back(word);
@@ -532,6 +719,62 @@ TEST_F(FontStyleApiTest, FindsStylesInRotatedPage) {
EXPECT_GE(num_bold, 6);
}
+// The words of a text line with a line below it must be underlined, with and
+// without a layout analysis, which removes long lines from the image.
+TEST_F(FontStyleApiTest, FindsUnderlinedLine) {
+ const int kLine = 3;
+ ASSERT_TRUE(api_.SetVariable("lstm_font_attributes", "1"));
+ std::vector<StyledWord> words = Recognize();
+ ASSERT_EQ(line_boxes_.size(), 8u);
+ for (const auto &word : words) {
+ EXPECT_FALSE(word.underlined) << word.text;
+ }
+ // The box of the text line ends with its descenders.
+ const std::array<int, 4> &box = line_boxes_[kLine];
+ for (int y = box[3] - 4; y < box[3] - 1; ++y) {
+ for (int x = box[0]; x < box[2]; ++x) {
+ pixSetPixel(pix_, x, y, 1);
+ }
+ }
+ for (const PageSegMode mode : {PSM_AUTO, PSM_SINGLE_BLOCK}) {
+ api_.SetPageSegMode(mode);
+ words = Recognize();
+ int num_underlined = 0;
+ for (const auto &word : words) {
+ if (word.line == kLine) {
+ num_underlined += word.underlined;
+ } else {
+ EXPECT_FALSE(word.underlined) << word.text;
+ }
+ }
+ EXPECT_GE(num_underlined, 6) << "mode " << mode;
+ }
+}
+
+// A ruling below a text line goes on beyond the text and is no underline.
+TEST_F(FontStyleApiTest, RulingIsNoUnderline) {
+ const int kLine = 3;
+ ASSERT_TRUE(api_.SetVariable("lstm_font_attributes", "1"));
+ std::vector<StyledWord> words = Recognize();
+ ASSERT_EQ(line_boxes_.size(), 8u);
+ const std::array<int, 4> &box = line_boxes_[kLine];
+ ASSERT_GT(box[0], 20);
+ ASSERT_LT(box[2] + 20, pixGetWidth(pix_));
+ for (int y = box[3] - 4; y < box[3] - 1; ++y) {
+ for (int x = 4; x < pixGetWidth(pix_) - 4; ++x) {
+ pixSetPixel(pix_, x, y, 1);
+ }
+ }
+ for (const PageSegMode mode : {PSM_AUTO, PSM_SINGLE_BLOCK}) {
+ api_.SetPageSegMode(mode);
+ words = Recognize();
+ ASSERT_GT(words.size(), 40u);
+ for (const auto &word : words) {
+ EXPECT_FALSE(word.underlined) << word.text;
+ }
+ }
+}
+
// Larger text has wider strokes, but it is not bold.
TEST_F(FontStyleApiTest, LargerTextIsNotBold) {
const int kBoldLine = 5;