Commit dd8e2e48 for tesseract

commit dd8e2e48b5c0a84586e459b77321e6d1776ea5c6
Author: Stefan Weil <sw@weilnetz.de>
Date:   Wed Nov 25 15:02:29 2026 +0100

    Recognize small words between lines of very large text

    The layout analysis tests every blob which is not part of a text line
    as a diacritic of a nearby larger blob. Next to very large text nearly
    anything passes that test. The three letters of a small "und" between
    the two lines of a newspaper title were shared out as diacritics among
    letters of both title lines, where they are far too small to be read,
    so the word was missing in the result.

    Keep the layout as it is, because a text line for the small word would
    split the lines of the large text. Save a copy of each diacritic which
    is at least as high as the normal text of the page, has a base character
    of at least 2.5 times its height and stands in a row of at least three
    similar blobs. After the blocks have been made, add a block of its own
    for each such row, after the block of the large text above it.

    The layout analysis rotates, reflects and deskews the boxes of the
    blobs, not their outlines. Each copy gets the box of its blob and is
    reflected and deskewed with the other blobs, so the new block is in the
    same coordinates as the other blocks on pages which are skewed, turned
    or read from right to left.

    Assisted-by: Claude Fable 5.2 (Anthropic)
    Signed-off-by: Stefan Weil <sw@weilnetz.de>

diff --git a/src/ccstruct/blobbox.cpp b/src/ccstruct/blobbox.cpp
index d40ee074..7b657fd9 100644
--- a/src/ccstruct/blobbox.cpp
+++ b/src/ccstruct/blobbox.cpp
@@ -957,6 +957,7 @@ TO_BLOCK::~TO_BLOCK() {
   BLOBNBOX::clear_blobnboxes(&noise_blobs);
   BLOBNBOX::clear_blobnboxes(&small_blobs);
   BLOBNBOX::clear_blobnboxes(&large_blobs);
+  BLOBNBOX::clear_blobnboxes(&small_word_blobs);
 }

 // Helper function to divide the input blobs over noise, small, medium
diff --git a/src/ccstruct/blobbox.h b/src/ccstruct/blobbox.h
index c35282e5..53aa379f 100644
--- a/src/ccstruct/blobbox.h
+++ b/src/ccstruct/blobbox.h
@@ -778,6 +778,11 @@ public:
   BLOBNBOX_LIST noise_blobs; // very small
   BLOBNBOX_LIST small_blobs; // fairly small
   BLOBNBOX_LIST large_blobs; // big blobs
+  // Copies of the letters of small words which the layout analysis treats
+  // as diacritics of very large text, see
+  // StrokeWidth::SaveLetterOfSmallWord. Their boxes are reflected and
+  // deskewed like those of the other lists.
+  BLOBNBOX_LIST small_word_blobs;
   BLOCK *block;              // real block
   PITCH_TYPE pitch_decision; // how strong is decision
   float line_spacing;        // estimate
