All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
devanagari_processing.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: devanagari_processing.cpp
3  * Description: Methods to process images containing devanagari symbols,
4  * prior to classification.
5  * Author: Shobhit Saxena
6  * Created: Mon Nov 17 20:26:01 IST 2008
7  *
8  * (C) Copyright 2008, Google Inc.
9  ** Licensed under the Apache License, Version 2.0 (the "License");
10  ** you may not use this file except in compliance with the License.
11  ** You may obtain a copy of the License at
12  ** http://www.apache.org/licenses/LICENSE-2.0
13  ** Unless required by applicable law or agreed to in writing, software
14  ** distributed under the License is distributed on an "AS IS" BASIS,
15  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  ** See the License for the specific language governing permissions and
17  ** limitations under the License.
18  *
19  **********************************************************************/
20 
21 #ifdef HAVE_CONFIG_H
22 #include "config_auto.h"
23 #endif
24 
25 #include "devanagari_processing.h"
26 #include "allheaders.h"
27 #include "tordmain.h"
28 #include "statistc.h"
29 
30 // Flags controlling the debugging information for shiro-rekha splitting
31 // strategies.
33  "Debug level for split shiro-rekha process.");
34 
36  "Whether to create a debug image for split shiro-rekha process.");
37 
38 namespace tesseract {
39 
41  orig_pix_ = NULL;
42  segmentation_block_list_ = NULL;
43  splitted_image_ = NULL;
44  global_xheight_ = kUnspecifiedXheight;
45  perform_close_ = false;
46  debug_image_ = NULL;
47  pageseg_split_strategy_ = NO_SPLIT;
48  ocr_split_strategy_ = NO_SPLIT;
49 }
50 
52  Clear();
53 }
54 
56  pixDestroy(&orig_pix_);
57  pixDestroy(&splitted_image_);
58  pageseg_split_strategy_ = NO_SPLIT;
59  ocr_split_strategy_ = NO_SPLIT;
60  pixDestroy(&debug_image_);
61  segmentation_block_list_ = NULL;
62  global_xheight_ = kUnspecifiedXheight;
63  perform_close_ = false;
64 }
65 
66 // This method dumps a debug image to the specified location.
68  pixWrite(filename, debug_image_, IFF_PNG);
69 }
70 
71 // On setting the input image, a clone of it is owned by this class.
73  if (orig_pix_) {
74  pixDestroy(&orig_pix_);
75  }
76  orig_pix_ = pixClone(pix);
77 }
78 
79 // Top-level method to perform splitting based on current settings.
80 // Returns true if a split was actually performed.
81 // split_for_pageseg should be true if the splitting is being done prior to
82 // page segmentation. This mode uses the flag
83 // pageseg_devanagari_split_strategy to determine the splitting strategy.
84 bool ShiroRekhaSplitter::Split(bool split_for_pageseg) {
85  SplitStrategy split_strategy = split_for_pageseg ? pageseg_split_strategy_ :
86  ocr_split_strategy_;
87  if (split_strategy == NO_SPLIT) {
88  return false; // Nothing to do.
89  }
90  ASSERT_HOST(split_strategy == MINIMAL_SPLIT ||
91  split_strategy == MAXIMAL_SPLIT);
92  ASSERT_HOST(orig_pix_);
94  tprintf("Splitting shiro-rekha ...\n");
95  tprintf("Split strategy = %s\n",
96  split_strategy == MINIMAL_SPLIT ? "Minimal" : "Maximal");
97  tprintf("Initial pageseg available = %s\n",
98  segmentation_block_list_ ? "yes" : "no");
99  }
100  // Create a copy of original image to store the splitting output.
101  pixDestroy(&splitted_image_);
102  splitted_image_ = pixCopy(NULL, orig_pix_);
103 
104  // Initialize debug image if required.
106  pixDestroy(&debug_image_);
107  debug_image_ = pixConvertTo32(orig_pix_);
108  }
109 
110  // Determine all connected components in the input image. A close operation
111  // may be required prior to this, depending on the current settings.
112  Pix* pix_for_ccs = pixClone(orig_pix_);
113  if (perform_close_ && global_xheight_ != kUnspecifiedXheight &&
114  !segmentation_block_list_) {
115  if (devanagari_split_debuglevel > 0) {
116  tprintf("Performing a global close operation..\n");
117  }
118  // A global measure is available for xheight, but no local information
119  // exists.
120  pixDestroy(&pix_for_ccs);
121  pix_for_ccs = pixCopy(NULL, orig_pix_);
122  PerformClose(pix_for_ccs, global_xheight_);
123  }
124  Pixa* ccs;
125  Boxa* tmp_boxa = pixConnComp(pix_for_ccs, &ccs, 8);
126  boxaDestroy(&tmp_boxa);
127  pixDestroy(&pix_for_ccs);
128 
129  // Iterate over all connected components. Get their bounding boxes and clip
130  // out the image regions corresponding to these boxes from the original image.
131  // Conditionally run splitting on each of them.
132  Boxa* regions_to_clear = boxaCreate(0);
133  for (int i = 0; i < pixaGetCount(ccs); ++i) {
134  Box* box = ccs->boxa->box[i];
135  Pix* word_pix = pixClipRectangle(orig_pix_, box, NULL);
136  ASSERT_HOST(word_pix);
137  int xheight = GetXheightForCC(box);
138  if (xheight == kUnspecifiedXheight && segmentation_block_list_ &&
140  pixRenderBoxArb(debug_image_, box, 1, 255, 0, 0);
141  }
142  // If some xheight measure is available, attempt to pre-eliminate small
143  // blobs from the shiro-rekha process. This is primarily to save the CCs
144  // corresponding to punctuation marks/small dots etc which are part of
145  // larger graphemes.
146  if (xheight == kUnspecifiedXheight ||
147  (box->w > xheight / 3 && box->h > xheight / 2)) {
148  SplitWordShiroRekha(split_strategy, word_pix, xheight,
149  box->x, box->y, regions_to_clear);
150  } else if (devanagari_split_debuglevel > 0) {
151  tprintf("CC dropped from splitting: %d,%d (%d, %d)\n",
152  box->x, box->y, box->w, box->h);
153  }
154  pixDestroy(&word_pix);
155  }
156  // Actually clear the boxes now.
157  for (int i = 0; i < boxaGetCount(regions_to_clear); ++i) {
158  Box* box = boxaGetBox(regions_to_clear, i, L_CLONE);
159  pixClearInRect(splitted_image_, box);
160  boxDestroy(&box);
161  }
162  boxaDestroy(&regions_to_clear);
163  pixaDestroy(&ccs);
165  DumpDebugImage(split_for_pageseg ? "pageseg_split_debug.png" :
166  "ocr_split_debug.png");
167  }
168  return true;
169 }
170 
171 // Method to perform a close operation on the input image. The xheight
172 // estimate decides the size of sel used.
173 void ShiroRekhaSplitter::PerformClose(Pix* pix, int xheight_estimate) {
174  pixCloseBrick(pix, pix, xheight_estimate / 8, xheight_estimate / 3);
175 }
176 
177 // This method resolves the cc bbox to a particular row and returns the row's
178 // xheight.
179 int ShiroRekhaSplitter::GetXheightForCC(Box* cc_bbox) {
180  if (!segmentation_block_list_) {
181  return global_xheight_;
182  }
183  // Compute the box coordinates in Tesseract's coordinate system.
184  TBOX bbox(cc_bbox->x,
185  pixGetHeight(orig_pix_) - cc_bbox->y - cc_bbox->h - 1,
186  cc_bbox->x + cc_bbox->w,
187  pixGetHeight(orig_pix_) - cc_bbox->y - 1);
188  // Iterate over all blocks.
189  BLOCK_IT block_it(segmentation_block_list_);
190  for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
191  BLOCK* block = block_it.data();
192  // Iterate over all rows in the block.
193  ROW_IT row_it(block->row_list());
194  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
195  ROW* row = row_it.data();
196  if (!row->bounding_box().major_overlap(bbox)) {
197  continue;
198  }
199  // Row could be skewed, warped, etc. Use the position of the box to
200  // determine the baseline position of the row for that x-coordinate.
201  // Create a square TBOX whose baseline's mid-point lies at this point
202  // and side is row's xheight. Take the overlap of this box with the input
203  // box and check if it is a 'major overlap'. If so, this box lies in this
204  // row. In that case, return the xheight for this row.
205  float box_middle = 0.5 * (bbox.left() + bbox.right());
206  int baseline = static_cast<int>(row->base_line(box_middle) + 0.5);
207  TBOX test_box(box_middle - row->x_height() / 2,
208  baseline,
209  box_middle + row->x_height() / 2,
210  static_cast<int>(baseline + row->x_height()));
211  // Compute overlap. If it is is a major overlap, this is the right row.
212  if (bbox.major_overlap(test_box)) {
213  return row->x_height();
214  }
215  }
216  }
217  // No row found for this bbox.
218  return kUnspecifiedXheight;
219 }
220 
221 // Returns a list of regions (boxes) which should be cleared in the original
222 // image so as to perform shiro-rekha splitting. Pix is assumed to carry one
223 // (or less) word only. Xheight measure could be the global estimate, the row
224 // estimate, or unspecified. If unspecified, over splitting may occur, since a
225 // conservative estimate of stroke width along with an associated multiplier
226 // is used in its place. It is advisable to have a specified xheight when
227 // splitting for classification/training.
228 // A vertical projection histogram of all the on-pixels in the input pix is
229 // computed. The maxima of this histogram is regarded as an approximate location
230 // of the shiro-rekha. By descending on the maxima's peak on both sides,
231 // stroke width of shiro-rekha is estimated.
232 // A horizontal projection histogram is computed for a sub-image of the input
233 // image, which extends from just below the shiro-rekha down to a certain
234 // leeway. The leeway depends on the input xheight, if provided, else a
235 // conservative multiplier on approximate stroke width is used (which may lead
236 // to over-splitting).
237 void ShiroRekhaSplitter::SplitWordShiroRekha(SplitStrategy split_strategy,
238  Pix* pix,
239  int xheight,
240  int word_left,
241  int word_top,
242  Boxa* regions_to_clear) {
243  if (split_strategy == NO_SPLIT) {
244  return;
245  }
246  int width = pixGetWidth(pix);
247  int height = pixGetHeight(pix);
248  // Statistically determine the yextents of the shiro-rekha.
249  int shirorekha_top, shirorekha_bottom, shirorekha_ylevel;
250  GetShiroRekhaYExtents(pix, &shirorekha_top, &shirorekha_bottom,
251  &shirorekha_ylevel);
252  // Since the shiro rekha is also a stroke, its width is equal to the stroke
253  // width.
254  int stroke_width = shirorekha_bottom - shirorekha_top + 1;
255 
256  // Some safeguards to protect CCs we do not want to be split.
257  // These are particularly useful when the word wasn't eliminated earlier
258  // because xheight information was unavailable.
259  if (shirorekha_ylevel > height / 2) {
260  // Shirorekha shouldn't be in the bottom half of the word.
261  if (devanagari_split_debuglevel > 0) {
262  tprintf("Skipping splitting CC at (%d, %d): shirorekha in lower half..\n",
263  word_left, word_top);
264  }
265  return;
266  }
267  if (stroke_width > height / 3) {
268  // Even the boldest of fonts shouldn't do this.
269  if (devanagari_split_debuglevel > 0) {
270  tprintf("Skipping splitting CC at (%d, %d): stroke width too huge..\n",
271  word_left, word_top);
272  }
273  return;
274  }
275 
276  // Clear the ascender and descender regions of the word.
277  // Obtain a vertical projection histogram for the resulting image.
278  Box* box_to_clear = boxCreate(0, shirorekha_top - stroke_width / 3,
279  width, 5 * stroke_width / 3);
280  Pix* word_in_xheight = pixCopy(NULL, pix);
281  pixClearInRect(word_in_xheight, box_to_clear);
282  // Also clear any pixels which are below shirorekha_bottom + some leeway.
283  // The leeway is set to xheight if the information is available, else it is a
284  // multiplier applied to the stroke width.
285  int leeway_to_keep = stroke_width * 3;
286  if (xheight != kUnspecifiedXheight) {
287  // This is because the xheight-region typically includes the shiro-rekha
288  // inside it, i.e., the top of the xheight range corresponds to the top of
289  // shiro-rekha.
290  leeway_to_keep = xheight - stroke_width;
291  }
292  box_to_clear->y = shirorekha_bottom + leeway_to_keep;
293  box_to_clear->h = height - box_to_clear->y;
294  pixClearInRect(word_in_xheight, box_to_clear);
295  boxDestroy(&box_to_clear);
296 
297  PixelHistogram vert_hist;
298  vert_hist.ConstructVerticalCountHist(word_in_xheight);
299  pixDestroy(&word_in_xheight);
300 
301  // If the number of black pixel in any column of the image is less than a
302  // fraction of the stroke width, treat it as noise / a stray mark. Perform
303  // these changes inside the vert_hist data itself, as that is used later on as
304  // a bit vector for the final split decision at every column.
305  for (int i = 0; i < width; ++i) {
306  if (vert_hist.hist()[i] <= stroke_width / 4)
307  vert_hist.hist()[i] = 0;
308  else
309  vert_hist.hist()[i] = 1;
310  }
311  // In order to split the line at any point, we make sure that the width of the
312  // gap is atleast half the stroke width.
313  int i = 0;
314  int cur_component_width = 0;
315  while (i < width) {
316  if (!vert_hist.hist()[i]) {
317  int j = 0;
318  while (i + j < width && !vert_hist.hist()[i+j])
319  ++j;
320  if (j >= stroke_width / 2 && cur_component_width >= stroke_width / 2) {
321  // Perform a shiro-rekha split. The intervening region lies from i to
322  // i+j-1.
323  // A minimal single-pixel split makes the estimation of intra- and
324  // inter-word spacing easier during page layout analysis,
325  // whereas a maximal split may be needed for OCR, depending on
326  // how the engine was trained.
327  bool minimal_split = (split_strategy == MINIMAL_SPLIT);
328  int split_width = minimal_split ? 1 : j;
329  int split_left = minimal_split ? i + (j / 2) - (split_width / 2) : i;
330  if (!minimal_split || (i != 0 && i + j != width)) {
331  Box* box_to_clear =
332  boxCreate(word_left + split_left,
333  word_top + shirorekha_top - stroke_width / 3,
334  split_width,
335  5 * stroke_width / 3);
336  if (box_to_clear) {
337  boxaAddBox(regions_to_clear, box_to_clear, L_CLONE);
338  // Mark this in the debug image if needed.
340  pixRenderBoxArb(debug_image_, box_to_clear, 1, 128, 255, 128);
341  }
342  boxDestroy(&box_to_clear);
343  cur_component_width = 0;
344  }
345  }
346  }
347  i += j;
348  } else {
349  ++i;
350  ++cur_component_width;
351  }
352  }
353 }
354 
355 // Refreshes the words in the segmentation block list by using blobs in the
356 // input block list.
357 // The segmentation block list must be set.
359  C_BLOB_LIST* new_blobs) {
360  // The segmentation block list must have been specified.
361  ASSERT_HOST(segmentation_block_list_);
362  if (devanagari_split_debuglevel > 0) {
363  tprintf("Before refreshing blobs:\n");
364  PrintSegmentationStats(segmentation_block_list_);
365  tprintf("New Blobs found: %d\n", new_blobs->length());
366  }
367 
368  C_BLOB_LIST not_found_blobs;
369  RefreshWordBlobsFromNewBlobs(segmentation_block_list_,
370  new_blobs,
371  ((devanagari_split_debugimage && debug_image_) ?
372  &not_found_blobs : NULL));
373 
374  if (devanagari_split_debuglevel > 0) {
375  tprintf("After refreshing blobs:\n");
376  PrintSegmentationStats(segmentation_block_list_);
377  }
378  if (devanagari_split_debugimage && debug_image_) {
379  // Plot out the original blobs for which no match was found in the new
380  // all_blobs list.
381  C_BLOB_IT not_found_it(&not_found_blobs);
382  for (not_found_it.mark_cycle_pt(); !not_found_it.cycled_list();
383  not_found_it.forward()) {
384  C_BLOB* not_found = not_found_it.data();
385  TBOX not_found_box = not_found->bounding_box();
386  Box* box_to_plot = GetBoxForTBOX(not_found_box);
387  pixRenderBoxArb(debug_image_, box_to_plot, 1, 255, 0, 255);
388  boxDestroy(&box_to_plot);
389  }
390 
391  // Plot out the blobs unused from all blobs.
392  C_BLOB_IT all_blobs_it(new_blobs);
393  for (all_blobs_it.mark_cycle_pt(); !all_blobs_it.cycled_list();
394  all_blobs_it.forward()) {
395  C_BLOB* a_blob = all_blobs_it.data();
396  Box* box_to_plot = GetBoxForTBOX(a_blob->bounding_box());
397  pixRenderBoxArb(debug_image_, box_to_plot, 3, 0, 127, 0);
398  boxDestroy(&box_to_plot);
399  }
400  }
401 }
402 
403 // Returns a new box object for the corresponding TBOX, based on the original
404 // image's coordinate system.
405 Box* ShiroRekhaSplitter::GetBoxForTBOX(const TBOX& tbox) const {
406  return boxCreate(tbox.left(), pixGetHeight(orig_pix_) - tbox.top() - 1,
407  tbox.width(), tbox.height());
408 }
409 
410 // This method returns the computed mode-height of blobs in the pix.
411 // It also prunes very small blobs from calculation.
413  Boxa* boxa = pixConnComp(pix, NULL, 8);
414  STATS heights(0, pixGetHeight(pix));
415  heights.clear();
416  for (int i = 0; i < boxaGetCount(boxa); ++i) {
417  Box* box = boxaGetBox(boxa, i, L_CLONE);
418  if (box->h >= 3 || box->w >= 3) {
419  heights.add(box->h, 1);
420  }
421  boxDestroy(&box);
422  }
423  boxaDestroy(&boxa);
424  return heights.mode();
425 }
426 
427 // This method returns y-extents of the shiro-rekha computed from the input
428 // word image.
429 void ShiroRekhaSplitter::GetShiroRekhaYExtents(Pix* word_pix,
430  int* shirorekha_top,
431  int* shirorekha_bottom,
432  int* shirorekha_ylevel) {
433  // Compute a histogram from projecting the word on a vertical line.
434  PixelHistogram hist_horiz;
435  hist_horiz.ConstructHorizontalCountHist(word_pix);
436  // Get the ylevel where the top-line exists. This is basically the global
437  // maxima in the horizontal histogram.
438  int topline_onpixel_count = 0;
439  int topline_ylevel = hist_horiz.GetHistogramMaximum(&topline_onpixel_count);
440 
441  // Get the upper and lower extents of the shiro rekha.
442  int thresh = (topline_onpixel_count * 70) / 100;
443  int ulimit = topline_ylevel;
444  int llimit = topline_ylevel;
445  while (ulimit > 0 && hist_horiz.hist()[ulimit] >= thresh)
446  --ulimit;
447  while (llimit < pixGetHeight(word_pix) && hist_horiz.hist()[llimit] >= thresh)
448  ++llimit;
449 
450  if (shirorekha_top) *shirorekha_top = ulimit;
451  if (shirorekha_bottom) *shirorekha_bottom = llimit;
452  if (shirorekha_ylevel) *shirorekha_ylevel = topline_ylevel;
453 }
454 
455 // This method returns the global-maxima for the histogram. The frequency of
456 // the global maxima is returned in count, if specified.
458  int best_value = 0;
459  for (int i = 0; i < length_; ++i) {
460  if (hist_[i] > hist_[best_value]) {
461  best_value = i;
462  }
463  }
464  if (count) {
465  *count = hist_[best_value];
466  }
467  return best_value;
468 }
469 
470 // Methods to construct histograms from images.
472  Clear();
473  int width = pixGetWidth(pix);
474  int height = pixGetHeight(pix);
475  hist_ = new int[width];
476  length_ = width;
477  int wpl = pixGetWpl(pix);
478  l_uint32 *data = pixGetData(pix);
479  for (int i = 0; i < width; ++i)
480  hist_[i] = 0;
481  for (int i = 0; i < height; ++i) {
482  l_uint32 *line = data + i * wpl;
483  for (int j = 0; j < width; ++j)
484  if (GET_DATA_BIT(line, j))
485  ++(hist_[j]);
486  }
487 }
488 
490  Clear();
491  Numa* counts = pixCountPixelsByRow(pix, NULL);
492  length_ = numaGetCount(counts);
493  hist_ = new int[length_];
494  for (int i = 0; i < length_; ++i) {
495  l_int32 val = 0;
496  numaGetIValue(counts, i, &val);
497  hist_[i] = val;
498  }
499  numaDestroy(&counts);
500 }
501 
502 } // namespace tesseract.
void RefreshSegmentationWithNewBlobs(C_BLOB_LIST *new_blobs)
#define tprintf(...)
Definition: tprintf.h:31
Definition: statistc.h:33
inT32 mode() const
Definition: statistc.cpp:118
void add(inT32 value, inT32 count)
Definition: statistc.cpp:104
#define BOOL_VAR(name, val, comment)
Definition: params.h:280
float x_height() const
Definition: ocrrow.h:61
#define ASSERT_HOST(x)
Definition: errcode.h:84
Definition: ocrrow.h:32
float base_line(float xpos) const
Definition: ocrrow.h:56
inT16 left() const
Definition: rect.h:68
Definition: ocrblock.h:30
void RefreshWordBlobsFromNewBlobs(BLOCK_LIST *block_list, C_BLOB_LIST *new_blobs, C_BLOB_LIST *not_found_blobs)
Definition: ocrblock.cpp:479
TBOX bounding_box() const
Definition: ocrrow.h:85
#define INT_VAR(name, val, comment)
Definition: params.h:277
void PrintSegmentationStats(BLOCK_LIST *block_list)
Definition: ocrblock.cpp:411
bool major_overlap(const TBOX &box) const
Definition: rect.h:358
bool Split(bool split_for_pageseg)
inT16 height() const
Definition: rect.h:104
inT16 width() const
Definition: rect.h:111
int count(LIST var_list)
Definition: oldlist.cpp:108
Definition: rect.h:30
TBOX bounding_box() const
Definition: stepblob.cpp:250
bool devanagari_split_debugimage
int GetHistogramMaximum(int *count) const
void clear()
Definition: statistc.cpp:81
#define NULL
Definition: host.h:144
void DumpDebugImage(const char *filename) const
ROW_LIST * row_list()
get rows
Definition: ocrblock.h:120
int devanagari_split_debuglevel
inT16 top() const
Definition: rect.h:54