tesseract  3.05.00
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
tesseractmain.cpp
Go to the documentation of this file.
1 /**********************************************************************
2 * File: tessedit.cpp (Formerly tessedit.c)
3 * Description: Main program for merge of tess and editor.
4 * Author: Ray Smith
5 * Created: Tue Jan 07 15:21:46 GMT 1992
6 *
7 * (C) Copyright 1992, Hewlett-Packard Ltd.
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 *
18 **********************************************************************/
19 
20 // Include automatically generated configuration file if running autoconf
21 #ifdef HAVE_CONFIG_H
22 #include "config_auto.h"
23 #endif
24 
25 #include <iostream>
26 
27 #include "allheaders.h"
28 #include "baseapi.h"
29 #include "basedir.h"
30 #include "renderer.h"
31 #include "strngs.h"
32 #include "tprintf.h"
33 #include "openclwrapper.h"
34 #include "osdetect.h"
35 
36 #if defined(HAVE_TIFFIO_H) && defined(_WIN32)
37 
38 #include <tiffio.h>
39 
40 static void Win32WarningHandler(const char* module, const char* fmt,
41  va_list ap) {
42  if (module != NULL) {
43  fprintf(stderr, "%s: ", module);
44  }
45  fprintf(stderr, "Warning, ");
46  vfprintf(stderr, fmt, ap);
47  fprintf(stderr, ".\n");
48 }
49 
50 #endif /* HAVE_TIFFIO_H && _WIN32 */
51 
53  char* versionStrP;
54 
55  printf("tesseract %s\n", tesseract::TessBaseAPI::Version());
56 
57  versionStrP = getLeptonicaVersion();
58  printf(" %s\n", versionStrP);
59  lept_free(versionStrP);
60 
61  versionStrP = getImagelibVersions();
62  printf(" %s\n", versionStrP);
63  lept_free(versionStrP);
64 
65 #ifdef USE_OPENCL
66  cl_platform_id platform;
67  cl_uint num_platforms;
68  cl_device_id devices[2];
69  cl_uint num_devices;
70  char info[256];
71  int i;
72 
73  printf(" OpenCL info:\n");
74  clGetPlatformIDs(1, &platform, &num_platforms);
75  printf(" Found %d platforms.\n", num_platforms);
76  clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0);
77  printf(" Platform name: %s.\n", info);
78  clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0);
79  printf(" Version: %s.\n", info);
80  clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices);
81  printf(" Found %d devices.\n", num_devices);
82  for (i = 0; i < num_devices; ++i) {
83  clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0);
84  printf(" Device %d name: %s.\n", i + 1, info);
85  }
86 #endif
87 }
88 
89 void PrintUsage(const char* program) {
90  printf(
91  "Usage:\n"
92  " %s --help | --help-psm | --help-oem | --version\n"
93  " %s --list-langs [--tessdata-dir PATH]\n"
94  " %s --print-parameters [options...] [configfile...]\n"
95  " %s imagename|stdin outputbase|stdout [options...] [configfile...]\n",
96  program, program, program, program);
97 }
98 
100  const char* msg =
101  "Page segmentation modes:\n"
102  " 0 Orientation and script detection (OSD) only.\n"
103  " 1 Automatic page segmentation with OSD.\n"
104  " 2 Automatic page segmentation, but no OSD, or OCR.\n"
105  " 3 Fully automatic page segmentation, but no OSD. (Default)\n"
106  " 4 Assume a single column of text of variable sizes.\n"
107  " 5 Assume a single uniform block of vertically aligned text.\n"
108  " 6 Assume a single uniform block of text.\n"
109  " 7 Treat the image as a single text line.\n"
110  " 8 Treat the image as a single word.\n"
111  " 9 Treat the image as a single word in a circle.\n"
112  " 10 Treat the image as a single character.\n"
113  " 11 Sparse text. Find as much text as possible in no"
114  " particular order.\n"
115  " 12 Sparse text with OSD.\n"
116  " 13 Raw line. Treat the image as a single text line,\n"
117  "\t\t\tbypassing hacks that are Tesseract-specific.\n";
118 
119  printf("%s", msg);
120 }
121 
123  const char* msg =
124  "OCR Engine modes:\n"
125  " 0 Original Tesseract only.\n"
126  " 1 Cube only.\n"
127  " 2 Tesseract + cube.\n"
128  " 3 Default, based on what is available.\n";
129 
130  printf("%s", msg);
131 }
132 
133 void PrintHelpMessage(const char* program) {
134  PrintUsage(program);
135 
136  const char* ocr_options =
137  "OCR options:\n"
138  " --tessdata-dir PATH Specify the location of tessdata path.\n"
139  " --user-words PATH Specify the location of user words file.\n"
140  " --user-patterns PATH Specify the location of user patterns file.\n"
141  " -l LANG[+LANG] Specify language(s) used for OCR.\n"
142  " -c VAR=VALUE Set value for config variables.\n"
143  " Multiple -c arguments are allowed.\n"
144  " --psm NUM Specify page segmentation mode.\n"
145  " --oem NUM Specify OCR Engine mode.\n"
146  "NOTE: These options must occur before any configfile.\n";
147 
148  printf("\n%s\n", ocr_options);
149  PrintHelpForPSM();
150  PrintHelpForOEM();
151 
152  const char* single_options =
153  "Single options:\n"
154  " -h, --help Show this help message.\n"
155  " --help-psm Show page segmentation modes.\n"
156  " --help-oem Show OCR Engine modes.\n"
157  " -v, --version Show version information.\n"
158  " --list-langs List available languages for tesseract engine.\n"
159  " --print-parameters Print tesseract parameters to stdout.\n";
160 
161  printf("\n%s", single_options);
162 }
163 
165  char** argv) {
166  char opt1[256], opt2[255];
167  for (int i = 0; i < argc; i++) {
168  if (strcmp(argv[i], "-c") == 0 && i + 1 < argc) {
169  strncpy(opt1, argv[i + 1], 255);
170  opt1[255] = '\0';
171  char* p = strchr(opt1, '=');
172  if (!p) {
173  fprintf(stderr, "Missing = in configvar assignment\n");
174  exit(1);
175  }
176  *p = 0;
177  strncpy(opt2, strchr(argv[i + 1], '=') + 1, 255);
178  opt2[254] = 0;
179  ++i;
180 
181  if (!api->SetVariable(opt1, opt2)) {
182  fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2);
183  }
184  }
185  }
186 }
187 
189  GenericVector<STRING> languages;
190  api->GetAvailableLanguagesAsVector(&languages);
191  printf("List of available languages (%d):\n", languages.size());
192  for (int index = 0; index < languages.size(); ++index) {
193  STRING& string = languages[index];
194  printf("%s\n", string.string());
195  }
196  api->End();
197 }
198 
199 void PrintBanner() {
200  tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
202 }
203 
219  tesseract::PageSegMode pagesegmode) {
221  api->SetPageSegMode(pagesegmode);
222 }
223 
224 // NOTE: arg_i is used here to avoid ugly *i so many times in this function
225 void ParseArgs(const int argc, char** argv, const char** lang,
226  const char** image, const char** outputbase,
227  const char** datapath, bool* list_langs, bool* print_parameters,
228  GenericVector<STRING>* vars_vec,
229  GenericVector<STRING>* vars_values, int* arg_i,
230  tesseract::PageSegMode* pagesegmode,
231  tesseract::OcrEngineMode* enginemode) {
232  if (argc == 1) {
233  PrintHelpMessage(argv[0]);
234  exit(0);
235  }
236 
237  if (argc == 2) {
238  if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0)) {
239  PrintHelpMessage(argv[0]);
240  exit(0);
241  }
242  if ((strcmp(argv[1], "--help-psm") == 0)) {
243  PrintHelpForPSM();
244  exit(0);
245  }
246  if ((strcmp(argv[1], "--help-oem") == 0)) {
247  PrintHelpForOEM();
248  exit(0);
249  }
250  if ((strcmp(argv[1], "-v") == 0) || (strcmp(argv[1], "--version") == 0)) {
252  exit(0);
253  }
254  }
255 
256  bool noocr = false;
257  int i = 1;
258  while (i < argc && (*outputbase == NULL || argv[i][0] == '-')) {
259  if (strcmp(argv[i], "-l") == 0 && i + 1 < argc) {
260  *lang = argv[i + 1];
261  ++i;
262  } else if (strcmp(argv[i], "--tessdata-dir") == 0 && i + 1 < argc) {
263  *datapath = argv[i + 1];
264  ++i;
265  } else if (strcmp(argv[i], "--user-words") == 0 && i + 1 < argc) {
266  vars_vec->push_back("user_words_file");
267  vars_values->push_back(argv[i + 1]);
268  ++i;
269  } else if (strcmp(argv[i], "--user-patterns") == 0 && i + 1 < argc) {
270  vars_vec->push_back("user_patterns_file");
271  vars_values->push_back(argv[i + 1]);
272  ++i;
273  } else if (strcmp(argv[i], "--list-langs") == 0) {
274  noocr = true;
275  *list_langs = true;
276  } else if (strcmp(argv[i], "-psm") == 0 && i + 1 < argc) {
277  // The parameter -psm is deprecated and was replaced by --psm.
278  // It is still supported for compatibility reasons.
279  *pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[i + 1]));
280  ++i;
281  } else if (strcmp(argv[i], "--psm") == 0 && i + 1 < argc) {
282  *pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[i + 1]));
283  ++i;
284  } else if (strcmp(argv[i], "--oem") == 0 && i + 1 < argc) {
285  *enginemode = static_cast<tesseract::OcrEngineMode>(atoi(argv[i + 1]));
286  ++i;
287  } else if (strcmp(argv[i], "--print-parameters") == 0) {
288  noocr = true;
289  *print_parameters = true;
290  } else if (strcmp(argv[i], "-c") == 0 && i + 1 < argc) {
291  // handled properly after api init
292  ++i;
293  } else if (*image == NULL) {
294  *image = argv[i];
295  } else if (*outputbase == NULL) {
296  *outputbase = argv[i];
297  }
298  ++i;
299  }
300 
301  *arg_i = i;
302 
303  if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) {
304  *list_langs = true;
305  noocr = true;
306  }
307 
308  if (*outputbase == NULL && noocr == false) {
309  PrintHelpMessage(argv[0]);
310  exit(1);
311  }
312 }
313 
317  tesseract::PageSegMode pagesegmode, const char* outputbase) {
318  if (pagesegmode == tesseract::PSM_OSD_ONLY) {
319  renderers->push_back(new tesseract::TessOsdRenderer(outputbase));
320  } else {
321  bool b;
322  api->GetBoolVariable("tessedit_create_hocr", &b);
323  if (b) {
324  bool font_info;
325  api->GetBoolVariable("hocr_font_info", &font_info);
326  renderers->push_back(
327  new tesseract::TessHOcrRenderer(outputbase, font_info));
328  }
329 
330  api->GetBoolVariable("tessedit_create_tsv", &b);
331  if (b) {
332  bool font_info;
333  api->GetBoolVariable("hocr_font_info", &font_info);
334  renderers->push_back(
335  new tesseract::TessTsvRenderer(outputbase, font_info));
336  }
337 
338  api->GetBoolVariable("tessedit_create_pdf", &b);
339  if (b) {
340  renderers->push_back(
341  new tesseract::TessPDFRenderer(outputbase, api->GetDatapath()));
342  }
343 
344  api->GetBoolVariable("tessedit_write_unlv", &b);
345  if (b) {
346  renderers->push_back(new tesseract::TessUnlvRenderer(outputbase));
347  }
348 
349  api->GetBoolVariable("tessedit_create_boxfile", &b);
350  if (b) {
351  renderers->push_back(new tesseract::TessBoxTextRenderer(outputbase));
352  }
353 
354  api->GetBoolVariable("tessedit_create_txt", &b);
355  if (b || renderers->empty()) {
356  renderers->push_back(new tesseract::TessTextRenderer(outputbase));
357  }
358  }
359 
360  if (!renderers->empty()) {
361  // Since the PointerVector auto-deletes, null-out the renderers that are
362  // added to the root, and leave the root in the vector.
363  for (int r = 1; r < renderers->size(); ++r) {
364  (*renderers)[0]->insert((*renderers)[r]);
365  (*renderers)[r] = NULL;
366  }
367  }
368 }
369 
370 /**********************************************************************
371  * main()
372  *
373  **********************************************************************/
374 
375 int main(int argc, char** argv) {
376  const char* lang = "eng";
377  const char* image = NULL;
378  const char* outputbase = NULL;
379  const char* datapath = NULL;
380  bool list_langs = false;
381  bool print_parameters = false;
382  int arg_i = 1;
385  /* main() calls functions like ParseArgs which call exit().
386  * This results in memory leaks if vars_vec and vars_values are
387  * declared as auto variables (destructor is not called then). */
388  static GenericVector<STRING> vars_vec;
389  static GenericVector<STRING> vars_values;
390 
391 #if !defined(DEBUG)
392  // Disable debugging and informational messages from Leptonica.
393  setMsgSeverity(L_SEVERITY_WARNING);
394 #endif
395 
396 #if defined(HAVE_TIFFIO_H) && defined(_WIN32)
397  /* Show libtiff warnings on console (not in GUI). */
398  TIFFSetWarningHandler(Win32WarningHandler);
399 #endif /* HAVE_TIFFIO_H && _WIN32 */
400 
401  ParseArgs(argc, argv, &lang, &image, &outputbase, &datapath, &list_langs,
402  &print_parameters, &vars_vec, &vars_values, &arg_i, &pagesegmode,
403  &enginemode);
404 
405  bool banner = false;
406  if (outputbase != NULL && strcmp(outputbase, "-") &&
407  strcmp(outputbase, "stdout")) {
408  banner = true;
409  }
410 
411  PERF_COUNT_START("Tesseract:main")
413 
414  api.SetOutputName(outputbase);
415 
416  int init_failed = api.Init(datapath, lang, enginemode, &(argv[arg_i]),
417  argc - arg_i, &vars_vec, &vars_values, false);
418  if (init_failed) {
419  fprintf(stderr, "Could not initialize tesseract.\n");
420  exit(1);
421  }
422 
423  SetVariablesFromCLArgs(&api, argc, argv);
424 
425  if (list_langs) {
426  PrintLangsList(&api);
427  exit(0);
428  }
429 
430  if (print_parameters) {
431  FILE* fout = stdout;
432  fprintf(stdout, "Tesseract parameters:\n");
433  api.PrintVariables(fout);
434  api.End();
435  exit(0);
436  }
437 
438  FixPageSegMode(&api, pagesegmode);
439 
440  if (pagesegmode == tesseract::PSM_AUTO_ONLY) {
441  int ret_val = 0;
442 
443  Pix* pixs = pixRead(image);
444  if (!pixs) {
445  fprintf(stderr, "Cannot open input file: %s\n", image);
446  exit(2);
447  }
448 
449  api.SetImage(pixs);
450 
451  tesseract::Orientation orientation;
454  float deskew_angle;
455 
457  if (it) {
458  it->Orientation(&orientation, &direction, &order, &deskew_angle);
459  tprintf(
460  "Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n"
461  "Deskew angle: %.4f\n",
462  orientation, direction, order, deskew_angle);
463  } else {
464  ret_val = 1;
465  }
466 
467  delete it;
468 
469  pixDestroy(&pixs);
470  exit(ret_val);
471  }
472 
473  // set in_training_mode to true when using one of these configs:
474  // ambigs.train, box.train, box.train.stderr, linebox, rebox
475  bool b = false;
476  bool in_training_mode =
477  (api.GetBoolVariable("tessedit_ambigs_training", &b) && b) ||
478  (api.GetBoolVariable("tessedit_resegment_from_boxes", &b) && b) ||
479  (api.GetBoolVariable("tessedit_make_boxes_from_boxes", &b) && b);
480 
482 
483  if (in_training_mode) {
484  renderers.push_back(NULL);
485  } else {
486  PreloadRenderers(&api, &renderers, pagesegmode, outputbase);
487  }
488 
489  if (!renderers.empty()) {
490  if (banner) PrintBanner();
491  bool succeed = api.ProcessPages(image, NULL, 0, renderers[0]);
492  if (!succeed) {
493  fprintf(stderr, "Error during processing.\n");
494  exit(1);
495  }
496  }
497 
499  return 0; // Normal exit
500 }
void PrintLangsList(tesseract::TessBaseAPI *api)
void SetVariablesFromCLArgs(tesseract::TessBaseAPI *api, int argc, char **argv)
Orientation and script detection only.
Definition: publictypes.h:152
PageSegMode GetPageSegMode() const
Definition: baseapi.cpp:465
Assume a single uniform block of text. (Default.)
Definition: publictypes.h:160
void PrintVersionInfo()
void PrintHelpMessage(const char *program)
void PreloadRenderers(tesseract::TessBaseAPI *api, tesseract::PointerVector< tesseract::TessResultRenderer > *renderers, tesseract::PageSegMode pagesegmode, const char *outputbase)
Definition: strngs.h:44
int main(int argc, char **argv)
#define PERF_COUNT_END
void SetPageSegMode(PageSegMode mode)
Definition: baseapi.cpp:458
bool empty() const
Definition: genericvector.h:84
void PrintBanner()
void PrintHelpForOEM()
void PrintHelpForPSM()
#define tprintf(...)
Definition: tprintf.h:31
void PrintUsage(const char *program)
void ParseArgs(const int argc, char **argv, const char **lang, const char **image, const char **outputbase, const char **datapath, bool *list_langs, bool *print_parameters, GenericVector< STRING > *vars_vec, GenericVector< STRING > *vars_values, int *arg_i, tesseract::PageSegMode *pagesegmode, tesseract::OcrEngineMode *enginemode)
int size() const
Definition: genericvector.h:72
int direction(EDGEPT *point)
Definition: vecfuncs.cpp:43
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: baseapi.cpp:521
PageIterator * AnalyseLayout()
Definition: baseapi.cpp:809
static const char * Version()
Definition: baseapi.cpp:140
#define PERF_COUNT_START(FUNCT_NAME)
const char * GetDatapath()
Definition: baseapi.cpp:948
Automatic page segmentation, but no OSD, or OCR.
Definition: publictypes.h:155
int push_back(T object)
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
Definition: baseapi.cpp:368
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1068
void SetOutputName(const char *name)
Definition: baseapi.cpp:207
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
void FixPageSegMode(tesseract::TessBaseAPI *api, tesseract::PageSegMode pagesegmode)
void PrintVariables(FILE *fp) const
Definition: baseapi.cpp:262
int Init(const char *datapath, const char *language, OcrEngineMode mode, char **configs, int configs_size, const GenericVector< STRING > *vars_vec, const GenericVector< STRING > *vars_values, bool set_only_non_debug_params)
Definition: baseapi.cpp:274
Fully automatic page segmentation, but no OSD.
Definition: publictypes.h:156
bool SetVariable(const char *name, const char *value)
Definition: baseapi.cpp:214
bool GetBoolVariable(const char *name, bool *value) const
Definition: baseapi.cpp:234