diff --git a/src/textord/colfind.cpp b/src/textord/colfind.cpp
index f7f9253d..a234dda8 100644
--- a/src/textord/colfind.cpp
+++ b/src/textord/colfind.cpp
@@ -457,6 +457,7 @@ int ColumnFinder::FindBlocks(PageSegMode pageseg_mode,
     part_grid_.ExtractPartitionsAsBlocks(blocks, to_blocks);
   } else {
     TransformToBlocks(blocks, to_blocks);
+    AddSmallWordBlocks(input_block, blocks, to_blocks);
   }
   if (textord_debug_tabfind) {
     tprintf("Found %d blocks, %d to_blocks\n", blocks->length(), to_blocks->length());
@@ -1495,6 +1496,7 @@ void ColumnFinder::ReflectForRtl(TO_BLOCK *input_block, BLOBNBOX_LIST *bblobs) {
   ReflectBlobList(&input_block->small_blobs);
   ReflectBlobList(&input_block->noise_blobs);
   ReflectBlobList(&input_block->large_blobs);
+  ReflectBlobList(&input_block->small_word_blobs);
   // Update the denorm with the reflection.
   auto *new_denorm = new DENORM;
   new_denorm->SetupNormalization(nullptr, nullptr, denorm_, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f);
@@ -1536,6 +1538,139 @@ static void RotateAndExplodeBlobList(const FCOORD &blob_rotation, BLOBNBOX_LIST
   }
 }

+// Makes a text block of its own from each row of the letters which
+// StrokeWidth::SaveLetterOfSmallWord has saved in block->small_word_blobs,
+// and puts it after the block of the large text above it.
+// The letters are the copies of blobs which the layout analysis has added as
+// diacritics to very large text, so the blocks of that text are not changed.
+void ColumnFinder::AddSmallWordBlocks(TO_BLOCK *block, BLOCK_LIST *blocks,
+                                      TO_BLOCK_LIST *to_blocks) {
+  // Sort the letters from left to right, without the duplicates which a
+  // second pass of the diacritic test can leave.
+  std::vector<BLOBNBOX *> letters;
+  BLOBNBOX_IT letter_it(&block->small_word_blobs);
+  for (letter_it.mark_cycle_pt(); !letter_it.empty(); letter_it.forward()) {
+    BLOBNBOX *letter = letter_it.extract();
+    bool duplicate = false;
+    for (const BLOBNBOX *other : letters) {
+      if (other->bounding_box() == letter->bounding_box()) {
+        duplicate = true;
+        break;
+      }
+    }
+    if (duplicate) {
+      delete letter;
+    } else {
+      letters.push_back(letter);
+    }
+  }
+  std::sort(letters.begin(), letters.end(), [](const BLOBNBOX *a, const BLOBNBOX *b) {
+    return a->bounding_box().left() < b->bounding_box().left();
+  });
+  // Collect the rows: a letter joins the row which it overlaps vertically
+  // and which ends near its left side.
+  std::vector<std::vector<BLOBNBOX *>> rows;
+  std::vector<TBOX> row_boxes;
+  for (BLOBNBOX *letter : letters) {
+    const TBOX &box = letter->bounding_box();
+    size_t r = 0;
+    for (; r < rows.size(); ++r) {
+      const TBOX &last_box = rows[r].back()->bounding_box();
+      if ((box.major_y_overlap(row_boxes[r]) || row_boxes[r].major_y_overlap(box)) &&
+          box.x_gap(last_box) <= std::max(box.height(), last_box.height())) {
+        break;
+      }
+    }
+    if (r == rows.size()) {
+      rows.emplace_back();
+      row_boxes.push_back(box);
+    } else {
+      row_boxes[r] += box;
+    }
+    rows[r].push_back(letter);
+  }
+  for (size_t r = 0; r < rows.size(); ++r) {
+    if (rows[r].size() < static_cast<size_t>(kMinSmallWordBlobs)) {
+      for (BLOBNBOX *letter : rows[r]) {
+        delete letter;
+      }
+      continue;
+    }
+    const TBOX &box = row_boxes[r];
+    auto *new_block = new BLOCK("", true, 0, 0, box.left(), box.bottom(), box.right(), box.top());
+    new_block->pdblk.set_poly_block(new POLY_BLOCK(box, PT_FLOWING_TEXT));
+    auto *new_to_block = new TO_BLOCK(new_block);
+    BLOBNBOX_IT blob_it(&new_to_block->blobs);
+    STATS heights(0, box.height());
+    for (BLOBNBOX *letter : rows[r]) {
+      heights.add(letter->bounding_box().height(), 1);
+      blob_it.add_to_end(letter);
+    }
+    new_to_block->line_size = std::max(1.0f, static_cast<float>(heights.median()));
+    new_to_block->line_spacing = static_cast<float>(box.height());
+    new_to_block->max_blob_size = static_cast<float>(box.height() + 1);
+    if (textord_debug_tabfind) {
+      tprintf("Small word of %zu letters next to large text:", rows[r].size());
+      box.print();
+    }
+    // Reading order: after the nearest block above the word which shares its
+    // columns (the upper line of the large text), else in front of the first
+    // block which lies below the word.
+    const int mid_y = (box.bottom() + box.top()) / 2;
+    BLOCK *prev_block = nullptr;
+    int prev_mid_y = 0;
+    BLOCK *next_block = nullptr;
+    BLOCK_IT block_it(blocks);
+    for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
+      const TBOX &other = block_it.data()->pdblk.bounding_box();
+      const int other_mid_y = (other.bottom() + other.top()) / 2;
+      if (other_mid_y > mid_y && other.major_x_overlap(box) &&
+          (prev_block == nullptr || other_mid_y < prev_mid_y)) {
+        prev_block = block_it.data();
+        prev_mid_y = other_mid_y;
+      }
+      if (next_block == nullptr && other.top() < mid_y) {
+        next_block = block_it.data();
+      }
+    }
+    if (prev_block != nullptr) {
+      // The block which follows prev_block, if there is one.
+      next_block = nullptr;
+      for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
+        if (block_it.data() == prev_block) {
+          if (!block_it.at_last()) {
+            next_block = block_it.data_relative(1);
+          }
+          break;
+        }
+      }
+    }
+    if (next_block == nullptr) {
+      block_it.add_to_end(new_block);
+    } else {
+      for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
+        if (block_it.data() == next_block) {
+          block_it.add_before_then_move(new_block);
+          break;
+        }
+      }
+    }
+    TO_BLOCK_IT to_block_it(to_blocks);
+    bool added = false;
+    for (to_block_it.mark_cycle_pt(); next_block != nullptr && !to_block_it.cycled_list();
+         to_block_it.forward()) {
+      if (to_block_it.data()->block == next_block) {
+        to_block_it.add_before_then_move(new_to_block);
+        added = true;
+        break;
+      }
+    }
+    if (!added) {
+      to_block_it.add_to_end(new_to_block);
+    }
+  }
+}
+
 // Undo the deskew that was done in FindTabVectors, as recognition is done
 // without correcting blobs or blob outlines for skew.
 // Reskew the completed blocks to put them back to the original rotated coords
