All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
boxchar.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: boxchar.cpp
3  * Description: Simple class to associate a Tesseract classification unit with
4  * its bounding box so that the boxes can be rotated as the image
5  * is rotated for degradation. Also includes routines to output
6  * the character-tagged boxes to a boxfile.
7  * Author: Ray Smith
8  * Created: Mon Nov 18 2013
9  *
10  * (C) Copyright 2013, Google Inc.
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * http://www.apache.org/licenses/LICENSE-2.0
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  **********************************************************************/
22 
23 #include "boxchar.h"
24 
25 #include <stddef.h>
26 #include <algorithm>
27 
28 #include "fileio.h"
29 #include "genericvector.h"
30 #include "ndminx.h"
31 #include "normstrngs.h"
32 #include "tprintf.h"
33 #include "unicharset.h"
34 #include "unicode/uchar.h" // from libicu
35 
36 // Absolute Ratio of dx:dy or dy:dx to be a newline.
37 const int kMinNewlineRatio = 5;
38 
39 namespace tesseract {
40 
41 BoxChar::BoxChar(const char* utf8_str, int len) : ch_(utf8_str, len) {
42  box_ = NULL;
43 }
44 
45 BoxChar::~BoxChar() { boxDestroy(&box_); }
46 
47 void BoxChar::AddBox(int x, int y, int width, int height) {
48  box_ = boxCreate(x, y, width, height);
49 }
50 
51 /* static */
52 void BoxChar::TranslateBoxes(int xshift, int yshift, vector<BoxChar*>* boxes) {
53  for (int i = 0; i < boxes->size(); ++i) {
54  BOX* box = (*boxes)[i]->box_;
55  if (box != NULL) {
56  box->x += xshift;
57  box->y += yshift;
58  }
59  }
60 }
61 
62 // Prepares for writing the boxes to a file by inserting newlines, spaces,
63 // and re-ordering so the boxes are strictly left-to-right.
64 /* static */
65 void BoxChar::PrepareToWrite(vector<BoxChar*>* boxes) {
66  bool rtl_rules = ContainsMostlyRTL(*boxes);
67  bool vertical_rules = MostlyVertical(*boxes);
68  InsertNewlines(rtl_rules, vertical_rules, boxes);
69  InsertSpaces(rtl_rules, vertical_rules, boxes);
70  for (int i = 0; i < boxes->size(); ++i) {
71  if ((*boxes)[i]->box_ == NULL) tprintf("Null box at index %d\n", i);
72  }
73  if (rtl_rules) {
74  ReorderRTLText(boxes);
75  }
76  tprintf("Rtl = %d ,vertical=%d\n", rtl_rules, vertical_rules);
77 }
78 
79 // Inserts newline (tab) characters into the vector at newline positions.
80 /* static */
81 void BoxChar::InsertNewlines(bool rtl_rules, bool vertical_rules,
82  vector<BoxChar*>* boxes) {
83  int prev_i = -1;
84  int max_shift = 0;
85  for (int i = 0; i < boxes->size(); ++i) {
86  Box* box = (*boxes)[i]->box_;
87  if (box == NULL) {
88  if (prev_i < 0 || prev_i < i - 1 || i + 1 == boxes->size()) {
89  // Erase null boxes at the start of a line and after another null box.
90  do {
91  delete (*boxes)[i];
92  boxes->erase(boxes->begin() + i);
93  --i;
94  } while (i >= 0 && i + 1 == boxes->size() && (*boxes)[i]->box_ == NULL);
95  }
96  continue;
97  }
98  if (prev_i >= 0) {
99  Box* prev_box = (*boxes)[prev_i]->box_;
100  int shift = box->x - prev_box->x;
101  if (vertical_rules) {
102  shift = box->y - prev_box->y;
103  } else if (rtl_rules) {
104  shift = -shift;
105  }
106  if (-shift > max_shift) {
107  // This is a newline.
108  int width = prev_box->w;
109  int height = prev_box->h;
110  int x = prev_box->x + width;
111  int y = prev_box->y;
112  if (vertical_rules) {
113  x = prev_box->x;
114  y = prev_box->y + height;
115  } else if (rtl_rules) {
116  x = prev_box->x - width;
117  if (x < 0) {
118  tprintf("prev x = %d, width=%d\n", prev_box->x, width);
119  x = 0;
120  }
121  }
122  if (prev_i == i - 1) {
123  // New character needed.
124  BoxChar* new_box = new BoxChar("\t", 1);
125  new_box->AddBox(x, y, width, height);
126  new_box->page_ = (*boxes)[i]->page_;
127  boxes->insert(boxes->begin() + i, new_box);
128  ++i;
129  } else {
130  (*boxes)[i - 1]->AddBox(x, y, width, height);
131  (*boxes)[i - 1]->ch_ = "\t";
132  }
133  max_shift = 0;
134  } else if (shift > max_shift) {
135  max_shift = shift;
136  }
137  }
138  prev_i = i;
139  }
140 }
141 
142 // Converts NULL boxes to space characters, with appropriate bounding boxes.
143 /* static */
144 void BoxChar::InsertSpaces(bool rtl_rules, bool vertical_rules,
145  vector<BoxChar*>* boxes) {
146  // After InsertNewlines, any remaining null boxes are not newlines, and are
147  // singletons, so add a box to each remaining null box.
148  for (int i = 1; i + 1 < boxes->size(); ++i) {
149  Box* box = (*boxes)[i]->box_;
150  if (box == NULL) {
151  Box* prev = (*boxes)[i - 1]->box_;
152  Box* next = (*boxes)[i + 1]->box_;
153  ASSERT_HOST(prev != NULL && next != NULL);
154  int top = MIN(prev->y, next->y);
155  int bottom = MAX(prev->y + prev->h, next->y + next->h);
156  int left = prev->x + prev->w;
157  int right = next->x;
158  if (vertical_rules) {
159  top = prev->y + prev->h;
160  bottom = next->y;
161  left = MIN(prev->x, next->x);
162  right = MAX(prev->x + prev->w, next->x + next->w);
163  } else if (rtl_rules) {
164  // With RTL we have to account for BiDi.
165  // Right becomes the min left of all prior boxes back to the first
166  // space or newline.
167  right = prev->x;
168  left = next->x + next->w;
169  for (int j = i - 2;
170  j >= 0 && (*boxes)[j]->ch_ != " " && (*boxes)[j]->ch_ != "\t";
171  --j) {
172  prev = (*boxes)[j]->box_;
173  ASSERT_HOST(prev != NULL);
174  if (prev->x < right) {
175  right = prev->x;
176  }
177  }
178  // Left becomes the max right of all next boxes foward to the first
179  // space or newline.
180  for (int j = i + 2; j < boxes->size() && (*boxes)[j]->box_ != NULL &&
181  (*boxes)[j]->ch_ != "\t";
182  ++j) {
183  next = (*boxes)[j]->box_;
184  if (next->x + next->w > left) {
185  left = next->x + next->w;
186  }
187  }
188  }
189  // Italic and stylized characters can produce negative spaces, which
190  // Leptonica doesn't like, so clip to a positive size.
191  if (right <= left) right = left + 1;
192  if (bottom <= top) bottom = top + 1;
193  (*boxes)[i]->AddBox(left, top, right - left, bottom - top);
194  (*boxes)[i]->ch_ = " ";
195  }
196  }
197 }
198 
199 // Reorders text in a right-to-left script in left-to-right order.
200 /* static */
201 void BoxChar::ReorderRTLText(vector<BoxChar*>* boxes) {
202  // After adding newlines and spaces, this task is simply a matter of sorting
203  // by left each group of boxes between newlines.
204  BoxCharPtrSort sorter;
205  int end = 0;
206  for (int start = 0; start < boxes->size(); start = end + 1) {
207  end = start + 1;
208  while (end < boxes->size() && (*boxes)[end]->ch_ != "\t") ++end;
209  sort(boxes->begin() + start, boxes->begin() + end, sorter);
210  }
211 }
212 
213 // Returns true if the vector contains mostly RTL characters.
214 /* static */
215 bool BoxChar::ContainsMostlyRTL(const vector<BoxChar*>& boxes) {
216  int num_rtl = 0, num_ltr = 0;
217  for (int i = 0; i < boxes.size(); ++i) {
218  // Convert the unichar to UTF32 representation
219  GenericVector<char32> uni_vector;
220  if (!UNICHAR::UTF8ToUnicode(boxes[i]->ch_.c_str(), &uni_vector)) {
221  tprintf("Illegal utf8 in boxchar %d string:%s = ", i,
222  boxes[i]->ch_.c_str());
223  for (int c = 0; c < boxes[i]->ch_.size(); ++c) {
224  tprintf(" 0x%x", boxes[i]->ch_[c]);
225  }
226  tprintf("\n");
227  continue;
228  }
229  for (int j = 0; j < uni_vector.size(); ++j) {
230  UCharDirection dir = u_charDirection(uni_vector[j]);
231  if (dir == U_RIGHT_TO_LEFT || dir == U_RIGHT_TO_LEFT_ARABIC ||
232  dir == U_ARABIC_NUMBER) {
233  ++num_rtl;
234  } else {
235  ++num_ltr;
236  }
237  }
238  }
239  return num_rtl > num_ltr;
240 }
241 
242 // Returns true if the text is mostly laid out vertically.
243 /* static */
244 bool BoxChar::MostlyVertical(const vector<BoxChar*>& boxes) {
245  inT64 total_dx = 0, total_dy = 0;
246  for (int i = 1; i < boxes.size(); ++i) {
247  if (boxes[i - 1]->box_ != NULL && boxes[i]->box_ != NULL &&
248  boxes[i - 1]->page_ == boxes[i]->page_) {
249  int dx = boxes[i]->box_->x - boxes[i - 1]->box_->x;
250  int dy = boxes[i]->box_->y - boxes[i - 1]->box_->y;
251  if (abs(dx) > abs(dy) * kMinNewlineRatio ||
252  abs(dy) > abs(dx) * kMinNewlineRatio) {
253  total_dx += dx * dx;
254  total_dy += dy * dy;
255  }
256  }
257  }
258  return total_dy > total_dx;
259 }
260 
261 // Returns the total length of all the strings in the boxes.
262 /* static */
263 int BoxChar::TotalByteLength(const vector<BoxChar*>& boxes) {
264  int total_length = 0;
265  for (int i = 0; i < boxes.size(); ++i) total_length += boxes[i]->ch_.size();
266  return total_length;
267 }
268 
269 // Rotate the boxes in [start_box, end_box) by the given rotation.
270 // The rotation is in radians clockwise about the given center.
271 /* static */
272 void BoxChar::RotateBoxes(float rotation, int xcenter, int ycenter,
273  int start_box, int end_box, vector<BoxChar*>* boxes) {
274  Boxa* orig = boxaCreate(0);
275  for (int i = start_box; i < end_box; ++i) {
276  BOX* box = (*boxes)[i]->box_;
277  if (box) boxaAddBox(orig, box, L_CLONE);
278  }
279  Boxa* rotated = boxaRotate(orig, xcenter, ycenter, rotation);
280  boxaDestroy(&orig);
281  for (int i = start_box, box_ind = 0; i < end_box; ++i) {
282  if ((*boxes)[i]->box_) {
283  boxDestroy(&((*boxes)[i]->box_));
284  (*boxes)[i]->box_ = boxaGetBox(rotated, box_ind++, L_CLONE);
285  }
286  }
287  boxaDestroy(&rotated);
288 }
289 
290 const int kMaxLineLength = 1024;
291 /* static */
292 void BoxChar::WriteTesseractBoxFile(const string& filename, int height,
293  const vector<BoxChar*>& boxes) {
294  string output;
295  char buffer[kMaxLineLength];
296  for (int i = 0; i < boxes.size(); ++i) {
297  const Box* box = boxes[i]->box_;
298  if (box == NULL) {
299  tprintf("Error: Call PrepareToWrite before WriteTesseractBoxFile!!\n");
300  return;
301  }
302  int nbytes =
303  snprintf(buffer, kMaxLineLength, "%s %d %d %d %d %d\n",
304  boxes[i]->ch_.c_str(), box->x, height - box->y - box->h,
305  box->x + box->w, height - box->y, boxes[i]->page_);
306  output.append(buffer, nbytes);
307  }
308  File::WriteStringToFileOrDie(output, filename);
309 }
310 } // namespace tesseract
int size() const
Definition: genericvector.h:72
static void ReorderRTLText(vector< BoxChar * > *boxes)
Definition: boxchar.cpp:201
#define MAX(x, y)
Definition: ndminx.h:24
#define tprintf(...)
Definition: tprintf.h:31
#define MIN(x, y)
Definition: ndminx.h:28
static void TranslateBoxes(int xshift, int yshift, vector< BoxChar * > *boxes)
Definition: boxchar.cpp:52
static void WriteStringToFileOrDie(const string &str, const string &filename)
Definition: fileio.cpp:53
BoxChar(const char *utf8_str, int len)
Definition: boxchar.cpp:41
#define ASSERT_HOST(x)
Definition: errcode.h:84
static bool UTF8ToUnicode(const char *utf8_str, GenericVector< int > *unicodes)
Definition: unichar.cpp:211
static void InsertSpaces(bool rtl_rules, bool vertical_rules, vector< BoxChar * > *boxes)
Definition: boxchar.cpp:144
void AddBox(int x, int y, int width, int height)
Definition: boxchar.cpp:47
const Box * box() const
Definition: boxchar.h:48
static void WriteTesseractBoxFile(const string &name, int height, const vector< BoxChar * > &boxes)
Definition: boxchar.cpp:292
static void RotateBoxes(float rotation, int xcenter, int ycenter, int start_box, int end_box, vector< BoxChar * > *boxes)
Definition: boxchar.cpp:272
static void PrepareToWrite(vector< BoxChar * > *boxes)
Definition: boxchar.cpp:65
const int kMinNewlineRatio
Definition: boxchar.cpp:37
#define NULL
Definition: host.h:144
static void InsertNewlines(bool rtl_rules, bool vertical_rules, vector< BoxChar * > *boxes)
Definition: boxchar.cpp:81
static int TotalByteLength(const vector< BoxChar * > &boxes)
Definition: boxchar.cpp:263
static bool MostlyVertical(const vector< BoxChar * > &boxes)
Definition: boxchar.cpp:244
static bool ContainsMostlyRTL(const vector< BoxChar * > &boxes)
Definition: boxchar.cpp:215
long long int inT64
Definition: host.h:108
const int kMaxLineLength
Definition: boxchar.cpp:290