All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
colfind.h
Go to the documentation of this file.
1 // File: colfind.h
3 // Description: Class to find columns in the grid of BLOBNBOXes.
4 // Author: Ray Smith
5 // Created: Thu Feb 21 14:04:01 PST 2008
6 //
7 // (C) Copyright 2008, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 
20 #ifndef TESSERACT_TEXTORD_COLFIND_H__
21 #define TESSERACT_TEXTORD_COLFIND_H__
22 
23 #include "tabfind.h"
24 #include "imagefind.h"
25 #include "colpartitiongrid.h"
26 #include "colpartitionset.h"
27 #include "ocrblock.h"
28 #include "textlineprojection.h"
29 
30 class BLOCK_LIST;
31 struct Boxa;
32 struct Pixa;
33 class DENORM;
34 class ScrollView;
35 class STATS;
36 class TO_BLOCK;
37 
38 namespace tesseract {
39 
40 extern BOOL_VAR_H(textord_tabfind_find_tables, false, "run table detection");
41 
42 class ColPartitionSet;
43 class ColPartitionSet_LIST;
44 class ColSegment_LIST;
45 class ColumnGroup_LIST;
46 class LineSpacing;
47 class StrokeWidth;
48 class TempColumn_LIST;
49 class EquationDetectBase;
50 
51 // The ColumnFinder class finds columns in the grid.
52 class ColumnFinder : public TabFind {
53  public:
54  // Gridsize is an estimate of the text size in the image. A suitable value
55  // is in TO_BLOCK::line_size after find_components has been used to make
56  // the blobs.
57  // bleft and tright are the bounds of the image (rectangle) being processed.
58  // vlines is a (possibly empty) list of TabVector and vertical_x and y are
59  // the sum logical vertical vector produced by LineFinder::FindVerticalLines.
60  // If cjk_script is true, then broken CJK characters are fixed during
61  // layout analysis to assist in detecting horizontal vs vertically written
62  // textlines.
63  ColumnFinder(int gridsize, const ICOORD& bleft, const ICOORD& tright,
64  int resolution, bool cjk_script, double aligned_gap_fraction,
65  TabVector_LIST* vlines, TabVector_LIST* hlines,
66  int vertical_x, int vertical_y);
67  virtual ~ColumnFinder();
68 
69  // Accessors for testing
70  const DENORM* denorm() const {
71  return denorm_;
72  }
73  const TextlineProjection* projection() const {
74  return &projection_;
75  }
76  void set_cjk_script(bool is_cjk) {
77  cjk_script_ = is_cjk;
78  }
79 
80  // ======================================================================
81  // The main function of ColumnFinder is broken into pieces to facilitate
82  // optional insertion of orientation and script detection in an efficient
83  // way. The calling sequence IS MANDATORY however, whether or not
84  // OSD is being used:
85  // 1. Construction.
86  // 2. SetupAndFilterNoise.
87  // 3. IsVerticallyAlignedText.
88  // 4. CorrectOrientation.
89  // 5. FindBlocks.
90  // 6. Destruction. Use of a single column finder for multiple images does not
91  // make sense.
92  // Throughout these steps, the ColPartitions are owned by part_grid_, which
93  // means that that it must be kept correct. Exception: big_parts_ owns its
94  // own ColPartitions.
95  // The BLOBNBOXes are owned by the input TO_BLOCK for the whole time, except
96  // for a phase in FindBlocks before TransformToBlocks, when they become
97  // owned by the ColPartitions. The owner() ColPartition of a BLOBNBOX
98  // indicates more of a betrothal for the majority of layout analysis, ie
99  // which ColPartition will take ownership when the blobs are release from
100  // the input TO_BLOCK. Exception: image_bblobs_ owns the fake blobs that
101  // are part of the image regions, as they are not on any TO_BLOCK list.
102  // TODO(rays) break up column finder further into smaller classes, as
103  // there is a lot more to it than column finding now.
104  // ======================================================================
105 
106  // Performs initial processing on the blobs in the input_block:
107  // Setup the part_grid, stroke_width_, nontext_map_.
108  // Obvious noise blobs are filtered out and used to mark the nontext_map_.
109  // Initial stroke-width analysis is used to get local text alignment
110  // direction, so the textline projection_ map can be setup.
111  // On return, IsVerticallyAlignedText may be called (now optionally) to
112  // determine the gross textline alignment of the page.
113  void SetupAndFilterNoise(PageSegMode pageseg_mode, Pix* photo_mask_pix,
114  TO_BLOCK* input_block);
115 
116  // Tests for vertical alignment of text (returning true if so), and generates
117  // a list of blobs (in osd_blobs) for orientation and script detection.
118  // block is the single block for the whole page or rectangle to be OCRed.
119  // Note that the vertical alignment may be due to text whose writing direction
120  // is vertical, like say Japanese, or due to text whose writing direction is
121  // horizontal but whose text appears vertically aligned because the image is
122  // not the right way up.
123  // find_vertical_text_ratio should be textord_tabfind_vertical_text_ratio.
124  bool IsVerticallyAlignedText(double find_vertical_text_ratio,
125  TO_BLOCK* block, BLOBNBOX_CLIST* osd_blobs);
126 
127  // Rotates the blobs and the TabVectors so that the gross writing direction
128  // (text lines) are horizontal and lines are read down the page.
129  // Applied rotation stored in rotation_.
130  // A second rotation is calculated for application during recognition to
131  // make the rotated blobs upright for recognition.
132  // Subsequent rotation stored in text_rotation_.
133  //
134  // Arguments:
135  // vertical_text_lines is true if the text lines are vertical.
136  // recognition_rotation [0..3] is the number of anti-clockwise 90 degree
137  // rotations from osd required for the text to be upright and readable.
138  void CorrectOrientation(TO_BLOCK* block, bool vertical_text_lines,
139  int recognition_rotation);
140 
141  // Finds blocks of text, image, rule line, table etc, returning them in the
142  // blocks and to_blocks
143  // (Each TO_BLOCK points to the basic BLOCK and adds more information.)
144  // Image blocks are generated by a combination of photo_mask_pix (which may
145  // NOT be NULL) and the rejected text found during preliminary textline
146  // finding.
147  // The input_block is the result of a call to find_components, and contains
148  // the blobs found in the image or rectangle to be OCRed. These blobs will be
149  // removed and placed in the output blocks, while unused ones will be deleted.
150  // If single_column is true, the input is treated as single column, but
151  // it is still divided into blocks of equal line spacing/text size.
152  // scaled_color is scaled down by scaled_factor from the input color image,
153  // and may be NULL if the input was not color.
154  // grey_pix is optional, but if present must match the photo_mask_pix in size,
155  // and must be a *real* grey image instead of binary_pix * 255.
156  // thresholds_pix is expected to be present iff grey_pix is present and
157  // can be an integer factor reduction of the grey_pix. It represents the
158  // thresholds that were used to create the binary_pix from the grey_pix.
159  // Small blobs that confuse the segmentation into lines are placed into
160  // diacritic_blobs, with the intention that they be put into the most
161  // appropriate word after the rest of layout analysis.
162  // Returns -1 if the user hits the 'd' key in the blocks window while running
163  // in debug mode, which requests a retry with more debug info.
164  int FindBlocks(PageSegMode pageseg_mode, Pix* scaled_color, int scaled_factor,
165  TO_BLOCK* block, Pix* photo_mask_pix, Pix* thresholds_pix,
166  Pix* grey_pix, BLOCK_LIST* blocks,
167  BLOBNBOX_LIST* diacritic_blobs, TO_BLOCK_LIST* to_blocks);
168 
169  // Get the rotation required to deskew, and its inverse rotation.
170  void GetDeskewVectors(FCOORD* deskew, FCOORD* reskew);
171 
172  // Set the equation detection pointer.
174 
175  private:
176  // Displays the blob and block bounding boxes in a window called Blocks.
177  void DisplayBlocks(BLOCK_LIST* blocks);
178  // Displays the column edges at each grid y coordinate defined by
179  // best_columns_.
180  void DisplayColumnBounds(PartSetVector* sets);
181 
183 
184  // Sets up column_sets_ (the determined column layout at each horizontal
185  // slice). Returns false if the page is empty.
186  bool MakeColumns(bool single_column);
187  // Attempt to improve the column_candidates by expanding the columns
188  // and adding new partitions from the partition sets in src_sets.
189  // Src_sets may be equal to column_candidates, in which case it will
190  // use them as a source to improve themselves.
191  void ImproveColumnCandidates(PartSetVector* src_sets,
192  PartSetVector* column_sets);
193  // Prints debug information on the column candidates.
194  void PrintColumnCandidates(const char* title);
195  // Finds the optimal set of columns that cover the entire image with as
196  // few changes in column partition as possible.
197  // Returns true if any part of the page is multi-column.
198  bool AssignColumns(const PartSetVector& part_sets);
199  // Finds the biggest range in part_sets_ that has no assigned column, but
200  // column assignment is possible.
201  bool BiggestUnassignedRange(int set_count, const bool* any_columns_possible,
202  int* start, int* end);
203  // Finds the modal compatible column_set_ index within the given range.
204  int RangeModalColumnSet(int** column_set_costs, const int* assigned_costs,
205  int start, int end);
206  // Given that there are many column_set_id compatible columns in the range,
207  // shrinks the range to the longest contiguous run of compatibility, allowing
208  // gaps where no columns are possible, but not where competing columns are
209  // possible.
210  void ShrinkRangeToLongestRun(int** column_set_costs,
211  const int* assigned_costs,
212  const bool* any_columns_possible,
213  int column_set_id,
214  int* best_start, int* best_end);
215  // Moves start in the direction of step, upto, but not including end while
216  // the only incompatible regions are no more than kMaxIncompatibleColumnCount
217  // in size, and the compatible regions beyond are bigger.
218  void ExtendRangePastSmallGaps(int** column_set_costs,
219  const int* assigned_costs,
220  const bool* any_columns_possible,
221  int column_set_id,
222  int step, int end, int* start);
223  // Assigns the given column_set_id to the part_sets_ in the given range.
224  void AssignColumnToRange(int column_set_id, int start, int end,
225  int** column_set_costs, int* assigned_costs);
226 
227  // Computes the mean_column_gap_.
228  void ComputeMeanColumnGap(bool any_multi_column);
229 
232 
233  // Hoovers up all un-owned blobs and deletes them.
234  // The rest get released from the block so the ColPartitions can pass
235  // ownership to the output blocks.
236  void ReleaseBlobsAndCleanupUnused(TO_BLOCK* block);
237  // Splits partitions that cross columns where they have nothing in the gap.
238  void GridSplitPartitions();
239  // Merges partitions where there is vertical overlap, within a single column,
240  // and the horizontal gap is small enough.
241  void GridMergePartitions();
242  // Inserts remaining noise blobs into the most applicable partition if any.
243  // If there is no applicable partition, then the blobs are deleted.
244  void InsertRemainingNoise(TO_BLOCK* block);
245  // Remove partitions that come from horizontal lines that look like
246  // underlines, but are not part of a table.
247  void GridRemoveUnderlinePartitions();
248  // Add horizontal line separators as partitions.
249  void GridInsertHLinePartitions();
250  // Add vertical line separators as partitions.
251  void GridInsertVLinePartitions();
252  // For every ColPartition in the grid, sets its type based on position
253  // in the columns.
254  void SetPartitionTypes();
255  // Only images remain with multiple types in a run of partners.
256  // Sets the type of all in the group to the maximum of the group.
257  void SmoothPartnerRuns();
258 
260 
261  // Helper functions for TransformToBlocks.
262  // Add the part to the temp list in the correct order.
263  void AddToTempPartList(ColPartition* part, ColPartition_CLIST* temp_list);
264  // Add everything from the temp list to the work_set assuming correct order.
265  void EmptyTempPartList(ColPartition_CLIST* temp_list,
266  WorkingPartSet_LIST* work_set);
267 
268  // Transform the grid of partitions to the output blocks.
269  void TransformToBlocks(BLOCK_LIST* blocks, TO_BLOCK_LIST* to_blocks);
270 
271  // Reflect the blob boxes (but not the outlines) in the y-axis so that
272  // the blocks get created in the correct RTL order. Rotates the blobs
273  // in the input_block and the bblobs list.
274  // The reflection is undone in RotateAndReskewBlocks by
275  // reflecting the blocks themselves, and then recomputing the blob bounding
276  // boxes.
277  void ReflectForRtl(TO_BLOCK* input_block, BLOBNBOX_LIST* bblobs);
278 
279  // Undo the deskew that was done in FindTabVectors, as recognition is done
280  // without correcting blobs or blob outlines for skew.
281  // Reskew the completed blocks to put them back to the original rotated coords
282  // that were created by CorrectOrientation.
283  // If the input_is_rtl, then reflect the blocks in the y-axis to undo the
284  // reflection that was done before FindTabVectors.
285  // Blocks that were identified as vertical text (relative to the rotated
286  // coordinates) are further rotated so the text lines are horizontal.
287  // blob polygonal outlines are rotated to match the position of the blocks
288  // that they are in, and their bounding boxes are recalculated to be accurate.
289  // Record appropriate inverse transformations and required
290  // classifier transformation in the blocks.
291  void RotateAndReskewBlocks(bool input_is_rtl, TO_BLOCK_LIST* to_blocks);
292 
293  // Computes the rotations for the block (to make textlines horizontal) and
294  // for the blobs (for classification) and sets the appropriate members
295  // of the given block.
296  // Returns the rotation that needs to be applied to the blobs to make
297  // them sit in the rotated block.
298  FCOORD ComputeBlockAndClassifyRotation(BLOCK* block);
299 
300  // If true then the page language is cjk, so it is safe to perform
301  // FixBrokenCJK.
302  bool cjk_script_;
303  // The minimum gutter width to apply for finding columns.
304  // Modified when vertical text is detected to prevent detection of
305  // vertical text lines as columns.
306  int min_gutter_width_;
307  // The mean gap between columns over the page.
308  int mean_column_gap_;
309  // Config param saved at construction time. Modifies min_gutter_width_ with
310  // vertical text to prevent detection of vertical text as columns.
311  double tabfind_aligned_gap_fraction_;
312  // The rotation vector needed to convert original coords to deskewed.
313  FCOORD deskew_;
314  // The rotation vector needed to convert deskewed back to original coords.
315  FCOORD reskew_;
316  // The rotation vector used to rotate vertically oriented pages.
317  FCOORD rotation_;
318  // The rotation vector needed to convert the rotated back to original coords.
319  FCOORD rerotate_;
320  // The additional rotation vector needed to rotate text for recognition.
321  FCOORD text_rotation_;
322  // The column_sets_ contain the ordered candidate ColPartitionSets that
323  // define the possible divisions of the page into columns.
324  PartSetVector column_sets_;
325  // A simple array of pointers to the best assigned column division at
326  // each grid y coordinate.
327  ColPartitionSet** best_columns_;
328  // The grid used for creating initial partitions with strokewidth.
329  StrokeWidth* stroke_width_;
330  // The grid used to hold ColPartitions after the columns have been determined.
331  ColPartitionGrid part_grid_;
332  // List of ColPartitions that are no longer needed after they have been
333  // turned into regions, but are kept around because they are referenced
334  // by the part_grid_.
335  ColPartition_LIST good_parts_;
336  // List of ColPartitions that are big and might be dropcap or vertically
337  // joined.
338  ColPartition_LIST big_parts_;
339  // List of ColPartitions that have been declared noise.
340  ColPartition_LIST noise_parts_;
341  // The fake blobs that are made from the images.
342  BLOBNBOX_LIST image_bblobs_;
343  // Horizontal line separators.
344  TabVector_LIST horizontal_lines_;
345  // Image map of photo/noise areas on the page.
346  Pix* nontext_map_;
347  // Textline projection map.
348  TextlineProjection projection_;
349  // Sequence of DENORMS that indicate how to get back to the original image
350  // coordinate space. The destructor must delete all the DENORMs in the chain.
351  DENORM* denorm_;
352 
353  // Various debug windows that automatically go away on completion.
354  ScrollView* input_blobs_win_;
355 
356  // The equation region detector pointer. Note: This pointer is passed in by
357  // member function SetEquationDetect, and releasing it is NOT owned by this
358  // class.
359  EquationDetectBase* equation_detect_;
360 
361  // Allow a subsequent instance to reuse the blocks window.
362  // Not thread-safe, but multiple threads shouldn't be using windows anyway.
363  static ScrollView* blocks_win_;
364 };
365 
366 } // namespace tesseract.
367 
368 #endif // TESSERACT_TEXTORD_COLFIND_H__
bool textord_tabfind_find_tables
Definition: colfind.cpp:74
ColumnFinder(int gridsize, const ICOORD &bleft, const ICOORD &tright, int resolution, bool cjk_script, double aligned_gap_fraction, TabVector_LIST *vlines, TabVector_LIST *hlines, int vertical_x, int vertical_y)
Definition: colfind.cpp:84
const DENORM * denorm() const
Definition: colfind.h:70
Definition: statistc.h:33
void SetupAndFilterNoise(PageSegMode pageseg_mode, Pix *photo_mask_pix, TO_BLOCK *input_block)
Definition: colfind.cpp:153
int FindBlocks(PageSegMode pageseg_mode, Pix *scaled_color, int scaled_factor, TO_BLOCK *block, Pix *photo_mask_pix, Pix *thresholds_pix, Pix *grey_pix, BLOCK_LIST *blocks, BLOBNBOX_LIST *diacritic_blobs, TO_BLOCK_LIST *to_blocks)
Definition: colfind.cpp:297
bool IsVerticallyAlignedText(double find_vertical_text_ratio, TO_BLOCK *block, BLOBNBOX_CLIST *osd_blobs)
Definition: colfind.cpp:191
void SetEquationDetect(EquationDetectBase *detect)
Definition: colfind.cpp:515
Definition: ocrblock.h:30
int gridsize() const
Definition: bbgrid.h:63
void set_cjk_script(bool is_cjk)
Definition: colfind.h:76
void CorrectOrientation(TO_BLOCK *block, bool vertical_text_lines, int recognition_rotation)
Definition: colfind.cpp:209
const ICOORD & bleft() const
Definition: bbgrid.h:72
integer coordinate
Definition: points.h:30
const ICOORD & tright() const
Definition: bbgrid.h:75
const TextlineProjection * projection() const
Definition: colfind.h:73
#define BOOL_VAR_H(name, val, comment)
Definition: params.h:268
Definition: points.h:189
void GetDeskewVectors(FCOORD *deskew, FCOORD *reskew)
Definition: colfind.cpp:509