diff --git a/src/textord/colfind.h b/src/textord/colfind.h
index 4c82b783..094da0fc 100644
--- a/src/textord/colfind.h
+++ b/src/textord/colfind.h
@@ -253,6 +253,11 @@ private:
   // Transform the grid of partitions to the output blocks.
   void TransformToBlocks(BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks);

+  // Makes a text block of its own from each row of the letters which
+  // StrokeWidth::SaveLetterOfSmallWord has saved in block->small_word_blobs,
+  // and puts it after the block of the large text above it.
+  void AddSmallWordBlocks(TO_BLOCK *block, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks);
+
   // Reflect the blob boxes (but not the outlines) in the y-axis so that
   // the blocks get created in the correct RTL order. Rotates the blobs
   // in the input_block and the bblobs list.
diff --git a/src/textord/strokewidth.cpp b/src/textord/strokewidth.cpp
index a54ae956..969ea48e 100644
--- a/src/textord/strokewidth.cpp
+++ b/src/textord/strokewidth.cpp
@@ -85,6 +85,10 @@ const double kMaxDiacriticDistanceRatio = 1.25;
 // Max x-gap between a diacritic and its base char as a fraction of the height
 // of the base char (allowing other blobs to fill the gap.)
 const double kMaxDiacriticGapToBaseCharHeight = 1.0;
+// Min ratio of the height of the base character to the height of a diacritic
+// for the diacritic to be tested as the letter of a small word, see
+// StrokeWidth::SaveLetterOfSmallWord.
+const double kMinBaseCharToSmallWordRatio = 2.5;
 // Ratio between longest side of a line and longest side of a character.
 // (neighbor_min > blob_min * kLineTrapShortest &&
 //  neighbor_max < blob_max / kLineTrapLongest)
@@ -1476,6 +1480,89 @@ void StrokeWidth::FindHorizontalTextChains(ColPartitionGrid *part_grid) {
   }
 }

