40 #include "allheaders.h" 53 #ifdef USE_STD_NAMESPACE 70 "Degrade rendered image with speckle noise, dilation/erosion " 74 BOOL_PARAM_FLAG(rotate_image,
true,
"Rotate the image in a random way.");
100 "Fraction of words to underline (value in [0,1])");
104 "Fraction of words to underline (value in [0,1])");
111 "Specify one of the following writing" 113 "'horizontal' : Render regular horizontal text. (default)\n" 114 "'vertical' : Render vertical text. Glyph orientation is" 115 " selected by Pango.\n" 116 "'vertical-upright' : Render vertical text. Glyph " 117 " orientation is set to be upright.");
119 INT_PARAM_FLAG(box_padding, 0,
"Padding around produced bounding boxes");
122 "Remove unrenderable words from source text");
128 "Rebuild and render ligatures");
131 "Search for all fonts that can render the text");
133 "If find_fonts==true, render each font to its own image. " 134 "Image filenames are of the form output_name.font_name.tif");
136 "If find_fonts==true, the minimum coverage the font has of " 137 "the characters in the text file to include it, between " 140 BOOL_PARAM_FLAG(list_available_fonts,
false,
"List available fonts and quit.");
142 BOOL_PARAM_FLAG(render_ngrams,
false,
"Put each space-separated entity from the" 143 " input file into one bounding box. The ngrams in the input" 144 " file will be randomly permuted before rendering (so that" 145 " there is sufficient variety of characters on each line).");
148 "Output word bounding boxes instead of character boxes. " 149 "This is used for Cube training, and implied by " 153 "File with characters in the unicharset. If --render_ngrams" 154 " is true and --unicharset_file is specified, ngrams with" 155 " characters that are not in unicharset will be omitted");
158 "Rotate the generated characters both ways.");
161 "Assumes that the input file contains a list of ngrams. Renders" 162 " each ngram, extracts spacing properties and records them in" 163 " output_base/[font_name].fontinfo file.");
167 "If true also outputs individual character images");
169 "Each glyph is square with this side length in pixels");
171 "Final_size=glyph_resized_size+2*glyph_num_border_pixels_to_pad");
185 static bool IsWhitespaceBox(
const BoxChar* boxchar) {
186 return (boxchar->
box() == NULL ||
190 static string StringReplace(
const string& in,
191 const string& oldsub,
const string& newsub) {
195 int pos = in.find(oldsub, start_pos);
196 if (pos == string::npos)
break;
197 out.append(in.data() + start_pos, pos - start_pos);
198 out.append(newsub.data(), newsub.length());
199 start_pos = pos + oldsub.length();
201 out.append(in.data() + start_pos, in.length() - start_pos);
217 const string &output_base) {
218 map<string, SpacingProperties> spacing_map;
219 map<string, SpacingProperties>::iterator spacing_map_it0;
220 map<string, SpacingProperties>::iterator spacing_map_it1;
221 int x_bearing, x_advance;
222 int len = utf8_text.length();
224 const char* text = utf8_text.c_str();
225 while (offset < len) {
226 offset += render->
RenderToImage(text + offset, strlen(text + offset), NULL);
227 const vector<BoxChar*> &boxes = render->
GetBoxes();
231 if (boxes.size() > 2 && !IsWhitespaceBox(boxes[boxes.size() - 1]) &&
232 IsWhitespaceBox(boxes[boxes.size() - 2])) {
233 if (boxes.size() > 3) {
234 tprintf(
"WARNING: Adjusting to bad page break after '%s%s'\n",
235 boxes[boxes.size() - 4]->ch().c_str(),
236 boxes[boxes.size() - 3]->ch().c_str());
238 offset -= boxes[boxes.size() - 1]->ch().size();
241 for (
int b = 0; b < boxes.size(); b += 2) {
242 while (b < boxes.size() && IsWhitespaceBox(boxes[b])) ++b;
243 if (b + 1 >= boxes.size())
break;
244 const string &ch0 = boxes[b]->ch();
257 if (IsWhitespaceBox(boxes[b+1])) {
260 int xgap = (boxes[b+1]->box()->x -
261 (boxes[b]->box()->x + boxes[b]->box()->w));
262 spacing_map_it0 = spacing_map.find(ch0);
264 if (spacing_map_it0 == spacing_map.end() &&
267 x_bearing, x_advance - x_bearing - boxes[b]->box()->w);
268 spacing_map_it0 = spacing_map.find(ch0);
271 const string &ch1 = boxes[b+1]->ch();
272 tlog(3,
"%s%s\n", ch0.c_str(), ch1.c_str());
273 spacing_map_it1 = spacing_map.find(ch1);
274 if (spacing_map_it1 == spacing_map.end() &&
277 x_bearing, x_advance - x_bearing - boxes[b+1]->box()->w);
278 spacing_map_it1 = spacing_map.find(ch1);
281 if (ok_count == 2 && xgap != (spacing_map_it0->second.x_gap_after +
282 spacing_map_it1->second.x_gap_before)) {
283 spacing_map_it0->second.kerned_x_gaps[ch1] = xgap;
288 string output_string;
289 const int kBufSize = 1024;
291 snprintf(buf, kBufSize,
"%d\n", static_cast<int>(spacing_map.size()));
292 output_string.append(buf);
293 map<string, SpacingProperties>::const_iterator spacing_map_it;
294 for (spacing_map_it = spacing_map.begin();
295 spacing_map_it != spacing_map.end(); ++spacing_map_it) {
296 snprintf(buf, kBufSize,
297 "%s %d %d %d", spacing_map_it->first.c_str(),
298 spacing_map_it->second.x_gap_before,
299 spacing_map_it->second.x_gap_after,
300 static_cast<int>(spacing_map_it->second.kerned_x_gaps.size()));
301 output_string.append(buf);
302 map<string, int>::const_iterator kern_it;
303 for (kern_it = spacing_map_it->second.kerned_x_gaps.begin();
304 kern_it != spacing_map_it->second.kerned_x_gaps.end(); ++kern_it) {
305 snprintf(buf, kBufSize,
306 " %s %d", kern_it->first.c_str(), kern_it->second);
307 output_string.append(buf);
309 output_string.append(
"\n");
315 const vector<BoxChar*>& vbox,
316 const int input_tiff_page) {
319 tprintf(
"ERROR: MakeIndividualGlyphs(): Input Pix* is NULL\n");
321 }
else if (FLAGS_glyph_resized_size <= 0) {
322 tprintf(
"ERROR: --glyph_resized_size must be positive\n");
324 }
else if (FLAGS_glyph_num_border_pixels_to_pad < 0) {
325 tprintf(
"ERROR: --glyph_num_border_pixels_to_pad must be 0 or positive\n");
329 const int n_boxes = vbox.size();
330 int n_boxes_saved = 0;
331 int current_tiff_page = 0;
333 static int glyph_count = 0;
334 for (
int i = 0; i < n_boxes; i++) {
336 Box* b = vbox[i]->mutable_box();
343 if (y < y_previous-pixGetHeight(pix)/10) {
344 tprintf(
"ERROR: Wrap-around encountered, at i=%d\n", i);
347 if (current_tiff_page < input_tiff_page)
continue;
348 else if (current_tiff_page > input_tiff_page)
break;
350 if (x < 0 || y < 0 ||
351 (x+w-1) >= pixGetWidth(pix) ||
352 (y+h-1) >= pixGetHeight(pix)) {
353 tprintf(
"ERROR: MakeIndividualGlyphs(): Index out of range, at i=%d" 354 " (x=%d, y=%d, w=%d, h=%d\n)", i, x, y, w, h);
356 }
else if (w < FLAGS_glyph_num_border_pixels_to_pad &&
357 h < FLAGS_glyph_num_border_pixels_to_pad) {
358 tprintf(
"ERROR: Input image too small to be a character, at i=%d\n", i);
362 Pix* pix_glyph = pixClipRectangle(pix, b, NULL);
364 tprintf(
"ERROR: MakeIndividualGlyphs(): Failed to clip, at i=%d\n", i);
368 Pix* pix_glyph_sq = pixScaleToSize(pix_glyph,
369 FLAGS_glyph_resized_size,
370 FLAGS_glyph_resized_size);
372 tprintf(
"ERROR: MakeIndividualGlyphs(): Failed to resize, at i=%d\n", i);
376 Pix* pix_glyph_sq_pad = pixAddBorder(pix_glyph_sq,
377 FLAGS_glyph_num_border_pixels_to_pad,
379 if (!pix_glyph_sq_pad) {
380 tprintf(
"ERROR: MakeIndividualGlyphs(): Failed to zero-pad, at i=%d\n",
385 Pix* pix_glyph_sq_pad_8 = pixConvertTo8(pix_glyph_sq_pad,
false);
387 snprintf(
filename, 1024,
"%s_%d.jpg", FLAGS_outputbase.c_str(),
389 if (pixWriteJpeg(
filename, pix_glyph_sq_pad_8, 100, 0)) {
390 tprintf(
"ERROR: MakeIndividualGlyphs(): Failed to write JPEG to %s," 395 pixDestroy(&pix_glyph);
396 pixDestroy(&pix_glyph_sq);
397 pixDestroy(&pix_glyph_sq_pad);
398 pixDestroy(&pix_glyph_sq_pad_8);
402 if (n_boxes_saved == 0) {
405 tprintf(
"Total number of characters saved = %d\n", n_boxes_saved);
419 int main(
int argc,
char** argv) {
422 if (FLAGS_list_available_fonts) {
423 const vector<string>& all_fonts = FontUtils::ListAvailableFonts();
424 for (
int i = 0; i < all_fonts.size(); ++i) {
425 printf(
"%3d: %s\n", i, all_fonts[i].c_str());
427 "Font %s is unrecognized.\n", all_fonts[i].c_str());
433 if (FLAGS_text.empty()) {
434 tprintf(
"'--text' option is missing!\n");
437 if (FLAGS_outputbase.empty()) {
438 tprintf(
"'--outputbase' option is missing!\n");
441 if (!FLAGS_unicharset_file.empty() && FLAGS_render_ngrams) {
442 tprintf(
"Use '--unicharset_file' only if '--render_ngrams' is set.\n");
446 if (!FLAGS_find_fonts && !FontUtils::IsAvailableFont(FLAGS_font.c_str())) {
448 if (!FontUtils::IsAvailableFont(FLAGS_font.c_str(), &pango_name)) {
449 tprintf(
"Could not find font named %s.\n", FLAGS_font.c_str());
450 if (!pango_name.empty()) {
451 tprintf(
"Pango suggested font %s.\n", pango_name.c_str());
453 tprintf(
"Please correct --font arg.\n");
458 if (FLAGS_render_ngrams)
459 FLAGS_output_word_boxes =
true;
461 char font_desc_name[1024];
462 snprintf(font_desc_name, 1024,
"%s %d", FLAGS_font.c_str(),
463 static_cast<int>(FLAGS_ptsize));
478 if (FLAGS_writing_mode ==
"horizontal") {
483 }
else if (FLAGS_writing_mode ==
"vertical") {
488 }
else if (FLAGS_writing_mode ==
"vertical-upright") {
498 tprintf(
"Invalid writing mode: %s\n", FLAGS_writing_mode.c_str());
504 if (!File::ReadFileToString(FLAGS_text.c_str(), &src_utf8)) {
505 tprintf(
"Failed to read file: %s\n", FLAGS_text.c_str());
510 if (strncmp(src_utf8.c_str(),
"\xef\xbb\xbf", 3) == 0) {
511 src_utf8.erase(0, 3);
513 tlog(1,
"Render string of size %d\n", src_utf8.length());
515 if (FLAGS_render_ngrams || FLAGS_only_extract_font_properties) {
518 const string kSeparator = FLAGS_render_ngrams ?
" " :
" ";
522 const int kCharsPerLine = (FLAGS_ptsize > 20) ? 50 : 100;
525 if (FLAGS_render_ngrams && !FLAGS_unicharset_file.empty() &&
527 tprintf(
"Failed to load unicharset from file %s\n",
528 FLAGS_unicharset_file.c_str());
535 const char *str8 = src_utf8.c_str();
536 int len = src_utf8.length();
538 vector<pair<int, int> > offsets;
540 while (offset < len) {
542 offsets.push_back(make_pair(offset, step));
546 if (FLAGS_render_ngrams)
547 std::random_shuffle(offsets.begin(), offsets.end());
549 for (
int i = 0, line = 1; i < offsets.size(); ++i) {
550 const char *curr_pos = str8 + offsets[i].first;
551 int ngram_len = offsets[i].second;
553 if (!FLAGS_unicharset_file.empty() &&
557 rand_utf8.append(curr_pos, ngram_len);
558 if (rand_utf8.length() > line * kCharsPerLine) {
559 rand_utf8.append(
" \n");
561 if (line & 0x1) rand_utf8.append(kSeparator);
563 rand_utf8.append(kSeparator);
566 tlog(1,
"Rendered ngram string of size %d\n", rand_utf8.length());
567 src_utf8.swap(rand_utf8);
569 if (FLAGS_only_extract_font_properties) {
570 tprintf(
"Extracting font properties only\n");
577 vector<float> page_rotation;
578 const char* to_render_utf8 = src_utf8.c_str();
582 vector<string> font_names;
586 int num_pass = FLAGS_bidirectional_rotation ? 2 : 1;
587 for (
int pass = 0; pass < num_pass; ++pass) {
590 for (
int offset = 0; offset < strlen(to_render_utf8); ++im, ++page_num) {
591 tlog(1,
"Starting page %d\n", im);
593 if (FLAGS_find_fonts) {
595 to_render_utf8 + offset,
596 strlen(to_render_utf8 + offset),
600 strlen(to_render_utf8 + offset), &pix);
606 rotation = -1 * page_rotation[page_num];
608 if (FLAGS_degrade_image) {
610 FLAGS_rotate_image ? &rotation : NULL);
616 page_rotation.push_back(rotation);
619 Pix* gray_pix = pixConvertTo8(pix,
false);
621 Pix* binary = pixThresholdToBinary(gray_pix, 128);
622 pixDestroy(&gray_pix);
623 char tiff_name[1024];
624 if (FLAGS_find_fonts) {
625 if (FLAGS_render_per_font) {
626 string fontname_for_file = tesseract::StringReplace(
627 font_used,
" ",
"_");
628 snprintf(tiff_name, 1024,
"%s.%s.tif", FLAGS_outputbase.c_str(),
629 fontname_for_file.c_str());
630 pixWriteTiff(tiff_name, binary, IFF_TIFF_G4,
"w");
631 tprintf(
"Rendered page %d to file %s\n", im, tiff_name);
633 font_names.push_back(font_used);
636 snprintf(tiff_name, 1024,
"%s.tif", FLAGS_outputbase.c_str());
637 pixWriteTiff(tiff_name, binary, IFF_TIFF_G4, im == 0 ?
"w" :
"a");
638 tprintf(
"Rendered page %d to file %s\n", im, tiff_name);
641 if (FLAGS_output_individual_glyph_images) {
643 tprintf(
"ERROR: Individual glyphs not saved\n");
648 if (FLAGS_find_fonts && offset != 0) {
655 if (!FLAGS_find_fonts) {
656 string box_name = FLAGS_outputbase.c_str();
659 }
else if (!FLAGS_render_per_font && !font_names.empty()) {
660 string filename = FLAGS_outputbase.c_str();
662 FILE* fp = fopen(
filename.c_str(),
"wb");
666 for (
int i = 0; i < font_names.size(); ++i) {
667 fprintf(fp,
"%s\n", font_names[i].c_str());
bool GetSpacingProperties(const string &utf8_char, int *x_bearing, int *x_advance) const
Pix * DegradeImage(Pix *input, int exposure, TRand *randomizer, float *rotation)
void set_strip_unrenderable_words(bool val)
BOOL_PARAM_FLAG(degrade_image, true, "Degrade rendered image with speckle noise, dilation/erosion " "and rotation")
void set_render_fullwidth_latin(bool render_fullwidth_latin)
void set_underline_continuation_prob(const double frac)
DOUBLE_PARAM_FLAG(char_spacing, 0, "Inter-character space in ems")
bool encodable_string(const char *str, int *first_bad_position) const
void set_vertical_text(bool vertical_text)
int SpanUTF8NotWhitespace(const char *text)
void set_output_word_boxes(bool val)
void set_box_padding(int val)
void set_add_ligatures(bool add_ligatures)
void set_seed(uinT64 seed)
int RenderAllFontsToImage(double min_coverage, const char *text, int text_length, string *font_used, Pix **pix)
SpacingProperties(int b, int a)
INT_PARAM_FLAG(exposure, 0, "Exposure level in photocopier")
int main(int argc, char **argv)
void set_h_margin(const int h_margin)
int RenderToImage(const char *text, int text_length, Pix **pix)
#define ASSERT_HOST_MSG(x,...)
const PangoFontInfo & font() const
void set_char_spacing(double char_spacing)
bool load_from_file(const char *const filename, bool skip_fragments)
const string & ch() const
int SpanUTF8Whitespace(const char *text)
void set_gravity_hint_strong(bool gravity_hint_strong)
void set_v_margin(const int v_margin)
const std::vector< BoxChar * > & GetBoxes() const
void RotatePageBoxes(float rotation)
map< string, int > kerned_x_gaps
void ParseCommandLineFlags(const char *usage, int *argc, char ***argv, const bool remove_flags)
void set_underline_start_prob(const double frac)
void WriteAllBoxes(const string &filename)
void ExtractFontProperties(const string &utf8_text, StringRenderer *render, const string &output_base)
STRING_PARAM_FLAG(text, "", "File name of text input to process")
void set_resolution(const int resolution)
void set_leading(int leading)
static void WriteStringToFileOrDie(const string &str, const string &filename)
bool MakeIndividualGlyphs(Pix *pix, const vector< BoxChar *> &vbox, const int input_tiff_page)