31 #include "vcsversion.h"
35 #undef __STRICT_ANSI__
50 #include "allheaders.h"
112 osd_tesseract_(NULL),
118 paragraph_models_(NULL),
126 recognition_done_(false),
128 rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0),
129 image_width_(0), image_height_(0) {
141 #if defined(GIT_REV) && (defined(DEBUG) || defined(_DEBUG))
156 #if USE_DEVICE_SELECTION
162 #if USE_DEVICE_SELECTION
163 ds_device device = OpenclDevice::getDeviceSelection();
164 if (device.type == DS_DEVICE_OPENCL_DEVICE) {
165 *data =
reinterpret_cast<void*
>(
new cl_device_id);
166 memcpy(*data, &device.oclDeviceID,
sizeof(cl_device_id));
167 return sizeof(cl_device_id);
182 struct sigaction action;
183 memset(&action, 0,
sizeof(action));
185 action.sa_flags = SA_RESETHAND;
186 sigaction(SIGSEGV, &action, NULL);
187 sigaction(SIGFPE, &action, NULL);
188 sigaction(SIGBUS, &action, NULL);
191 tprintf(
"CatchSignals has no non-linux implementation!\n");
227 IntParam *p = ParamUtils::FindParam<IntParam>(
229 if (p == NULL)
return false;
230 *value = (
inT32)(*p);
235 BoolParam *p = ParamUtils::FindParam<BoolParam>(
237 if (p == NULL)
return false;
238 *value = (
BOOL8)(*p);
243 StringParam *p = ParamUtils::FindParam<StringParam>(
245 return (p != NULL) ? p->
string() : NULL;
249 DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
251 if (p == NULL)
return false;
252 *value = (double)(*p);
278 bool set_only_non_debug_params) {
281 if (language == NULL) language =
"eng";
300 bool reset_classifier =
true;
302 reset_classifier =
false;
306 language,
oem, configs, configs_size, vars_vec, vars_values,
307 set_only_non_debug_params) != 0) {
328 if (reset_classifier) {
360 for (
int i = 0; i < num_subs; ++i)
374 char fname[_MAX_FNAME];
375 WIN32_FIND_DATA data;
377 HANDLE handle = FindFirstFile(pattern.
string(), &data);
378 if (handle != INVALID_HANDLE_VALUE) {
379 for (; result; result = FindNextFile(handle, &data)) {
380 _splitpath(data.cFileName, NULL, NULL, fname, NULL);
387 struct dirent *dirent;
394 while ((dirent = readdir(dir))) {
396 if (dirent->d_name[0] !=
'.') {
397 if (strstr(dirent->d_name, extension.
string()) != NULL) {
398 dot = strrchr(dirent->d_name,
'.');
400 if (strncmp(dot, extension.
string(),
401 strlen(extension.
string())) == 0) {
489 int width,
int height) {
495 int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
496 SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
497 bytes_per_pixel, bytes_per_line);
522 int width,
int height,
523 int bytes_per_pixel,
int bytes_per_line) {
526 bytes_per_pixel, bytes_per_line);
535 tprintf(
"Please call SetImage before SetSourceResolution.\n");
595 Pixa** pixa,
int** blockids,
int** paraids) {
597 pixa, blockids, paraids);
640 bool text_only,
bool raw_image,
641 const int raw_padding,
642 Pixa** pixa,
int** blockids,
651 int component_count = 0;
652 int left, top, right, bottom;
659 &left, &top, &right, &bottom);
665 level, &left, &top, &right, &bottom);
668 if (get_bbox->
Run() &&
671 }
while (page_it->
Next(level));
673 Boxa* boxa = boxaCreate(component_count);
675 *pixa = pixaCreate(component_count);
676 if (blockids != NULL)
677 *blockids =
new int[component_count];
679 *paraids =
new int[component_count];
683 int component_index = 0;
686 if (get_bbox->
Run() &&
688 Box* lbox = boxCreate(left, top, right - left, bottom - top);
689 boxaAddBox(boxa, lbox, L_INSERT);
698 pixaAddPix(*pixa, pix, L_INSERT);
699 pixaAddBox(*pixa, lbox, L_CLONE);
701 if (paraids != NULL) {
702 (*paraids)[component_index] = paraid;
706 if (blockids != NULL) {
707 (*blockids)[component_index] = blockid;
715 }
while (page_it->
Next(level));
732 FILE *fp = fopen(filename,
"wb");
734 int width = pixGetWidth(pix);
735 int height = pixGetHeight(pix);
736 l_uint32* data = pixGetData(pix);
737 fprintf(fp,
"P5 %d %d 255\n", width, height);
738 for (
int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
739 for (
int x = 0; x < width; ++x) {
740 uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255;
741 fwrite(&b, 1, 1, fp);
747 #ifndef NO_CUBE_BUILD
755 Boxa* boxa_words, Pixa* pixa_words,
756 const FCOORD& reskew, Pix* page_pix,
758 int block_count = boxaGetCount(boxa_blocks);
759 ASSERT_HOST(block_count == pixaGetCount(pixa_blocks));
761 for (
int i = 0; i < block_count; ++i) {
762 Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE);
763 pixDisplayWrite(pix, 1);
765 int word_count = boxaGetCount(boxa_words);
766 ASSERT_HOST(word_count == pixaGetCount(pixa_words));
770 page_res_it.
forward(), ++pr_word) {
776 if (choice != NULL) {
780 filename +=
"unclassified";
781 snprintf(numbuf, 32,
"%03d", pr_word);
785 Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE);
786 pixWrite(filename.
string(), pix, IFF_TIFF_G4);
792 #endif // NO_CUBE_BUILD
873 #ifndef GRAPHICS_DISABLED
875 #endif // GRAPHICS_DISABLED
890 fclose(training_output_file);
893 bool wait_for_text =
true;
910 tprintf(
"Please call SetImage before attempting recognition.");
927 while (page_res_it.
word() != NULL) {
931 page_res_it.
row()->
row, word_res);
960 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
962 const char* retry_config,
963 int timeout_millisec,
965 int tessedit_page_number) {
966 if (!flist && !buf)
return false;
967 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
972 buf->
split(
'\n', &lines);
973 if (lines.
empty())
return false;
977 for (
int i = 0; i < page; i++) {
979 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
991 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
993 if (page >= lines.
size())
break;
994 snprintf(pagename,
sizeof(pagename),
"%s", lines[page].c_str());
997 Pix *pix = pixRead(pagename);
999 tprintf(
"Image file %s cannot be read!\n", pagename);
1002 tprintf(
"Page %d : %s\n", page, pagename);
1003 bool r =
ProcessPage(pix, page, pagename, retry_config,
1004 timeout_millisec, renderer);
1006 if (!r)
return false;
1007 if (tessedit_page_number >= 0)
break;
1018 bool TessBaseAPI::ProcessPagesMultipageTiff(
const l_uint8 *data,
1021 const char* retry_config,
1022 int timeout_millisec,
1024 int tessedit_page_number) {
1025 #ifndef ANDROID_BUILD
1029 #endif // USE_OPENCL
1030 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1033 if (tessedit_page_number >= 0)
1034 page = tessedit_page_number;
1036 if ( od.selectedDeviceIsOpenCL() ) {
1038 od.pixReadMemTiffCl(data, size, page) :
1039 od.pixReadTiffCl(filename, page);
1041 #endif // USE_OPENCL
1043 pixReadMemFromMultipageTiff(data, size, &offset) :
1044 pixReadFromMultipageTiff(filename, &offset);
1047 #endif // USE_OPENCL
1048 if (pix == NULL)
break;
1049 tprintf(
"Page %d\n", page + 1);
1053 bool r =
ProcessPage(pix, page, filename, retry_config,
1054 timeout_millisec, renderer);
1056 if (!r)
return false;
1057 if (tessedit_page_number >= 0)
break;
1069 int timeout_millisec,
1095 const char* retry_config,
1096 int timeout_millisec,
1099 bool stdInput = !strcmp(filename,
"stdin") || !strcmp(filename,
"-");
1102 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1103 tprintf(
"ERROR: cin to binary: %s", strerror(errno));
1108 return ProcessPagesFileList(stdin, NULL, retry_config,
1109 timeout_millisec, renderer,
1117 const l_uint8 *data = NULL;
1119 buf.
assign((std::istreambuf_iterator<char>(std::cin)),
1120 (std::istreambuf_iterator<char>()));
1121 data =
reinterpret_cast<const l_uint8 *
>(buf.data());
1126 int r = (stdInput) ?
1127 findFileFormatBuffer(data, &format) :
1128 findFileFormat(filename, &format);
1131 if (r != 0 || format == IFF_UNKNOWN) {
1136 std::ifstream t(filename);
1137 std::string u((std::istreambuf_iterator<char>(t)),
1138 std::istreambuf_iterator<char>());
1141 return ProcessPagesFileList(NULL, &s, retry_config,
1142 timeout_millisec, renderer,
1147 bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1148 format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1149 format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1150 format == IFF_TIFF_ZIP);
1155 pix = (stdInput) ? pixReadMem(data, buf.size()) : pixRead(filename);
1169 ProcessPagesMultipageTiff(data, buf.size(),
filename, retry_config,
1170 timeout_millisec, renderer,
1173 timeout_millisec, renderer);
1179 if (!r || (renderer && !renderer->EndDocument())) {
1187 const char* retry_config,
int timeout_millisec,
1192 bool failed =
false;
1205 }
else if (timeout_millisec > 0) {
1220 #ifndef ANDROID_BUILD
1222 pixWrite(
"tessinput.tif", page_pix, IFF_TIFF_G4);
1223 #endif // ANDROID_BUILD
1226 if (failed && retry_config != NULL && retry_config[0] !=
'\0') {
1239 if (renderer && !failed) {
1240 failed = !renderer->
AddImage(
this);
1307 char* result =
new char[text.
length() + 1];
1321 it->
Orientation(&orientation, &writing_direction, &textline_order,
1334 static void AddBaselineCoordsTohOCR(
const PageIterator *it,
1339 hocr_str->
add_str_int(
"; textangle ", 360 - orientation * 90);
1343 int left, top, right, bottom;
1344 it->BoundingBox(level, &left, &top, &right, &bottom);
1348 if (!it->Baseline(level, &x1, &y1, &x2, &y2))
1366 p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1367 p0 = y1 -
static_cast<double>(p1 * x1);
1369 hocr_str->
add_str_double(
"; baseline ", round(p1 * 1000.0) / 1000.0);
1373 static void AddIdTohOCR(
STRING* hocr_str,
const std::string base,
int num1,
1375 const size_t BUFSIZE = 64;
1376 char id_buffer[BUFSIZE];
1378 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d_%d", base.c_str(), num1, num2);
1380 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d", base.c_str(), num1);
1382 id_buffer[BUFSIZE - 1] =
'\0';
1383 *hocr_str +=
" id='";
1384 *hocr_str += id_buffer;
1390 int left, top, right, bottom;
1391 it->BoundingBox(level, &left, &top, &right, &bottom);
1400 AddBaselineCoordsTohOCR(it, level, hocr_str);
1402 float row_height, descenders, ascenders;
1403 it->RowAttributes(&row_height, &descenders, &ascenders);
1414 int left, top, right, bottom;
1415 it->BoundingBox(level, &left, &top, &right, &bottom);
1446 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1447 int page_id = page_number + 1;
1448 bool para_is_ltr =
true;
1449 const char* paragraph_lang = NULL;
1450 bool font_info =
false;
1462 wchar_t *uni16_str =
new WCHAR[str16_len];
1464 uni16_str, str16_len);
1465 int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, 0,
1467 char *utf8_str =
new char[utf8_len];
1468 WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1469 utf8_len, NULL, NULL);
1475 hocr_str +=
" <div class='ocr_page'";
1476 AddIdTohOCR(&hocr_str,
"page", page_id, -1);
1477 hocr_str +=
" title='image \"";
1481 hocr_str +=
"unknown";
1500 hocr_str +=
" <div class='ocr_carea'";
1501 AddIdTohOCR(&hocr_str,
"block", page_id, bcnt);
1502 AddBoxTohOCR(res_it,
RIL_BLOCK, &hocr_str);
1505 hocr_str +=
"\n <p class='ocr_par'";
1508 hocr_str +=
" dir='rtl'";
1510 AddIdTohOCR(&hocr_str,
"par", page_id, pcnt);
1512 if (paragraph_lang) {
1513 hocr_str +=
" lang='";
1514 hocr_str += paragraph_lang;
1517 AddBoxTohOCR(res_it,
RIL_PARA, &hocr_str);
1520 hocr_str +=
"\n <span class='ocr_line'";
1521 AddIdTohOCR(&hocr_str,
"line", page_id, lcnt);
1526 hocr_str +=
"<span class='ocrx_word'";
1527 AddIdTohOCR(&hocr_str,
"word", page_id, wcnt);
1528 int left, top, right, bottom;
1529 bool bold, italic, underlined, monospace, serif, smallcaps;
1530 int pointsize, font_id;
1531 const char *font_name;
1534 &monospace, &serif, &smallcaps,
1535 &pointsize, &font_id);
1543 hocr_str +=
"; x_font ";
1550 if (lang && (!paragraph_lang || strcmp(lang, paragraph_lang))) {
1551 hocr_str +=
" lang='";
1558 if (!para_is_ltr) hocr_str +=
" dir='ltr'";
1561 if (para_is_ltr) hocr_str +=
" dir='rtl'";
1572 if (bold) hocr_str +=
"<strong>";
1573 if (italic) hocr_str +=
"<em>";
1576 if (grapheme && grapheme[0] != 0) {
1582 if (italic) hocr_str +=
"</em>";
1583 if (bold) hocr_str +=
"</strong>";
1584 hocr_str +=
"</span> ";
1587 if (last_word_in_line) {
1588 hocr_str +=
"\n </span>";
1591 if (last_word_in_para) {
1592 hocr_str +=
"\n </p>\n";
1596 if (last_word_in_block) {
1597 hocr_str +=
" </div>\n";
1601 hocr_str +=
" </div>\n";
1603 char *ret =
new char[hocr_str.
length() + 1];
1604 strcpy(ret, hocr_str.
string());
1617 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1618 int page_id = page_number + 1;
1622 int page_num = page_id, block_num = 0, par_num = 0, line_num = 0,
1634 tsv_str +=
"\t-1\t\n";
1645 block_num++, par_num = 0, line_num = 0, word_num = 0;
1651 AddBoxToTSV(res_it,
RIL_BLOCK, &tsv_str);
1652 tsv_str +=
"\t-1\t\n";
1655 par_num++, line_num = 0, word_num = 0;
1661 AddBoxToTSV(res_it,
RIL_PARA, &tsv_str);
1662 tsv_str +=
"\t-1\t\n";
1665 line_num++, word_num = 0;
1672 tsv_str +=
"\t-1\t\n";
1676 int left, top, right, bottom;
1677 bool bold, italic, underlined, monospace, serif, smallcaps;
1678 int pointsize, font_id;
1679 const char* font_name;
1683 &serif, &smallcaps, &pointsize, &font_id);
1710 char* ret =
new char[tsv_str.
length() + 1];
1711 strcpy(ret, tsv_str.
string());
1753 char* result =
new char[total_length];
1755 int output_length = 0;
1758 int left, top, right, bottom;
1763 for (
int i = 0; text[i] !=
'\0'; ++i) {
1767 snprintf(result + output_length, total_length - output_length,
1768 "%s %d %d %d %d %d\n",
1771 output_length += strlen(result + output_length);
1774 if (output_length + kMaxBytesPerLine > total_length)
1788 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1792 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1804 bool tilde_crunch_written =
false;
1805 bool last_char_was_newline =
true;
1806 bool last_char_was_tilde =
false;
1810 char* result =
new char[total_length];
1818 (!tilde_crunch_written ||
1829 last_char_was_tilde =
false;
1831 if (!last_char_was_tilde) {
1833 last_char_was_tilde =
true;
1835 tilde_crunch_written =
true;
1836 last_char_was_newline =
false;
1841 tilde_crunch_written =
false;
1845 int length = lengths.
length();
1849 if (last_char_was_tilde &&
1850 word->
word->
space() == 0 && wordstr[offset] ==
' ') {
1854 offset = lengths[i++];
1856 if (i < length && wordstr[offset] != 0) {
1857 if (!last_char_was_newline)
1860 last_char_was_newline =
false;
1861 for (; i < length; offset += lengths[i++]) {
1862 if (wordstr[offset] ==
' ' ||
1865 last_char_was_tilde =
true;
1869 UNICHAR ch(wordstr + offset, lengths[i]);
1871 for (
int j = 0;
kUniChs[j] != 0; ++j) {
1877 if (uni_ch <= 0xff) {
1878 *ptr++ =
static_cast<char>(uni_ch);
1879 last_char_was_tilde =
false;
1882 last_char_was_tilde =
true;
1891 tilde_crunch_written =
false;
1892 last_char_was_newline =
true;
1893 last_char_was_tilde =
false;
1922 *orient_deg = orient_id * 90;
1925 const char* script =
1928 *script_name = script;
1945 const char* script_name;
1954 const int kOsdBufsize = 255;
1955 char* osd_buf =
new char[kOsdBufsize];
1956 snprintf(osd_buf, kOsdBufsize,
1958 "Orientation in degrees: %d\n"
1960 "Orientation confidence: %.2f\n"
1962 "Script confidence: %.2f\n",
1963 page_number, orient_deg, rotate, orient_conf, script_name,
1972 if (!conf)
return 0;
1975 while (*pt >= 0) sum += *pt++;
1976 if (pt != conf) sum /= pt - conf;
1991 int* conf =
new int[n_word+1];
1996 int w_conf =
static_cast<int>(100 + 5 * choice->
certainty());
1998 if (w_conf < 0) w_conf = 0;
1999 if (w_conf > 100) w_conf = 100;
2000 conf[n_word++] = w_conf;
2019 bool success =
true;
2025 tprintf(
"Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
2030 if (word_res != NULL) {
2038 for (t = 0; text[t] !=
'\0'; ++t) {
2039 if (text[t] ==
'\n' || text[t] ==
' ')
2041 while (wordstr[w] !=
'\0' && wordstr[w] ==
' ')
2043 if (text[t] != wordstr[w])
2047 if (text[t] !=
'\0' || wordstr[w] !=
'\0') {
2055 if (pr_it.
word() == NULL)
2058 word_res = pr_it.
word();
2176 if (x2 <= x1) x2 = x1 + 1;
2178 *out_slope =
static_cast<float>(y2 - y1) / (x2 - x1);
2179 *out_offset =
static_cast<int>(y1 - *out_slope * x1);
2182 int left, top, right, bottom;
2192 *out_offset += bottom -
MAX(left_y, right_y);
2195 *out_slope = -*out_slope;
2222 for (
int i = 0; i < num_subs; ++i) {
2236 tprintf(
"Please call Init before attempting to set an image.");
2260 tprintf(
"Warning. Invalid resolution %d dpi. Using %d instead.\n",
2286 tprintf(
"Estimated resolution %d out of range! Corrected to %d\n",
2296 tprintf(
"Please call SetImage before attempting recognition.");
2312 tprintf(
"Image too large: (%d, %d)\n",
2335 NULL, 0, NULL, NULL,
false) == 0) {
2340 tprintf(
"Warning: Auto orientation and script detection requested,"
2341 " but osd language failed to load\n");
2390 int total_length = 2;
2391 int total_blobs = 0;
2397 if (choice != NULL) {
2398 total_blobs += choice->
length() + 2;
2406 if (blob_count != NULL)
2407 *blob_count = total_blobs;
2408 return total_length;
2445 bool** vertical_writing) {
2446 delete[] *block_orientation;
2447 *block_orientation = NULL;
2448 delete[] *vertical_writing;
2449 *vertical_writing = NULL;
2452 block_it.move_to_first();
2454 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2455 if (!block_it.data()->poly_block()->IsText()) {
2461 tprintf(
"WARNING: Found no blocks\n");
2464 *block_orientation =
new int[num_blocks];
2465 *vertical_writing =
new bool[num_blocks];
2466 block_it.move_to_first();
2468 for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2469 block_it.forward()) {
2470 if (!block_it.data()->poly_block()->IsText()) {
2473 FCOORD re_rotation = block_it.data()->re_rotation();
2474 float re_theta = re_rotation.
angle();
2475 FCOORD classify_rotation = block_it.data()->classify_rotation();
2476 float classify_theta = classify_rotation.
angle();
2477 double rot_theta = - (re_theta - classify_theta) * 2.0 /
PI;
2478 if (rot_theta < 0) rot_theta += 4;
2479 int num_rotations =
static_cast<int>(rot_theta + 0.5);
2480 (*block_orientation)[i] = num_rotations;
2483 (*vertical_writing)[i] = classify_rotation.
y() != 0.0f;
2513 inT32 xstarts[] = {-32000};
2514 double quad_coeffs[] = {0, 0, baseline};
2519 ascender - (baseline + xheight),
2520 descender - baseline,
2527 int width = pixGetWidth(pix);
2528 int height = pixGetHeight(pix);
2529 BLOCK block(
"a character",
TRUE, 0, 0, 0, 0, width, height);
2536 C_BLOB_IT c_blob_it(list);
2537 if (c_blob_it.empty())
2540 C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2541 for (c_blob_it.forward();
2542 !c_blob_it.at_first();
2543 c_blob_it.forward()) {
2544 C_BLOB *c_blob = c_blob_it.data();
2545 ol_it.add_list_after(c_blob->
out_list());
2558 float x_center = (box.
left() + box.
right()) / 2.0f;
2561 tblob->
Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
2570 float descender,
float ascender,
2571 bool numeric_mode, Pix* pix) {
2598 float best_rating = -100;
2602 BLOB_CHOICE_LIST choices;
2604 BLOB_CHOICE_IT choice_it;
2605 choice_it.set_to_list(&choices);
2606 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2607 choice_it.forward()) {
2608 if (choice_it.data()->rating() > best_rating) {
2609 best_rating = choice_it.data()->rating();
2632 pass1_result =
new PAGE_RES(
false, block_list,
2635 return pass1_result;
2639 int debug_level = 0;
2647 result_it, &models);
2660 length = (len == -1 ? strlen(repr) : len);
2675 static
void add_space(TESS_CHAR_IT* it) {
2676 TESS_CHAR *t =
new TESS_CHAR(0,
" ");
2677 it->add_after_then_move(t);
2681 static float rating_to_cost(
float rating) {
2682 rating = 100 + rating;
2686 if (rating < 0) rating = 0;
2694 static void extract_result(TESS_CHAR_IT* out,
2698 while (page_res_it.word() != NULL) {
2706 int n = strlen(len);
2707 for (
int i = 0; i < n; i++) {
2711 out->add_after_then_move(tc);
2715 page_res_it.forward();
2732 TESS_CHAR_LIST tess_chars;
2733 TESS_CHAR_IT tess_chars_it(&tess_chars);
2734 extract_result(&tess_chars_it, page_res);
2735 tess_chars_it.move_to_first();
2736 int n = tess_chars.length();
2738 *lengths =
new int[n];
2739 *costs =
new float[n];
2745 for (tess_chars_it.mark_cycle_pt();
2746 !tess_chars_it.cycled_list();
2747 tess_chars_it.forward(), i++) {
2749 text_len += (*lengths)[i] = tc->
length;
2750 (*costs)[i] = tc->
cost;
2754 (*y1)[i] = tc->
box.
top();
2756 char *p = *text =
new char[text_len];
2758 tess_chars_it.move_to_first();
2759 for (tess_chars_it.mark_cycle_pt();
2760 !tess_chars_it.cycled_list();
2761 tess_chars_it.forward()) {
2779 int* feature_outline_index) {
2785 &cn_features, &fx_info, &outline_counts);
2790 *num_features = cn_features.
size();
2791 memcpy(int_features, &cn_features[0], *num_features *
sizeof(cn_features[0]));
2793 if (feature_outline_index != NULL) {
2795 for (
int i = 0; i < outline_counts.
size(); ++i) {
2796 while (f < outline_counts[i])
2797 feature_outline_index[f++] = i;
2805 int left,
int top,
int right,
int bottom) {
2806 TBOX box(left, bottom, right, top);
2807 BLOCK_IT b_it(blocks);
2808 for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2809 BLOCK* block = b_it.data();
2813 for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2814 ROW* row = r_it.data();
2818 for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2819 WERD* word = w_it.data();
2830 int num_max_matches,
2833 int* num_matches_returned) {
2834 BLOB_CHOICE_LIST* choices =
new BLOB_CHOICE_LIST;
2836 BLOB_CHOICE_IT choices_it(choices);
2837 int& index = *num_matches_returned;
2839 for (choices_it.mark_cycle_pt();
2840 !choices_it.cycled_list() && index < num_max_matches;
2841 choices_it.forward()) {
2844 ratings[index] = choice->
rating();
2847 *num_matches_returned = index;
2867 #ifndef NO_CUBE_BUILD
2872 #endif // NO_CUBE_BUILD
2878 for (ptr = text; *ptr; ptr++) {
2880 case '<': ret +=
"<";
break;
2881 case '>': ret +=
">";
break;
2882 case '&': ret +=
"&";
break;
2883 case '"': ret +=
""";
break;
2884 case '\'': ret +=
"'";
break;
2885 default: ret += *ptr;
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
const char * kOldVarsFile
OcrEngineMode oem() const
bool tessedit_write_images
BOOL8 flag(WERD_FLAGS mask) const
bool tessedit_train_from_boxes
void * cancel_this
called whenever progress increases
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
void ResetDocumentDictionary()
const char * GetInitLanguagesAsString() const
int GetScaleFactor() const
const int kBytesPer64BitNumber
ImageThresholder * thresholder_
Image thresholding module.
void SetSourceYResolution(int ppi)
int IsValidWord(const char *word)
void SavePixForCrash(int resolution, Pix *pix)
const char * GetUnichar(int unichar_id)
CubeRecoContext * GetCubeRecoContext() const
Orientation and script detection only.
virtual void Run(A1, A2, A3, A4)=0
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
Tesseract * tesseract() const
TESS_LOCAL bool InternalSetImage()
int tessedit_pageseg_mode
ADAPT_TEMPLATES AdaptedTemplates
PageSegMode GetPageSegMode() const
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
Assume a single uniform block of text. (Default.)
void set_unlv_suspects(WERD_RES *word)
void SetInputImage(Pix *pix)
Pix * pix_original() const
void set_pix_grey(Pix *grey_pix)
void SetEquationDetect(EquationDetect *detector)
float Confidence(PageIteratorLevel level) const
double(Dict::* probability_in_context_)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
Probability in context function used by the ngram permuter.
BLOCK_LIST * block_list_
The page layout.
STRING * language_
Last initialized language.
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
void ClearAdaptiveClassifier()
ResultIterator * GetIterator()
int GetSourceYResolution() const
bool GetDoubleVariable(const char *name, double *value) const
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
void CorrectClassifyWords(PAGE_RES *page_res)
int init_tesseract(const char *arg0, const char *textbase, const char *language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector< STRING > *vars_vec, const GenericVector< STRING > *vars_values, bool set_only_init_params)
bool recognition_done_
page_res_ contains recognition data.
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
int InitLangMod(const char *datapath, const char *language)
virtual Pix * GetPixRectThresholds()
bool GetIntVariable(const char *name, int *value) const
static size_t getOpenCLDevice(void **device)
Boxa * GetConnectedComponents(Pixa **cc)
void ExtractFontName(const STRING &filename, STRING *fontname)
ROW_LIST * row_list()
get rows
void BestChoiceToCorrectText()
bool BeginDocument(const char *title)
void SetPageSegMode(PageSegMode mode)
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
int * AllWordConfidences()
TruthCallback * truth_cb_
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
const STRING & unichar_lengths() const
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
static void CatchSignals()
Boxa * GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
const int kNumbersPerBlob
const char * WordRecognitionLanguage() const
Tesseract * osd_tesseract_
For orientation & script detection.
#define MAX_NUM_INT_FEATURES
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
Pix ** mutable_pix_binary()
void set_source_resolution(int ppi)
TESS_LOCAL LTRResultIterator * GetLTRIterator()
int GetScaledEstimatedResolution() const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
void SetBlackAndWhitelist()
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
STRING HOcrEscape(const char *text)
static void DeleteBlockList(BLOCK_LIST *block_list)
TESS_LOCAL int FindLines()
bool GetVariableAsString(const char *name, STRING *val)
CRUNCH_MODE unlv_crunch_mode
tesseract::BoxWord * box_word
TBOX bounding_box() const
const char * string() const
const int kMaxCredibleResolution
bool tessedit_make_boxes_from_boxes
TESS_LOCAL int TextLength(int *blob_count)
bool tessedit_resegment_from_boxes
void SetDictFunc(DictFunc f)
TESS_API int get_best_script(int orientation_id) const
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
TBOX bounding_box() const
const int kBytesPerNumber
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language)
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
bool IsBinary() const
Returns true if the source image is binary.
const char * GetStringVariable(const char *name) const
const int kMinCredibleResolution
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
GenericVector< IntParam * > int_params
bool PTIsTextType(PolyBlockType type)
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
int OrientationIdToValue(const int &id)
const char * get_script_from_script_id(int id) const
void SetSourceResolution(int ppi)
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
void set_min_orientation_margin(double margin)
const TBOX & BlobBox(int index) const
void assign(const char *cstr, int len)
void set_pix_thresholds(Pix *thresholds)
TBOX bounding_box() const
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
float base_line(float xpos) const
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
void SetRectangle(int left, int top, int width, int height)
MutableIterator * GetMutableIterator()
const UNICHARSET & getUnicharset() const
bool classify_bln_numeric_mode
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void LearnWord(const char *fontname, WERD_RES *word)
const char * c_str() const
BLOCK_LIST * FindLinesCreateBlockList()
void SetInputName(const char *name)
const STRING & unichar_string() const
bool interactive_display_mode
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
static TBLOB * MakeTBLOB(Pix *pix)
C_BLOB_LIST * blob_list()
get blobs
TBOX intersection(const TBOX &box) const
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
WERD_RES * restart_page()
bool DetectOS(OSResults *)
int CubeAPITest(Boxa *boxa_blocks, Pixa *pixa_blocks, Boxa *boxa_words, Pixa *pixa_words, const FCOORD &reskew, Pix *page_pix, PAGE_RES *page_res)
const char kTesseractReject
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA * > *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel * > *models)
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
#define TESSERACT_VERSION_STR
PolyBlockType BlockType() const
void ReadConfigFile(const char *filename)
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
bool IsEmpty() const
Return true if no image has been set.
#define PERF_COUNT_SUB(SUB)
PageIterator * AnalyseLayout()
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
int GetSourceYResolution()
Pix * GetThresholdedImage()
const char * id_to_unichar(UNICHAR_ID id) const
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
WERD_CHOICE * prev_word_best_choice_
TESS_CHAR(float _cost, const char *repr, int len=-1)
struct TessResultRenderer TessResultRenderer
virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
EquationDetect * equ_detect_
The equation detector.
virtual bool Next(PageIteratorLevel level)
PAGE_RES * page_res_
The page-level data.
void add_str_int(const char *str, int number)
static const char * Version()
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
FILE * init_recog_training(const STRING &fname)
void Normalize(const BLOCK *block, const FCOORD *rotation, const DENORM *predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift, bool inverse, Pix *pix)
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
static void ExtractFeatures(const TBLOB &blob, bool nonlinear_norm, GenericVector< INT_FEATURE_STRUCT > *bl_features, GenericVector< INT_FEATURE_STRUCT > *cn_features, INT_FX_RESULT_STRUCT *results, GenericVector< int > *outline_cn_counts)
bool tessedit_ambigs_training
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
void delete_data_pointers()
CANCEL_FUNC cancel
for errcode use
virtual Pix * GetPixRectGrey()
C_OUTLINE_LIST * out_list()
Boxa * GetStrips(Pixa **pixa, int **blockids)
static DawgCache * GlobalDawgCache()
virtual bool Next(PageIteratorLevel level)
void InitForAnalysePage()
bool contains_unichar(const char *const unichar_repr) const
GenericVector< BoolParam * > bool_params
const int kMaxBytesPerLine
#define PERF_COUNT_START(FUNCT_NAME)
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
const char * GetDatapath()
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
Tesseract * tesseract_
The underlying data object.
BLOCK_RES * block() const
static void ClearPersistentCache()
void ResetAdaptiveClassifier()
int RecognizeForChopTest(ETEXT_DESC *monitor)
STRING * output_file_
Name used by debug code.
const int kBytesPerBoxFileLine
WERD_CHOICE * best_choice
StrongScriptDirection WordDirection() const
void TidyUp(PAGE_RES *page_res)
bool WriteTRFile(const STRING &filename)
void split(const char c, GenericVector< STRING > *splited)
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
bool major_overlap(const TBOX &box) const
void read_config_file(const char *filename, SetParamConstraint constraint)
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
Tesseract * get_sub_lang(int index) const
void InitAdaptiveClassifier(bool load_pre_trained_templates)
bool textord_equation_detect
Automatic page segmentation, but no OSD, or OCR.
void add_str_double(const char *str, double number)
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
void chomp_string(char *str)
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
void SetFillLatticeFunc(FillLatticeFunc f)
int num_sub_langs() const
GenericVector< DoubleParam * > double_params
char * GetOsdText(int page_number)
bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf)
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
const char * WordFontAttributes(bool *is_bold, bool *is_italic, bool *is_underlined, bool *is_monospace, bool *is_serif, bool *is_smallcaps, int *pointsize, int *font_id) const
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
int IntCastRounded(double x)
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
bool IsValidCharacter(const char *utf8_character)
float angle() const
find angle
char * GetTSVText(int page_number)
char * GetBoxText(int page_number)
const int kBlnBaselineOffset
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
static TESS_LOCAL int TesseractExtractResult(char **text, int **lengths, float **costs, int **x0, int **y0, int **x1, int **y1, PAGE_RES *page_res)
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
bool GetTextDirection(int *out_offset, float *out_slope)
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
bool AddImage(TessBaseAPI *api)
virtual char * GetUTF8Text(PageIteratorLevel level) const
const char * string() const
void SetRectangle(int left, int top, int width, int height)
void SetOutputName(const char *name)
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
bool SetDebugVariable(const char *name, const char *value)
GenericVector< StringParam * > string_params
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
void ReSegmentByClassification(PAGE_RES *page_res)
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
const char * GetInputName()
bool ParagraphIsLtr() const
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
void PrintVariables(FILE *fp) const
int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
char * GetHOCRText(ETEXT_DESC *monitor, int page_number)
int Recognize(ETEXT_DESC *monitor)
Boxa * GetWords(Pixa **pixa)
void pgeditor_main(int width, int height, PAGE_RES *page_res)
int GetThresholdedImageScaleFactor() const
#define BOOL_VAR(name, val, comment)
GenericVector< ParagraphModel * > * paragraph_models_
Pix * GetBinaryImage(PageIteratorLevel level) const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
bool PSM_OSD_ENABLED(int pageseg_mode)
bool Empty(PageIteratorLevel level) const
void signal_exit(int signal_code)
void ReadDebugConfigFile(const char *filename)
const Dawg * GetDawg(int i) const
bool tessedit_resegment_from_line_boxes
Boxa * GetRegions(Pixa **pixa)
void set_deadline_msecs(inT32 deadline_msecs)
void set_pix_original(Pix *original_pix)
tesseract::ParamsVectors * GlobalParams()
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
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)
char * GetUTF8Text(PageIteratorLevel level) const
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
STRING * input_file_
Name used by training code.
double min_orientation_margin
int GetScaledYResolution() const
static void ResetToDefaults(ParamsVectors *member_params)
void extract_edges(Pix *pix, BLOCK *block)
void DumpPGM(const char *filename)
CubeRecoContext * GetCubeRecoContext()
double matcher_good_threshold
virtual TESS_LOCAL void Threshold(Pix **pix)
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
bool SetVariable(const char *name, const char *value)
STRING * datapath_
Current location of tessdata.
UNICHAR_ID unichar_id() const
void set_text(const char *new_text)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
bool GetBoolVariable(const char *name, bool *value) const