+// Returns true if blob stands in a horizontal row of at least
+// kMinSmallWordBlobs blobs of similar height which are close to each other,
+// like the letters of a word. Real diacritics come alone or in pairs
+// (dieresis, quotes).
+// The grid is const really.
+static bool InRowOfSimilarBlobs(BlobGrid *grid, const BLOBNBOX *blob) {
+  int count = 1;
+  for (int dir = -1; dir <= 1 && count < kMinSmallWordBlobs; dir += 2) {
+    TBOX box(blob->bounding_box());
+    while (count < kMinSmallWordBlobs) {
+      // Look for the nearest similar blob on this side of box.
+      const int max_gap = box.height();
+      TBOX search_box(box);
+      if (dir > 0) {
+        search_box.set_left(box.right());
+        search_box.set_right(box.right() + max_gap);
+      } else {
+        search_box.set_right(box.left());
+        search_box.set_left(box.left() - max_gap);
+      }
+      BlobGridSearch rsearch(grid);
+      rsearch.SetUniqueMode(true);
+      rsearch.StartRectSearch(search_box);
+      const BLOBNBOX *best = nullptr;
+      int best_gap = 0;
+      BLOBNBOX *neighbour;
+      while ((neighbour = rsearch.NextRectSearch()) != nullptr) {
+        if (neighbour == blob) {
+          continue;
+        }
+        const TBOX &nbox = neighbour->bounding_box();
+        const bool beyond = dir > 0 ? nbox.left() > box.left() && nbox.right() > box.right()
+                                    : nbox.right() < box.right() && nbox.left() < box.left();
+        if (!beyond || nbox.height() > 2 * box.height() || box.height() > 2 * nbox.height() ||
+            !(nbox.major_y_overlap(box) || box.major_y_overlap(nbox))) {
+          continue;
+        }
+        const int gap = box.x_gap(nbox);
+        if (gap <= max_gap && (best == nullptr || gap < best_gap)) {
+          best = neighbour;
+          best_gap = gap;
+        }
+      }
+      if (best == nullptr) {
+        break;
+      }
+      box = best->bounding_box();
+      ++count;
+    }
+  }
+  return count >= kMinSmallWordBlobs;
+}
+
+// Saves a copy of blob in block->small_word_blobs if blob, which has just
+// been accepted as a diacritic, is more likely a letter of a small word next
+// to very large text, like a small "and" between the two lines of a large
+// title: it is at least as high as the normal text of the page, much smaller
+// than its base character, and it stands in a row of similar blobs. The
+// letters of such a word are shared out as diacritics among the letters of
+// the large text, where they are far too small to be read. The layout is
+// left as it is; ColumnFinder::AddSmallWordBlocks makes a block of its own
+// from the copies.
+void StrokeWidth::SaveLetterOfSmallWord(BlobGrid *small_grid, const BLOBNBOX *blob,
+                                        TO_BLOCK *block) {
+  const BLOBNBOX *base_blob = blob->base_char_blob();
+  const int height = blob->bounding_box().height();
+  if (base_blob == nullptr || blob->cblob() == nullptr || height < gridsize() ||
+      base_blob->bounding_box().height() < kMinBaseCharToSmallWordRatio * height ||
+      !InRowOfSimilarBlobs(small_grid, blob)) {
+    return;
+  }
+  auto *copy = new BLOBNBOX(C_BLOB::deep_copy(blob->cblob()));
+  copy->set_owns_cblob(true);
+  // The outlines stay in the coordinates of the image, but the layout
+  // analysis rotates, reflects and deskews the boxes of the blobs. The copy
+  // needs the box of blob, and all which is done later to that box, for its
+  // block to be in the same coordinates as the other blocks.
+  copy->set_bounding_box(blob->bounding_box());
+  copy->set_region_type(BRT_TEXT);
+  BLOBNBOX_IT it(&block->small_word_blobs);
+  it.add_to_end(copy);
+}
+
 // Finds diacritics and saves their base character in the blob.
 // The objective is to move all diacritics to the noise_blobs list, so
 // they don't mess up early textline finding/merging, or force splits
@@ -1494,6 +1581,7 @@ void StrokeWidth::TestDiacritics(ColPartitionGrid *part_grid, TO_BLOCK *block) {
     BLOBNBOX *blob = small_it.data();
     if (blob->owner() == nullptr && !blob->IsDiacritic() && DiacriticBlob(&small_grid, blob)) {
       ++small_diacritics;
+      SaveLetterOfSmallWord(&small_grid, blob, block);
     }
   }
   BLOBNBOX_IT blob_it(&block->blobs);
