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));
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) {
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 1027 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1030 if (tessedit_page_number >= 0)
1031 page = tessedit_page_number;
1032 pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
1033 : pixReadFromMultipageTiff(
filename, &offset);
1034 if (pix == NULL)
break;
1035 tprintf(
"Page %d\n", page + 1);
1040 timeout_millisec, renderer);
1042 if (!r)
return false;
1043 if (tessedit_page_number >= 0)
break;
1055 int timeout_millisec,
1081 const char* retry_config,
1082 int timeout_millisec,
1088 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1089 tprintf(
"ERROR: cin to binary: %s", strerror(errno));
1094 return ProcessPagesFileList(stdin, NULL, retry_config,
1095 timeout_millisec, renderer,
1103 const l_uint8 *data = NULL;
1105 buf.
assign((std::istreambuf_iterator<char>(std::cin)),
1106 (std::istreambuf_iterator<char>()));
1107 data =
reinterpret_cast<const l_uint8 *
>(buf.data());
1112 int r = (stdInput) ?
1113 findFileFormatBuffer(data, &format) :
1117 if (r != 0 || format == IFF_UNKNOWN) {
1123 std::string u((std::istreambuf_iterator<char>(t)),
1124 std::istreambuf_iterator<char>());
1127 return ProcessPagesFileList(NULL, &s, retry_config,
1128 timeout_millisec, renderer,
1133 bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1134 format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1135 format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1136 format == IFF_TIFF_ZIP);
1141 pix = (stdInput) ? pixReadMem(data, buf.size()) : pixRead(
filename);
1155 ProcessPagesMultipageTiff(data, buf.size(),
filename, retry_config,
1156 timeout_millisec, renderer,
1159 timeout_millisec, renderer);
1165 if (!r || (renderer && !renderer->EndDocument())) {
1173 const char* retry_config,
int timeout_millisec,
1178 bool failed =
false;
1191 }
else if (timeout_millisec > 0) {
1206 #ifndef ANDROID_BUILD 1208 pixWrite(
"tessinput.tif", page_pix, IFF_TIFF_G4);
1209 #endif // ANDROID_BUILD 1212 if (failed && retry_config != NULL && retry_config[0] !=
'\0') {
1225 if (renderer && !failed) {
1226 failed = !renderer->
AddImage(
this);
1293 char* result =
new char[text.
length() + 1];
1307 it->
Orientation(&orientation, &writing_direction, &textline_order,
1320 static void AddBaselineCoordsTohOCR(
const PageIterator *it,
1325 hocr_str->
add_str_int(
"; textangle ", 360 - orientation * 90);
1329 int left, top, right, bottom;
1330 it->BoundingBox(level, &left, &top, &right, &bottom);
1334 if (!it->Baseline(level, &x1, &y1, &x2, &y2))
1352 p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1353 p0 = y1 -
static_cast<double>(p1 * x1);
1355 hocr_str->
add_str_double(
"; baseline ", round(p1 * 1000.0) / 1000.0);
1359 static void AddIdTohOCR(
STRING* hocr_str,
const std::string base,
int num1,
1361 const size_t BUFSIZE = 64;
1362 char id_buffer[BUFSIZE];
1364 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d_%d", base.c_str(), num1, num2);
1366 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d", base.c_str(), num1);
1368 id_buffer[BUFSIZE - 1] =
'\0';
1369 *hocr_str +=
" id='";
1370 *hocr_str += id_buffer;
1376 int left, top, right, bottom;
1377 it->BoundingBox(level, &left, &top, &right, &bottom);
1386 AddBaselineCoordsTohOCR(it, level, hocr_str);
1388 float row_height, descenders, ascenders;
1389 it->RowAttributes(&row_height, &descenders, &ascenders);
1400 int left, top, right, bottom;
1401 it->BoundingBox(level, &left, &top, &right, &bottom);
1432 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1433 int page_id = page_number + 1;
1434 bool para_is_ltr =
true;
1435 const char* paragraph_lang = NULL;
1436 bool font_info =
false;
1448 wchar_t *uni16_str =
new WCHAR[str16_len];
1450 uni16_str, str16_len);
1451 int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, 0,
1453 char *utf8_str =
new char[utf8_len];
1454 WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1455 utf8_len, NULL, NULL);
1461 hocr_str +=
" <div class='ocr_page'";
1462 AddIdTohOCR(&hocr_str,
"page", page_id, -1);
1463 hocr_str +=
" title='image \"";
1467 hocr_str +=
"unknown";
1486 hocr_str +=
" <div class='ocr_carea'";
1487 AddIdTohOCR(&hocr_str,
"block", page_id, bcnt);
1488 AddBoxTohOCR(res_it,
RIL_BLOCK, &hocr_str);
1491 hocr_str +=
"\n <p class='ocr_par'";
1494 hocr_str +=
" dir='rtl'";
1496 AddIdTohOCR(&hocr_str,
"par", page_id, pcnt);
1498 if (paragraph_lang) {
1499 hocr_str +=
" lang='";
1500 hocr_str += paragraph_lang;
1503 AddBoxTohOCR(res_it,
RIL_PARA, &hocr_str);
1506 hocr_str +=
"\n <span class='ocr_line'";
1507 AddIdTohOCR(&hocr_str,
"line", page_id, lcnt);
1512 hocr_str +=
"<span class='ocrx_word'";
1513 AddIdTohOCR(&hocr_str,
"word", page_id, wcnt);
1514 int left, top, right, bottom;
1515 bool bold, italic, underlined, monospace, serif, smallcaps;
1516 int pointsize, font_id;
1517 const char *font_name;
1520 &monospace, &serif, &smallcaps,
1521 &pointsize, &font_id);
1529 hocr_str +=
"; x_font ";
1536 if (
lang && (!paragraph_lang || strcmp(
lang, paragraph_lang))) {
1537 hocr_str +=
" lang='";
1544 if (!para_is_ltr) hocr_str +=
" dir='ltr'";
1547 if (para_is_ltr) hocr_str +=
" dir='rtl'";
1558 if (bold) hocr_str +=
"<strong>";
1559 if (italic) hocr_str +=
"<em>";
1562 if (grapheme && grapheme[0] != 0) {
1568 if (italic) hocr_str +=
"</em>";
1569 if (bold) hocr_str +=
"</strong>";
1570 hocr_str +=
"</span> ";
1573 if (last_word_in_line) {
1574 hocr_str +=
"\n </span>";
1577 if (last_word_in_para) {
1578 hocr_str +=
"\n </p>\n";
1582 if (last_word_in_block) {
1583 hocr_str +=
" </div>\n";
1587 hocr_str +=
" </div>\n";
1589 char *ret =
new char[hocr_str.
length() + 1];
1590 strcpy(ret, hocr_str.
string());
1603 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1604 int page_id = page_number + 1;
1608 int page_num = page_id, block_num = 0, par_num = 0, line_num = 0,
1620 tsv_str +=
"\t-1\t\n";
1631 block_num++, par_num = 0, line_num = 0, word_num = 0;
1637 AddBoxToTSV(res_it,
RIL_BLOCK, &tsv_str);
1638 tsv_str +=
"\t-1\t\n";
1641 par_num++, line_num = 0, word_num = 0;
1647 AddBoxToTSV(res_it,
RIL_PARA, &tsv_str);
1648 tsv_str +=
"\t-1\t\n";
1651 line_num++, word_num = 0;
1658 tsv_str +=
"\t-1\t\n";
1662 int left, top, right, bottom;
1663 bool bold, italic, underlined, monospace, serif, smallcaps;
1664 int pointsize, font_id;
1665 const char* font_name;
1669 &serif, &smallcaps, &pointsize, &font_id);
1696 char* ret =
new char[tsv_str.
length() + 1];
1697 strcpy(ret, tsv_str.
string());
1739 char* result =
new char[total_length];
1741 int output_length = 0;
1744 int left, top, right, bottom;
1749 for (
int i = 0; text[i] !=
'\0'; ++i) {
1753 snprintf(result + output_length, total_length - output_length,
1754 "%s %d %d %d %d %d\n",
1757 output_length += strlen(result + output_length);
1774 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1778 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1790 bool tilde_crunch_written =
false;
1791 bool last_char_was_newline =
true;
1792 bool last_char_was_tilde =
false;
1796 char* result =
new char[total_length];
1804 (!tilde_crunch_written ||
1815 last_char_was_tilde =
false;
1817 if (!last_char_was_tilde) {
1819 last_char_was_tilde =
true;
1821 tilde_crunch_written =
true;
1822 last_char_was_newline =
false;
1827 tilde_crunch_written =
false;
1831 int length = lengths.
length();
1835 if (last_char_was_tilde &&
1836 word->
word->
space() == 0 && wordstr[offset] ==
' ') {
1840 offset = lengths[i++];
1842 if (i < length && wordstr[offset] != 0) {
1843 if (!last_char_was_newline)
1846 last_char_was_newline =
false;
1847 for (; i < length; offset += lengths[i++]) {
1848 if (wordstr[offset] ==
' ' ||
1851 last_char_was_tilde =
true;
1855 UNICHAR ch(wordstr + offset, lengths[i]);
1857 for (
int j = 0;
kUniChs[j] != 0; ++j) {
1863 if (uni_ch <= 0xff) {
1864 *ptr++ =
static_cast<char>(uni_ch);
1865 last_char_was_tilde =
false;
1868 last_char_was_tilde =
true;
1877 tilde_crunch_written =
false;
1878 last_char_was_newline =
true;
1879 last_char_was_tilde =
false;
1908 *orient_deg = orient_id * 90;
1911 const char* script =
1914 *script_name = script;
1931 const char* script_name;
1940 const int kOsdBufsize = 255;
1941 char* osd_buf =
new char[kOsdBufsize];
1942 snprintf(osd_buf, kOsdBufsize,
1944 "Orientation in degrees: %d\n" 1946 "Orientation confidence: %.2f\n" 1948 "Script confidence: %.2f\n",
1949 page_number, orient_deg, rotate, orient_conf, script_name,
1958 if (!conf)
return 0;
1961 while (*pt >= 0) sum += *pt++;
1962 if (pt != conf) sum /= pt - conf;
1977 int* conf =
new int[n_word+1];
1982 int w_conf =
static_cast<int>(100 + 5 * choice->
certainty());
1984 if (w_conf < 0) w_conf = 0;
1985 if (w_conf > 100) w_conf = 100;
1986 conf[n_word++] = w_conf;
2005 bool success =
true;
2011 tprintf(
"Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
2016 if (word_res != NULL) {
2024 for (t = 0; text[t] !=
'\0'; ++t) {
2025 if (text[t] ==
'\n' || text[t] ==
' ')
2027 while (wordstr[w] !=
'\0' && wordstr[w] ==
' ')
2029 if (text[t] != wordstr[w])
2033 if (text[t] !=
'\0' || wordstr[w] !=
'\0') {
2041 if (pr_it.
word() == NULL)
2044 word_res = pr_it.
word();
2142 if (x2 <= x1) x2 = x1 + 1;
2144 *out_slope =
static_cast<float>(y2 - y1) / (x2 - x1);
2145 *out_offset =
static_cast<int>(y1 - *out_slope * x1);
2148 int left, top, right, bottom;
2158 *out_offset += bottom -
MAX(left_y, right_y);
2161 *out_slope = -*out_slope;
2188 for (
int i = 0; i < num_subs; ++i) {
2202 tprintf(
"Please call Init before attempting to set an image.");
2226 tprintf(
"Warning. Invalid resolution %d dpi. Using %d instead.\n",
2252 tprintf(
"Estimated resolution %d out of range! Corrected to %d\n",
2262 tprintf(
"Please call SetImage before attempting recognition.");
2278 tprintf(
"Image too large: (%d, %d)\n",
2301 NULL, 0, NULL, NULL,
false) == 0) {
2306 tprintf(
"Warning: Auto orientation and script detection requested," 2307 " but osd language failed to load\n");
2356 int total_length = 2;
2357 int total_blobs = 0;
2363 if (choice != NULL) {
2364 total_blobs += choice->
length() + 2;
2372 if (blob_count != NULL)
2373 *blob_count = total_blobs;
2374 return total_length;
2411 bool** vertical_writing) {
2412 delete[] *block_orientation;
2413 *block_orientation = NULL;
2414 delete[] *vertical_writing;
2415 *vertical_writing = NULL;
2418 block_it.move_to_first();
2420 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2421 if (!block_it.data()->poly_block()->IsText()) {
2427 tprintf(
"WARNING: Found no blocks\n");
2430 *block_orientation =
new int[num_blocks];
2431 *vertical_writing =
new bool[num_blocks];
2432 block_it.move_to_first();
2434 for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2435 block_it.forward()) {
2436 if (!block_it.data()->poly_block()->IsText()) {
2439 FCOORD re_rotation = block_it.data()->re_rotation();
2440 float re_theta = re_rotation.
angle();
2441 FCOORD classify_rotation = block_it.data()->classify_rotation();
2442 float classify_theta = classify_rotation.
angle();
2443 double rot_theta = - (re_theta - classify_theta) * 2.0 /
PI;
2444 if (rot_theta < 0) rot_theta += 4;
2445 int num_rotations =
static_cast<int>(rot_theta + 0.5);
2446 (*block_orientation)[i] = num_rotations;
2449 (*vertical_writing)[i] = classify_rotation.
y() != 0.0f;
2479 inT32 xstarts[] = {-32000};
2480 double quad_coeffs[] = {0, 0,
baseline};
2493 int width = pixGetWidth(pix);
2494 int height = pixGetHeight(pix);
2495 BLOCK block(
"a character",
TRUE, 0, 0, 0, 0, width, height);
2502 C_BLOB_IT c_blob_it(list);
2503 if (c_blob_it.empty())
2506 C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2507 for (c_blob_it.forward();
2508 !c_blob_it.at_first();
2509 c_blob_it.forward()) {
2510 C_BLOB *c_blob = c_blob_it.data();
2511 ol_it.add_list_after(c_blob->
out_list());
2524 float x_center = (box.
left() + box.
right()) / 2.0f;
2536 float descender,
float ascender,
2537 bool numeric_mode, Pix* pix) {
2564 float best_rating = -100;
2568 BLOB_CHOICE_LIST choices;
2570 BLOB_CHOICE_IT choice_it;
2571 choice_it.set_to_list(&choices);
2572 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2573 choice_it.forward()) {
2574 if (choice_it.data()->rating() > best_rating) {
2575 best_rating = choice_it.data()->rating();
2598 pass1_result =
new PAGE_RES(
false, block_list,
2601 return pass1_result;
2605 int debug_level = 0;
2613 result_it, &models);
2626 length = (len == -1 ? strlen(repr) : len);
2641 static void add_space(TESS_CHAR_IT* it) {
2642 TESS_CHAR *t =
new TESS_CHAR(0,
" ");
2643 it->add_after_then_move(t);
2647 static float rating_to_cost(
float rating) {
2648 rating = 100 + rating;
2652 if (rating < 0) rating = 0;
2660 static void extract_result(TESS_CHAR_IT* out,
2664 while (page_res_it.word() != NULL) {
2672 int n = strlen(len);
2673 for (
int i = 0; i < n; i++) {
2677 out->add_after_then_move(tc);
2681 page_res_it.forward();
2698 TESS_CHAR_LIST tess_chars;
2699 TESS_CHAR_IT tess_chars_it(&tess_chars);
2700 extract_result(&tess_chars_it, page_res);
2701 tess_chars_it.move_to_first();
2702 int n = tess_chars.length();
2704 *lengths =
new int[n];
2705 *costs =
new float[n];
2711 for (tess_chars_it.mark_cycle_pt();
2712 !tess_chars_it.cycled_list();
2713 tess_chars_it.forward(), i++) {
2715 text_len += (*lengths)[i] = tc->
length;
2716 (*costs)[i] = tc->
cost;
2720 (*y1)[i] = tc->
box.
top();
2722 char *p = *text =
new char[text_len];
2724 tess_chars_it.move_to_first();
2725 for (tess_chars_it.mark_cycle_pt();
2726 !tess_chars_it.cycled_list();
2727 tess_chars_it.forward()) {
2745 int* feature_outline_index) {
2751 &cn_features, &fx_info, &outline_counts);
2756 *num_features = cn_features.
size();
2757 memcpy(int_features, &cn_features[0], *num_features *
sizeof(cn_features[0]));
2759 if (feature_outline_index != NULL) {
2761 for (
int i = 0; i < outline_counts.
size(); ++i) {
2762 while (f < outline_counts[i])
2763 feature_outline_index[f++] = i;
2771 int left,
int top,
int right,
int bottom) {
2772 TBOX box(left, bottom, right, top);
2773 BLOCK_IT b_it(blocks);
2774 for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2775 BLOCK* block = b_it.data();
2779 for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2780 ROW* row = r_it.data();
2784 for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2785 WERD* word = w_it.data();
2796 int num_max_matches,
2799 int* num_matches_returned) {
2800 BLOB_CHOICE_LIST* choices =
new BLOB_CHOICE_LIST;
2802 BLOB_CHOICE_IT choices_it(choices);
2803 int& index = *num_matches_returned;
2805 for (choices_it.mark_cycle_pt();
2806 !choices_it.cycled_list() && index < num_max_matches;
2807 choices_it.forward()) {
2810 ratings[index] = choice->
rating();
2813 *num_matches_returned = index;
2833 #ifndef NO_CUBE_BUILD 2838 #endif // NO_CUBE_BUILD 2844 for (ptr = text; *ptr; ptr++) {
2846 case '<': ret +=
"<";
break;
2847 case '>': ret +=
">";
break;
2848 case '&': ret +=
"&";
break;
2849 case '"': ret +=
""";
break;
2850 case '\'': ret +=
"'";
break;
2851 default: ret += *ptr;
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Pix * GetBinaryImage(PageIteratorLevel level) const
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
int IsValidWord(const char *word)
bool PSM_OSD_ENABLED(int pageseg_mode)
TESS_API int get_best_script(int orientation_id) const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
#define PERF_COUNT_SUB(SUB)
double matcher_good_threshold
bool SetDebugVariable(const char *name, const char *value)
const int kBytesPer64BitNumber
const char * GetInitLanguagesAsString() const
int Recognize(ETEXT_DESC *monitor)
CRUNCH_MODE unlv_crunch_mode
CANCEL_FUNC cancel
for errcode use
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
const int kBlnBaselineOffset
void ReadConfigFile(const char *filename)
TBOX bounding_box() const
bool AddImage(TessBaseAPI *api)
GenericVector< BoolParam * > bool_params
Boxa * GetRegions(Pixa **pixa)
int IntCastRounded(double x)
void set_pix_thresholds(Pix *thresholds)
tesseract::ParamsVectors * GlobalParams()
void ReadDebugConfigFile(const char *filename)
int OrientationIdToValue(const int &id)
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
int tessedit_pageseg_mode
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA *> *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel *> *models)
PageSegMode GetPageSegMode() const
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
bool BeginDocument(const char *title)
ADAPT_TEMPLATES AdaptedTemplates
bool tessedit_resegment_from_line_boxes
void split(const char c, GenericVector< STRING > *splited)
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language)
float base_line(float xpos) const
int * AllWordConfidences()
const char * GetUnichar(int unichar_id)
bool TESS_API contains_unichar(const char *const unichar_repr) const
const STRING & unichar_string() const
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)
bool interactive_display_mode
virtual TESS_LOCAL void Threshold(Pix **pix)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
const char kTesseractReject
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
const char * GetInputName()
virtual bool Next(PageIteratorLevel level)
STRING * output_file_
Name used by debug code.
void pgeditor_main(int width, int height, PAGE_RES *page_res)
Orientation and script detection only.
ResultIterator * GetIterator()
Boxa * GetWords(Pixa **pixa)
char * GetBoxText(int page_number)
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
void set_pix_grey(Pix *grey_pix)
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
void SetSourceResolution(int ppi)
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
static size_t getOpenCLDevice(void **device)
void SetFillLatticeFunc(FillLatticeFunc f)
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
const char * get_script_from_script_id(int id) const
ROW_LIST * row_list()
get rows
bool IsValidCharacter(const char *utf8_character)
float Confidence(PageIteratorLevel level) const
bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf)
bool ParagraphIsLtr() const
void SetInputImage(Pix *pix)
StrongScriptDirection WordDirection() const
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
const UNICHARSET & getUnicharset() const
Boxa * GetConnectedComponents(Pixa **cc)
GenericVector< DoubleParam * > double_params
PAGE_RES * page_res_
The page-level data.
Pix ** mutable_pix_binary()
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
void LearnWord(const char *fontname, WERD_RES *word)
void SetRectangle(int left, int top, int width, int height)
const char * string() const
static void CatchSignals()
bool SetVariable(const char *name, const char *value)
C_OUTLINE_LIST * out_list()
void read_config_file(const char *filename, SetParamConstraint constraint)
int GetScaledYResolution() const
Boxa * GetStrips(Pixa **pixa, int **blockids)
const int kNumbersPerBlob
TESS_CHAR(float _cost, const char *repr, int len=-1)
GenericVector< StringParam * > string_params
virtual char * GetUTF8Text(PageIteratorLevel level) const
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
TESS_LOCAL bool InternalSetImage()
bool GetBoolVariable(const char *name, bool *value) const
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
WERD_RES * restart_page()
WERD_CHOICE * best_choice
TBOX bounding_box() const
bool tessedit_train_from_boxes
void SetOutputName(const char *name)
int GetSourceYResolution()
void add_str_double(const char *str, double number)
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
double min_orientation_margin
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
void SetSourceYResolution(int ppi)
const char * GetStringVariable(const char *name) const
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
UNICHAR_ID unichar_id() const
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
void add_str_int(const char *str, int number)
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
Automatic page segmentation, but no OSD, or OCR.
bool PTIsTextType(PolyBlockType type)
CubeRecoContext * GetCubeRecoContext() const
void SetEquationDetect(EquationDetect *detector)
void set_source_resolution(int ppi)
void SetRectangle(int left, int top, int width, int height)
virtual void Run(A1, A2, A3, A4)=0
GenericVector< IntParam * > int_params
int GetSourceYResolution() const
PolyBlockType BlockType() const
OcrEngineMode oem() const
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
bool DetectOS(OSResults *)
Boxa * GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
static void ResetToDefaults(ParamsVectors *member_params)
BLOCK_LIST * FindLinesCreateBlockList()
int CubeAPITest(Boxa *boxa_blocks, Pixa *pixa_blocks, Boxa *boxa_words, Pixa *pixa_words, const FCOORD &reskew, Pix *page_pix, PAGE_RES *page_res)
void * cancel_this
called whenever progress increases
tesseract::BoxWord * box_word
bool textord_equation_detect
int InitLangMod(const char *datapath, const char *language)
const char * string() const
CubeRecoContext * GetCubeRecoContext()
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
Tesseract * osd_tesseract_
For orientation & script detection.
bool tessedit_ambigs_training
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
void SetBlackAndWhitelist()
#define MAX_NUM_INT_FEATURES
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
TESS_LOCAL int FindLines()
BOOL8 flag(WERD_FLAGS mask) const
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
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.
bool GetVariableAsString(const char *name, STRING *val)
void assign(const char *cstr, int len)
const int kMaxBytesPerLine
void CorrectClassifyWords(PAGE_RES *page_res)
const int kMaxCredibleResolution
GenericVector< ParagraphModel * > * paragraph_models_
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
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)
virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
bool GetIntVariable(const char *name, int *value) const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
char * GetOsdText(int page_number)
bool Empty(PageIteratorLevel level) const
bool tessedit_make_boxes_from_boxes
void TidyUp(PAGE_RES *page_res)
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
virtual bool Next(PageIteratorLevel level)
const char * c_str() const
EquationDetect * equ_detect_
The equation detector.
void extract_edges(Pix *pix, BLOCK *block)
#define PERF_COUNT_START(FUNCT_NAME)
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
void ResetDocumentDictionary()
const int kMinCredibleResolution
void signal_exit(int signal_code)
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
virtual Pix * GetPixRectGrey()
void ResetAdaptiveClassifier()
void set_min_orientation_margin(double margin)
void delete_data_pointers()
int RecognizeForChopTest(ETEXT_DESC *monitor)
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
PageIterator * AnalyseLayout()
BLOCK_RES * block() const
TESS_LOCAL LTRResultIterator * GetLTRIterator()
bool recognition_done_
page_res_ contains recognition data.
char * GetUTF8Text(PageIteratorLevel level) const
void ExtractFontName(const STRING &filename, STRING *fontname)
void SetDictFunc(DictFunc f)
static void ClearPersistentCache()
UNICHAR_ID TESS_API unichar_to_id(const char *const unichar_repr) const
const char * kOldVarsFile
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
TruthCallback * truth_cb_
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
static TBLOB * MakeTBLOB(Pix *pix)
FILE * init_recog_training(const STRING &fname)
virtual Pix * GetPixRectThresholds()
STRING * language_
Last initialized language.
bool IsEmpty() const
Return true if no image has been set.
bool WriteTRFile(const STRING &filename)
void SetInputName(const char *name)
const TBOX & BlobBox(int index) const
bool tessedit_write_images
int GetScaleFactor() const
bool tessedit_resegment_from_boxes
void InitForAnalysePage()
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
Pix * GetThresholdedImage()
STRING HOcrEscape(const char *text)
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
MutableIterator * GetMutableIterator()
void ClearAdaptiveClassifier()
char * GetHOCRText(ETEXT_DESC *monitor, int page_number)
Assume a single uniform block of text. (Default.)
WERD_CHOICE * prev_word_best_choice_
void set_pix_original(Pix *original_pix)
ImageThresholder * thresholder_
Image thresholding module.
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
TESS_LOCAL int TextLength(int *blob_count)
static TESS_LOCAL int TesseractExtractResult(char **text, int **lengths, float **costs, int **x0, int **y0, int **x1, int **y1, PAGE_RES *page_res)
Pix * pix_original() const
struct TessResultRenderer TessResultRenderer
static DawgCache * GlobalDawgCache()
bool major_overlap(const TBOX &box) const
const Dawg * GetDawg(int i) const
const int kBytesPerBoxFileLine
const STRING & unichar_lengths() const
Tesseract * tesseract() const
bool classify_bln_numeric_mode
void PrintVariables(FILE *fp) const
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Tesseract * get_sub_lang(int index) const
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
void ReSegmentByClassification(PAGE_RES *page_res)
Tesseract * tesseract_
The underlying data object.
const int kBytesPerNumber
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
TBOX intersection(const TBOX &box) const
int GetScaledEstimatedResolution() const
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
C_BLOB_LIST * blob_list()
get blobs
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)
void DumpPGM(const char *filename)
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
const char * WordRecognitionLanguage() const
void InitAdaptiveClassifier(bool load_pre_trained_templates)
void SetPageSegMode(PageSegMode mode)
const char * id_to_unichar(UNICHAR_ID id) const
bool IsBinary() const
Returns true if the source image is binary.
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
#define TESSERACT_VERSION_STR
#define BOOL_VAR(name, val, comment)
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
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)
static const char * Version()
void set_deadline_msecs(inT32 deadline_msecs)
void chomp_string(char *str)
float angle() const
find angle
STRING * input_file_
Name used by training code.
void set_unlv_suspects(WERD_RES *word)
int num_sub_langs() const
int GetThresholdedImageScaleFactor() const
void BestChoiceToCorrectText()
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
TBOX bounding_box() const
BLOCK_LIST * block_list_
The page layout.
STRING * datapath_
Current location of tessdata.
char * GetTSVText(int page_number)
bool GetDoubleVariable(const char *name, double *value) const
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 SavePixForCrash(int resolution, Pix *pix)
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
const char * GetDatapath()
bool GetTextDirection(int *out_offset, float *out_slope)
void set_text(const char *new_text)
static void DeleteBlockList(BLOCK_LIST *block_list)