@@ -1506,6 +1594,7 @@ void StrokeWidth::TestDiacritics(ColPartitionGrid *part_grid, TO_BLOCK *block) {
     ColPartition *part = blob->owner();
     if (part == nullptr && DiacriticBlob(&small_grid, blob)) {
       ++medium_diacritics;
+      SaveLetterOfSmallWord(&small_grid, blob, block);
       RemoveBBox(blob);
       small_it.add_to_end(blob_it.extract());
     } else if (part != nullptr && !part->block_owned() && part->boxes_count() < 3) {
@@ -1531,6 +1620,7 @@ void StrokeWidth::TestDiacritics(ColPartitionGrid *part_grid, TO_BLOCK *block) {
           box->set_owner(nullptr);
           box_it.forward();
           ++medium_diacritics;
+          SaveLetterOfSmallWord(&small_grid, box, block);
           // We remove the blob from the grid so it isn't found by subsequent
           // searches where we might not want to include diacritics.
           RemoveBBox(box);
diff --git a/src/textord/strokewidth.h b/src/textord/strokewidth.h
index e7b5f43e..c4290cc3 100644
--- a/src/textord/strokewidth.h
+++ b/src/textord/strokewidth.h
@@ -50,6 +50,11 @@ enum PartitionFindResult {
  * It is used to find good large blobs and move them to the normal blobs
  * by virtue of having a reasonable strokewidth compatible neighbour.
  */
+// Min number of similar blobs in a row which make a small word next to very
+// large text instead of diacritics of that text, see
+// StrokeWidth::SaveLetterOfSmallWord and ColumnFinder::AddSmallWordBlocks.
+const int kMinSmallWordBlobs = 3;
+
 class StrokeWidth : public BlobGrid {
 public:
   StrokeWidth(int gridsize, const ICOORD &bleft, const ICOORD &tright);
@@ -231,6 +236,9 @@ private:
   // that are not in this grid, but may be useful for determining a connection
   // between blob and its potential base character. (See DiacriticXGapFilled.)
   bool DiacriticBlob(BlobGrid *small_grid, BLOBNBOX *blob);
+  // Saves a copy of the diacritic blob in block->small_word_blobs if it is
+  // more likely a letter of a small word next to very large text.
+  void SaveLetterOfSmallWord(BlobGrid *small_grid, const BLOBNBOX *blob, TO_BLOCK *block);
   // Returns true if there is no gap between the base char and the diacritic
   // bigger than a fraction of the height of the base char:
   // Eg: line end.....'
diff --git a/src/textord/tabfind.cpp b/src/textord/tabfind.cpp
index 03c063b8..1f90fe03 100644
--- a/src/textord/tabfind.cpp
+++ b/src/textord/tabfind.cpp
@@ -1294,6 +1294,7 @@ bool TabFind::Deskew(TabVector_LIST *hlines, BLOBNBOX_LIST *image_blobs, TO_BLOC
   RotateBlobList(*deskew, &block->blobs);
   RotateBlobList(*deskew, &block->small_blobs);
   RotateBlobList(*deskew, &block->noise_blobs);
+  RotateBlobList(*deskew, &block->small_word_blobs);

   // Rotate the horizontal vectors. The vertical vectors don't need
   // rotating as they can just be refitted.
diff --git a/unittest/layout_test.cc b/unittest/layout_test.cc
index ee870122..e211ae53 100644
--- a/unittest/layout_test.cc
+++ b/unittest/layout_test.cc
@@ -216,6 +216,61 @@ protected:
     return width;
   }

+  // A rectangle in the coordinates of the image.
+  struct Rect {
+    int left;
+    int top;
+    int right;
+    int bottom;
+  };
+
+  // Writes text with the largest built in font, enlarged by the factor
+  // scale, with its centre at x and its baseline at y on pix. Returns the
+  // rectangle of its pixels.
+  static Rect DrawCentredText(Pix *pix, const char *text, int x, int y,
+                              int scale) {
+    const int kBaseline = 60;
+    Pix *line = pixCreate(1200, 100, 8);
+    pixSetAll(line);
+    DrawText(line, text, 10, kBaseline, 20);
+    Pix *binary = pixThresholdToBinary(line, 128);
+    Box *box = nullptr;
+    pixClipToForeground(binary, nullptr, &box);
+    CHECK(box != nullptr);
+    l_int32 left, top, width, height;
+    boxGetGeometry(box, &left, &top, &width, &height);
+    Pix *word = pixClipRectangle(line, box, nullptr);
+    Pix *scaled = pixScaleBySampling(word, scale, scale);
+    Rect rect;
+    rect.left = x - width * scale / 2;
+    rect.top = y - (kBaseline - top) * scale;
+    rect.right = rect.left + width * scale;
+    rect.bottom = rect.top + height * scale;
+    pixRasterop(pix, rect.left, rect.top, width * scale, height * scale,
+                PIX_SRC, scaled, 0, 0);
+    pixDestroy(&scaled);
+    pixDestroy(&word);
+    boxDestroy(&box);
+    pixDestroy(&binary);
+    pixDestroy(&line);
+    return rect;
+  }
+
+  // Makes a page of text with a title of two lines of very large text and a
+  // small word between them, like the title of a newspaper. The letters of
+  // the small word are as high as the lines of the text, and they are so
+  // close to the title that the layout analysis takes them for diacritics
+  // of its letters. Returns the rectangle of the small word in small_word.
+  static Pix *MakeTitlePage(Rect *small_word) {
+    Pix *page = MakeTextPage();
+    // Make room at the top of the text.
+    FillRect(page, 200, 300, 1600, 660, false);
+    DrawCentredText(page, "German Gazette", kPageWidth / 2, 400, 3);
+    *small_word = DrawCentredText(page, "and", kPageWidth / 2, 500, 1);
+    DrawCentredText(page, "Prussian Herald", kPageWidth / 2, 720, 3);
+    return page;
+  }
+
   // Makes a white 8 bit page with 32 lines of text.
   static Pix *MakeTextPage() {
     Pix *pix = pixCreate(kPageWidth, kPageHeight, 8);
@@ -254,11 +309,12 @@ protected:
   // Takes a synthetic page, which is destroyed here, and runs the layout
   // analysis on it. A resolution of 0 leaves it to Tesseract.
   void AnalysePage(Pix *page, int resolution = 0,
-                   tesseract::PageSegMode mode = tesseract::PSM_AUTO) {
+                   tesseract::PageSegMode mode = tesseract::PSM_AUTO,
+                   const char *lang = "eng") {
     src_pix_.destroy();
     src_pix_ = pixThresholdToBinary(page, 128);
     pixDestroy(&page);
-    ASSERT_EQ(api_.Init(TessdataPath().c_str(), "eng"), 0);
+    ASSERT_EQ(api_.Init(TessdataPath().c_str(), lang), 0);
     api_.SetPageSegMode(mode);
     api_.SetImage(src_pix_);
     if (resolution > 0) {
@@ -288,6 +344,66 @@ protected:
     return count;
   }

+  // Finds the text line which the last AnalysePage found completely inside
+  // area, not more than margin pixels from its sides. Sets line to its box
+  // and block to the bounding box of the polygon of its block. Returns false
+  // if there is no such line or more than one.
+  bool FindTextLineIn(const Rect &area, int margin, Rect *line, Rect *block) {
+    int count = 0;
+    if (page_it_ == nullptr) {
+      return false;
+    }
+    page_it_->Begin();
+    do {
+      Rect box;
+      if (!PTIsTextType(page_it_->BlockType()) ||
+          !page_it_->BoundingBox(tesseract::RIL_TEXTLINE, &box.left, &box.top,
+                                 &box.right, &box.bottom) ||
+          box.left < area.left - margin || box.right > area.right + margin ||
+          box.top < area.top - margin || box.bottom > area.bottom + margin) {
+        continue;
+      }
+      ++count;
+      *line = box;
+      *block = {0, 0, 0, 0};
+      Pta *polygon = page_it_->BlockPolygon();
+      if (polygon != nullptr) {
+        l_float32 left, right, top, bottom;
+        ptaGetRange(polygon, &left, &right, &top, &bottom);
+        *block = {static_cast<int>(left), static_cast<int>(top),
+                  static_cast<int>(right), static_cast<int>(bottom)};
+        ptaDestroy(&polygon);
+      }
+    } while (page_it_->Next(tesseract::RIL_TEXTLINE));
+    return count == 1;
+  }
+
+  // Expects that the two rectangles differ by not more than tolerance pixels
+  // on each side.
+  static void ExpectNear(const Rect &a, const Rect &b, int tolerance) {
+    EXPECT_NEAR(a.left, b.left, tolerance);
+    EXPECT_NEAR(a.top, b.top, tolerance);
+    EXPECT_NEAR(a.right, b.right, tolerance);
+    EXPECT_NEAR(a.bottom, b.bottom, tolerance);
+  }
+
+  // Expects that the last AnalysePage found the small word of a page from
+  // MakeTitlePage as a text line with a block of its own, which is where
+  // the line is. The word is at small_word, not more than margin pixels
+  // away, and its line and its block fit with the given tolerance.
+  void ExpectSmallWordBlock(const Rect &small_word, int margin,
+                            int tolerance) {
+    Rect line;
+    Rect block;
+    ASSERT_TRUE(FindTextLineIn(small_word, margin, &line, &block));
+    // All of the word, not a part of it.
+    EXPECT_NEAR(line.right - line.left, small_word.right - small_word.left,
+                tolerance);
+    EXPECT_NEAR(line.bottom - line.top, small_word.bottom - small_word.top,
+                tolerance);
+    ExpectNear(block, line, tolerance);
+  }
+
   // Returns the number of text lines found where the page number is.
   int CountPageNumberLines() {
     return CountTextLinesIn(kPageNumberLeft - 50,
@@ -434,4 +550,71 @@ TEST_F(LayoutTest, RowFromTwoColumns) {
   EXPECT_EQ(CountTextLinesIn(250, kBaseline - 60, 1750, kBaseline + 60), 1);
 }

+// Tests that a small word between the two lines of a very large title is
+// found. Its letters are shared out as diacritics among the letters of the
+// title, so it gets a text line and a block of its own.
+TEST_F(LayoutTest, SmallWordInLargeTitle) {
+  REQUIRE_TRAINEDDATA(TESSDATA_DIR, "eng");
+  Rect small_word;
+  Pix *page = MakeTitlePage(&small_word);
+  AnalysePage(page);
+  ExpectSmallWordBlock(small_word, 2, 2);
+  // The lines of the text are still there.
+  EXPECT_EQ(CountTextLinesIn(250, 960, 1750, 2330), 22);
+}
+
+// Tests that the block of the small word is where the word is on a skewed
+// page. The layout analysis makes the blocks from deskewed boxes and turns
+// them back at the end.
+TEST_F(LayoutTest, SmallWordInSkewedLargeTitle) {
+  REQUIRE_TRAINEDDATA(TESSDATA_DIR, "eng");
+  const float kRadiansPerDegree = 0.0174533f;
+  for (float degrees : {1.0f, -1.0f}) {
+    SCOPED_TRACE(degrees);
+    Rect small_word;
+    Pix *page = MakeTitlePage(&small_word);
+    Pix *skewed = pixRotate(page, degrees * kRadiansPerDegree,
+                            L_ROTATE_AREA_MAP, L_BRING_IN_WHITE, 0, 0);
+    pixDestroy(&page);
+    ASSERT_NE(skewed, nullptr);
+    AnalysePage(skewed);
+    // The skew moves the word by some pixels.
+    ExpectSmallWordBlock(small_word, 30, 5);
+  }
+}
+
+// Tests that the block of the small word is where the word is on a page
+// which is read from right to left, where the layout analysis works with
+// reflected boxes.
+TEST_F(LayoutTest, SmallWordInLargeTitleRightToLeft) {
+  REQUIRE_TRAINEDDATA(TESSDATA_DIR, "heb");
+  Rect small_word;
+  Pix *page = MakeTitlePage(&small_word);
+  AnalysePage(page, 0, tesseract::PSM_AUTO, "heb");
+  ExpectSmallWordBlock(small_word, 2, 2);
+}
+
+// Tests that the block of the small word is where the word is on a page
+// which is upside down, and that it comes after the block of the title.
+TEST_F(LayoutTest, SmallWordInLargeTitleUpsideDown) {
+  REQUIRE_TRAINEDDATA(TESSDATA_DIR, "eng");
+  REQUIRE_TRAINEDDATA(TESSDATA_DIR, "osd");
+  Rect small_word;
+  Pix *page = MakeTitlePage(&small_word);
+  Pix *turned = pixRotate180(nullptr, page);
+  pixDestroy(&page);
+  AnalysePage(turned, 0, tesseract::PSM_AUTO_OSD);
+  const Rect turned_word = {kPageWidth - small_word.right,
+                            kPageHeight - small_word.bottom,
+                            kPageWidth - small_word.left,
+                            kPageHeight - small_word.top};
+  ExpectSmallWordBlock(turned_word, 2, 2);
+  // The first block is the title, which is much wider than the small word.
+  page_it_->Begin();
+  int left, top, right, bottom;
+  ASSERT_TRUE(page_it_->BoundingBox(tesseract::RIL_BLOCK, &left, &top, &right,
+                                    &bottom));
+  EXPECT_GT(right - left, 1000);
+}
+
 } // namespace tesseract