22 #include "config_auto.h" 32 #undef __STRICT_ANSI__ 40 #include <sys/types.h> 51 #include "allheaders.h" 106 static void addAvailableLanguages(
const STRING &datadir,
const STRING &base,
109 const STRING base2 = (base.
string()[0] ==
'\0') ? base : base +
"/";
110 const size_t extlen =
sizeof(kTrainedDataSuffix);
112 WIN32_FIND_DATA data;
113 HANDLE handle = FindFirstFile((datadir + base2 +
"*").
string(), &data);
114 if (handle != INVALID_HANDLE_VALUE) {
117 char *name = data.cFileName;
119 if (name[0] !=
'.') {
120 if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
121 FILE_ATTRIBUTE_DIRECTORY) {
122 addAvailableLanguages(datadir, base2 + name, langs);
124 size_t len = strlen(name);
125 if (len > extlen && name[len - extlen] ==
'.' &&
126 strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
127 name[len - extlen] =
'\0';
132 result = FindNextFile(handle, &data);
137 DIR* dir = opendir((datadir + base).
string());
140 while ((de = readdir(dir))) {
141 char *name = de->d_name;
143 if (name[0] !=
'.') {
145 if (stat((datadir + base2 + name).
string(), &st) == 0 &&
146 (st.st_mode & S_IFDIR) == S_IFDIR) {
147 addAvailableLanguages(datadir, base2 + name, langs);
149 size_t len = strlen(name);
150 if (len > extlen && name[len - extlen] ==
'.' &&
151 strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
152 name[len - extlen] =
'\0';
164 : tesseract_(nullptr),
165 osd_tesseract_(nullptr),
166 equ_detect_(nullptr),
171 thresholder_(nullptr),
172 paragraph_models_(nullptr),
173 block_list_(nullptr),
175 input_file_(nullptr),
176 output_file_(nullptr),
180 recognition_done_(false),
208 #if USE_DEVICE_SELECTION 214 #if USE_DEVICE_SELECTION 215 ds_device device = OpenclDevice::getDeviceSelection();
216 if (device.type == DS_DEVICE_OPENCL_DEVICE) {
217 *data =
new cl_device_id;
218 memcpy(*data, &device.oclDeviceID,
sizeof(cl_device_id));
219 return sizeof(cl_device_id);
234 struct sigaction action;
235 memset(&action, 0,
sizeof(action));
237 action.sa_flags = SA_RESETHAND;
238 sigaction(SIGSEGV, &action, NULL);
239 sigaction(SIGFPE, &action, NULL);
240 sigaction(SIGBUS, &action, NULL);
243 tprintf(
"CatchSignals has no non-linux implementation!\n");
279 IntParam *p = ParamUtils::FindParam<IntParam>(
281 if (p == NULL)
return false;
282 *value = (int32_t)(*p);
287 BoolParam *p = ParamUtils::FindParam<BoolParam>(
289 if (p == NULL)
return false;
290 *value = (
BOOL8)(*p);
295 StringParam *p = ParamUtils::FindParam<StringParam>(
297 return (p != NULL) ? p->
string() : NULL;
301 DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
303 if (p == NULL)
return false;
304 *value = (double)(*p);
330 bool set_only_non_debug_params) {
331 return Init(datapath, 0, language, oem, configs, configs_size, vars_vec,
332 vars_values, set_only_non_debug_params,
nullptr);
342 bool set_only_non_debug_params,
FileReader reader) {
345 if (language ==
nullptr) language =
"eng";
346 STRING datapath = data_size == 0 ? data : language;
365 bool reset_classifier =
true;
367 reset_classifier =
false;
369 if (reader !=
nullptr)
reader_ = reader;
371 if (data_size != 0) {
377 language,
oem, configs, configs_size, vars_vec, vars_values,
378 set_only_non_debug_params, &mgr) != 0) {
399 if (reset_classifier) {
431 for (
int i = 0; i < num_subs; ++i)
523 int width,
int height) {
524 if (
tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize)
529 int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
530 SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
531 bytes_per_pixel, bytes_per_line);
556 int width,
int height,
557 int bytes_per_pixel,
int bytes_per_line) {
560 bytes_per_pixel, bytes_per_line);
569 tprintf(
"Please call SetImage before SetSourceResolution.\n");
630 Pixa** pixa,
int** blockids,
int** paraids) {
632 pixa, blockids, paraids);
675 bool text_only,
bool raw_image,
676 const int raw_padding,
677 Pixa** pixa,
int** blockids,
686 int component_count = 0;
687 int left, top, right, bottom;
694 &left, &top, &right, &bottom);
700 level, &left, &top, &right, &bottom);
703 if (get_bbox->
Run() &&
706 }
while (page_it->
Next(level));
708 Boxa* boxa = boxaCreate(component_count);
710 *pixa = pixaCreate(component_count);
711 if (blockids != NULL)
712 *blockids =
new int[component_count];
714 *paraids =
new int[component_count];
718 int component_index = 0;
721 if (get_bbox->
Run() &&
723 Box* lbox = boxCreate(left, top, right - left, bottom - top);
724 boxaAddBox(boxa, lbox, L_INSERT);
733 pixaAddPix(*pixa, pix, L_INSERT);
734 pixaAddBox(*pixa, lbox, L_CLONE);
736 if (paraids != NULL) {
737 (*paraids)[component_index] = paraid;
741 if (blockids != NULL) {
742 (*blockids)[component_index] = blockid;
750 }
while (page_it->
Next(level));
846 #ifndef GRAPHICS_DISABLED 848 #endif // GRAPHICS_DISABLED 863 fclose(training_output_file);
866 bool wait_for_text =
true;
883 tprintf(
"Please call SetImage before attempting recognition.\n");
900 while (page_res_it.
word() != NULL) {
904 page_res_it.
row()->
row, word_res);
933 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
935 const char* retry_config,
936 int timeout_millisec,
938 int tessedit_page_number) {
939 if (!flist && !buf)
return false;
940 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
945 buf->
split(
'\n', &lines);
946 if (lines.
empty())
return false;
950 for (
int i = 0; i < page; i++) {
952 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
964 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
966 if (page >= lines.
size())
break;
967 snprintf(pagename,
sizeof(pagename),
"%s", lines[page].c_str());
970 Pix *pix = pixRead(pagename);
972 tprintf(
"Image file %s cannot be read!\n", pagename);
975 tprintf(
"Page %d : %s\n", page, pagename);
976 bool r =
ProcessPage(pix, page, pagename, retry_config,
977 timeout_millisec, renderer);
979 if (!r)
return false;
980 if (tessedit_page_number >= 0)
break;
991 bool TessBaseAPI::ProcessPagesMultipageTiff(
const l_uint8 *data,
994 const char* retry_config,
995 int timeout_millisec,
997 int tessedit_page_number) {
998 #ifndef ANDROID_BUILD 1000 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1003 if (tessedit_page_number >= 0)
1004 page = tessedit_page_number;
1005 pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
1006 : pixReadFromMultipageTiff(filename, &offset);
1007 if (pix == NULL)
break;
1008 tprintf(
"Page %d\n", page + 1);
1010 snprintf(page_str, kMaxIntSize - 1,
"%d", page);
1012 bool r =
ProcessPage(pix, page, filename, retry_config,
1013 timeout_millisec, renderer);
1015 if (!r)
return false;
1016 if (tessedit_page_number >= 0)
break;
1028 int timeout_millisec,
1054 const char* retry_config,
1055 int timeout_millisec,
1058 bool stdInput = !strcmp(filename,
"stdin") || !strcmp(filename,
"-");
1061 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1062 tprintf(
"ERROR: cin to binary: %s", strerror(errno));
1067 return ProcessPagesFileList(stdin, NULL, retry_config,
1068 timeout_millisec, renderer,
1076 const l_uint8 *data = NULL;
1078 buf.
assign((std::istreambuf_iterator<char>(std::cin)),
1079 (std::istreambuf_iterator<char>()));
1080 data =
reinterpret_cast<const l_uint8 *
>(buf.data());
1085 int r = (stdInput) ?
1086 findFileFormatBuffer(data, &format) :
1087 findFileFormat(filename, &format);
1090 if (r != 0 || format == IFF_UNKNOWN) {
1095 std::ifstream t(filename);
1096 std::string u((std::istreambuf_iterator<char>(t)),
1097 std::istreambuf_iterator<char>());
1100 return ProcessPagesFileList(NULL, &s, retry_config,
1101 timeout_millisec, renderer,
1106 bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1107 format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1108 format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1109 format == IFF_TIFF_ZIP);
1114 pix = (stdInput) ? pixReadMem(data, buf.size()) : pixRead(filename);
1128 ProcessPagesMultipageTiff(data, buf.size(),
filename, retry_config,
1129 timeout_millisec, renderer,
1132 timeout_millisec, renderer);
1138 if (!r || (renderer && !renderer->EndDocument())) {
1146 const char* retry_config,
int timeout_millisec,
1151 bool failed =
false;
1164 }
else if (timeout_millisec > 0) {
1179 #ifndef ANDROID_BUILD 1181 pixWrite(
"tessinput.tif", page_pix, IFF_TIFF_G4);
1182 #endif // ANDROID_BUILD 1185 if (failed && retry_config != NULL && retry_config[0] !=
'\0') {
1187 FILE* fp = fopen(kOldVarsFile,
"wb");
1198 if (renderer && !failed) {
1199 failed = !renderer->
AddImage(
this);
1263 text += para_text.get();
1265 char* result =
new char[text.
length() + 1];
1279 it->
Orientation(&orientation, &writing_direction, &textline_order,
1292 static void AddBaselineCoordsTohOCR(
const PageIterator *it,
1297 hocr_str->
add_str_int(
"; textangle ", 360 - orientation * 90);
1301 int left, top, right, bottom;
1302 it->
BoundingBox(level, &left, &top, &right, &bottom);
1306 if (!it->
Baseline(level, &x1, &y1, &x2, &y2))
1324 p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1325 p0 = y1 -
static_cast<double>(p1 * x1);
1327 hocr_str->
add_str_double(
"; baseline ", round(p1 * 1000.0) / 1000.0);
1331 static void AddIdTohOCR(
STRING* hocr_str,
const std::string base,
int num1,
1333 const size_t BUFSIZE = 64;
1334 char id_buffer[BUFSIZE];
1336 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d_%d", base.c_str(), num1, num2);
1338 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d", base.c_str(), num1);
1340 id_buffer[BUFSIZE - 1] =
'\0';
1341 *hocr_str +=
" id='";
1342 *hocr_str += id_buffer;
1348 int left, top, right, bottom;
1349 it->
BoundingBox(level, &left, &top, &right, &bottom);
1358 AddBaselineCoordsTohOCR(it, level, hocr_str);
1360 float row_height, descenders, ascenders;
1372 int left, top, right, bottom;
1373 it->
BoundingBox(level, &left, &top, &right, &bottom);
1406 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1407 int page_id = page_number + 1;
1408 bool para_is_ltr =
true;
1409 const char* paragraph_lang = NULL;
1410 bool font_info =
false;
1422 wchar_t *uni16_str =
new WCHAR[str16_len];
1424 uni16_str, str16_len);
1425 int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, 0,
1427 char *utf8_str =
new char[utf8_len];
1428 WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1429 utf8_len, NULL, NULL);
1435 hocr_str +=
" <div class='ocr_page'";
1436 AddIdTohOCR(&hocr_str,
"page", page_id, -1);
1437 hocr_str +=
" title='image \"";
1441 hocr_str +=
"unknown";
1460 hocr_str +=
" <div class='ocr_carea'";
1461 AddIdTohOCR(&hocr_str,
"block", page_id, bcnt);
1462 AddBoxTohOCR(res_it,
RIL_BLOCK, &hocr_str);
1465 hocr_str +=
"\n <p class='ocr_par'";
1468 hocr_str +=
" dir='rtl'";
1470 AddIdTohOCR(&hocr_str,
"par", page_id, pcnt);
1472 if (paragraph_lang) {
1473 hocr_str +=
" lang='";
1474 hocr_str += paragraph_lang;
1477 AddBoxTohOCR(res_it,
RIL_PARA, &hocr_str);
1480 hocr_str +=
"\n <span class='ocr_line'";
1481 AddIdTohOCR(&hocr_str,
"line", page_id, lcnt);
1486 hocr_str +=
"<span class='ocrx_word'";
1487 AddIdTohOCR(&hocr_str,
"word", page_id, wcnt);
1488 int left, top, right, bottom;
1489 bool bold, italic, underlined, monospace, serif, smallcaps;
1490 int pointsize, font_id;
1491 const char *font_name;
1494 &monospace, &serif, &smallcaps,
1495 &pointsize, &font_id);
1503 hocr_str +=
"; x_font ";
1510 if (lang && (!paragraph_lang || strcmp(lang, paragraph_lang))) {
1511 hocr_str +=
" lang='";
1518 if (!para_is_ltr) hocr_str +=
" dir='ltr'";
1521 if (para_is_ltr) hocr_str +=
" dir='rtl'";
1532 if (bold) hocr_str +=
"<strong>";
1533 if (italic) hocr_str +=
"<em>";
1535 const std::unique_ptr<const char[]> grapheme(
1537 if (grapheme && grapheme[0] != 0) {
1542 if (italic) hocr_str +=
"</em>";
1543 if (bold) hocr_str +=
"</strong>";
1544 hocr_str +=
"</span> ";
1547 if (last_word_in_line) {
1548 hocr_str +=
"\n </span>";
1551 if (last_word_in_para) {
1552 hocr_str +=
"\n </p>\n";
1556 if (last_word_in_block) {
1557 hocr_str +=
" </div>\n";
1561 hocr_str +=
" </div>\n";
1563 char *ret =
new char[hocr_str.
length() + 1];
1564 strcpy(ret, hocr_str.
string());
1578 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1579 int page_id = page_number + 1;
1583 int page_num = page_id, block_num = 0, par_num = 0, line_num = 0,
1595 tsv_str +=
"\t-1\t\n";
1606 block_num++, par_num = 0, line_num = 0, word_num = 0;
1612 AddBoxToTSV(res_it,
RIL_BLOCK, &tsv_str);
1613 tsv_str +=
"\t-1\t\n";
1616 par_num++, line_num = 0, word_num = 0;
1622 AddBoxToTSV(res_it,
RIL_PARA, &tsv_str);
1623 tsv_str +=
"\t-1\t\n";
1626 line_num++, word_num = 0;
1633 tsv_str +=
"\t-1\t\n";
1637 int left, top, right, bottom;
1666 char* ret =
new char[tsv_str.
length() + 1];
1667 strcpy(ret, tsv_str.
string());
1708 int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
1710 char* result =
new char[total_length];
1712 int output_length = 0;
1715 int left, top, right, bottom;
1717 const std::unique_ptr<
char[]> text(
1721 for (
int i = 0; text[i] !=
'\0'; ++i) {
1725 snprintf(result + output_length, total_length - output_length,
1726 "%s %d %d %d %d %d\n", text.get(), left,
image_height_ - bottom,
1728 output_length += strlen(result + output_length);
1730 if (output_length + kMaxBytesPerLine > total_length)
1744 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1748 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1760 bool tilde_crunch_written =
false;
1761 bool last_char_was_newline =
true;
1762 bool last_char_was_tilde =
false;
1766 char* result =
new char[total_length];
1774 (!tilde_crunch_written ||
1785 last_char_was_tilde =
false;
1787 if (!last_char_was_tilde) {
1789 last_char_was_tilde =
true;
1791 tilde_crunch_written =
true;
1792 last_char_was_newline =
false;
1797 tilde_crunch_written =
false;
1801 int length = lengths.
length();
1805 if (last_char_was_tilde &&
1806 word->
word->
space() == 0 && wordstr[offset] ==
' ') {
1810 offset = lengths[i++];
1812 if (i < length && wordstr[offset] != 0) {
1813 if (!last_char_was_newline)
1816 last_char_was_newline =
false;
1817 for (; i < length; offset += lengths[i++]) {
1818 if (wordstr[offset] ==
' ' ||
1819 wordstr[offset] == kTesseractReject) {
1821 last_char_was_tilde =
true;
1824 *ptr++ = kUNLVSuspect;
1825 UNICHAR ch(wordstr + offset, lengths[i]);
1827 for (
int j = 0; kUniChs[j] != 0; ++j) {
1828 if (kUniChs[j] == uni_ch) {
1829 uni_ch = kLatinChs[j];
1833 if (uni_ch <= 0xff) {
1834 *ptr++ =
static_cast<char>(uni_ch);
1835 last_char_was_tilde =
false;
1838 last_char_was_tilde =
true;
1847 tilde_crunch_written =
false;
1848 last_char_was_newline =
true;
1849 last_char_was_tilde =
false;
1867 const char** script_name,
1868 float* script_conf) {
1879 if (orient_deg) *orient_deg = orient_id * 90;
1884 *script_name = script;
1900 const char* script_name;
1910 const int kOsdBufsize = 255;
1911 char* osd_buf =
new char[kOsdBufsize];
1912 snprintf(osd_buf, kOsdBufsize,
1914 "Orientation in degrees: %d\n" 1916 "Orientation confidence: %.2f\n" 1918 "Script confidence: %.2f\n",
1919 page_number, orient_deg, rotate, orient_conf, script_name,
1928 if (!conf)
return 0;
1931 while (*pt >= 0) sum += *pt++;
1932 if (pt != conf) sum /= pt - conf;
1947 int* conf =
new int[n_word+1];
1952 int w_conf =
static_cast<int>(100 + 5 * choice->
certainty());
1954 if (w_conf < 0) w_conf = 0;
1955 if (w_conf > 100) w_conf = 100;
1956 conf[n_word++] = w_conf;
1975 bool success =
true;
1979 const std::unique_ptr<const char[]> text(
GetUTF8Text());
1981 tprintf(
"Trying to adapt \"%s\" to \"%s\"\n", text.get(), wordstr);
1986 if (word_res != NULL) {
1994 for (t = 0; text[t] !=
'\0'; ++t) {
1995 if (text[t] ==
'\n' || text[t] ==
' ')
1997 while (wordstr[w] ==
' ') ++w;
1998 if (text[t] != wordstr[w])
2002 if (text[t] !=
'\0' || wordstr[w] !=
'\0') {
2010 if (pr_it.
word() == NULL)
2013 word_res = pr_it.
word();
2109 if (x2 <= x1) x2 = x1 + 1;
2111 *out_slope =
static_cast<float>(y2 - y1) / (x2 - x1);
2112 *out_offset =
static_cast<int>(y1 - *out_slope * x1);
2115 int left, top, right, bottom;
2125 *out_offset += bottom -
MAX(left_y, right_y);
2128 *out_slope = -*out_slope;
2155 for (
int i = 0; i < num_subs; ++i) {
2169 tprintf(
"Please call Init before attempting to set an image.\n");
2193 tprintf(
"Warning. Invalid resolution %d dpi. Using %d instead.\n", y_res,
2219 tprintf(
"Estimated resolution %d out of range! Corrected to %d\n",
2230 tprintf(
"Please call SetImage before attempting recognition.\n");
2254 tprintf(
"Warning: Could not set equation detector\n");
2263 osd_tess ==
nullptr) {
2270 tprintf(
"Warning: Auto orientation and script detection requested," 2271 " but data path is undefined\n");
2276 nullptr, 0,
nullptr,
nullptr,
2277 false, &mgr) == 0) {
2282 tprintf(
"Warning: Auto orientation and script detection requested," 2283 " but osd language failed to load\n");
2332 int total_length = 2;
2333 int total_blobs = 0;
2339 if (choice != NULL) {
2340 total_blobs += choice->
length() + 2;
2348 if (blob_count != NULL)
2349 *blob_count = total_blobs;
2350 return total_length;
2389 bool** vertical_writing) {
2390 delete[] *block_orientation;
2391 *block_orientation = NULL;
2392 delete[] *vertical_writing;
2393 *vertical_writing = NULL;
2396 block_it.move_to_first();
2398 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2399 if (!block_it.data()->poly_block()->IsText()) {
2405 tprintf(
"WARNING: Found no blocks\n");
2408 *block_orientation =
new int[num_blocks];
2409 *vertical_writing =
new bool[num_blocks];
2410 block_it.move_to_first();
2412 for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2413 block_it.forward()) {
2414 if (!block_it.data()->poly_block()->IsText()) {
2417 FCOORD re_rotation = block_it.data()->re_rotation();
2418 float re_theta = re_rotation.
angle();
2419 FCOORD classify_rotation = block_it.data()->classify_rotation();
2420 float classify_theta = classify_rotation.
angle();
2421 double rot_theta = - (re_theta - classify_theta) * 2.0 /
PI;
2422 if (rot_theta < 0) rot_theta += 4;
2423 int num_rotations =
static_cast<int>(rot_theta + 0.5);
2424 (*block_orientation)[i] = num_rotations;
2427 (*vertical_writing)[i] = classify_rotation.
y() != 0.0f;
2457 int32_t xstarts[] = {-32000};
2458 double quad_coeffs[] = {0, 0, baseline};
2463 ascender - (baseline + xheight),
2464 descender - baseline,
2471 int width = pixGetWidth(pix);
2472 int height = pixGetHeight(pix);
2473 BLOCK block(
"a character",
TRUE, 0, 0, 0, 0, width, height);
2480 C_BLOB_IT c_blob_it(list);
2481 if (c_blob_it.empty())
2484 C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2485 for (c_blob_it.forward();
2486 !c_blob_it.at_first();
2487 c_blob_it.forward()) {
2488 C_BLOB *c_blob = c_blob_it.data();
2489 ol_it.add_list_after(c_blob->
out_list());
2502 float x_center = (box.
left() + box.
right()) / 2.0f;
2505 tblob->
Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
2514 float descender,
float ascender,
2515 bool numeric_mode, Pix* pix) {
2542 float best_rating = -100;
2546 BLOB_CHOICE_LIST choices;
2548 BLOB_CHOICE_IT choice_it;
2549 choice_it.set_to_list(&choices);
2550 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2551 choice_it.forward()) {
2552 if (choice_it.data()->rating() > best_rating) {
2553 best_rating = choice_it.data()->rating();
2576 pass1_result =
new PAGE_RES(
false, block_list,
2579 return pass1_result;
2583 int debug_level = 0;
2591 result_it, &models);
2603 TESS_CHAR(
float _cost,
const char *repr,
int len = -1) : cost(_cost) {
2604 length = (len == -1 ? strlen(repr) : len);
2605 unicode_repr =
new char[length + 1];
2606 strncpy(unicode_repr, repr, length);
2612 delete [] unicode_repr;
2619 static void add_space(TESS_CHAR_IT* it) {
2621 it->add_after_then_move(t);
2625 static float rating_to_cost(
float rating) {
2626 rating = 100 + rating;
2630 if (rating < 0) rating = 0;
2638 static void extract_result(TESS_CHAR_IT* out,
2642 while (page_res_it.
word() != NULL) {
2650 int n = strlen(len);
2651 for (
int i = 0; i < n; i++) {
2655 out->add_after_then_move(tc);
2676 TESS_CHAR_LIST tess_chars;
2677 TESS_CHAR_IT tess_chars_it(&tess_chars);
2678 extract_result(&tess_chars_it, page_res);
2679 tess_chars_it.move_to_first();
2680 int n = tess_chars.length();
2682 *lengths =
new int[n];
2683 *costs =
new float[n];
2689 for (tess_chars_it.mark_cycle_pt();
2690 !tess_chars_it.cycled_list();
2691 tess_chars_it.forward(), i++) {
2693 text_len += (*lengths)[i] = tc->
length;
2694 (*costs)[i] = tc->
cost;
2698 (*y1)[i] = tc->
box.
top();
2700 char *p = *text =
new char[text_len];
2702 tess_chars_it.move_to_first();
2703 for (tess_chars_it.mark_cycle_pt();
2704 !tess_chars_it.cycled_list();
2705 tess_chars_it.forward()) {
2723 int* feature_outline_index) {
2729 &cn_features, &fx_info, &outline_counts);
2734 *num_features = cn_features.
size();
2735 memcpy(int_features, &cn_features[0], *num_features *
sizeof(cn_features[0]));
2737 if (feature_outline_index != NULL) {
2739 for (
int i = 0; i < outline_counts.
size(); ++i) {
2740 while (f < outline_counts[i])
2741 feature_outline_index[f++] = i;
2749 int left,
int top,
int right,
int bottom) {
2750 TBOX box(left, bottom, right, top);
2751 BLOCK_IT b_it(blocks);
2752 for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2753 BLOCK* block = b_it.data();
2757 for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2758 ROW* row = r_it.data();
2762 for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2763 WERD* word = w_it.data();
2774 int num_max_matches,
2777 int* num_matches_returned) {
2778 BLOB_CHOICE_LIST* choices =
new BLOB_CHOICE_LIST;
2780 BLOB_CHOICE_IT choices_it(choices);
2781 int& index = *num_matches_returned;
2783 for (choices_it.mark_cycle_pt();
2784 !choices_it.cycled_list() && index < num_max_matches;
2785 choices_it.forward()) {
2788 ratings[index] = choice->
rating();
2791 *num_matches_returned = index;
2815 for (ptr = text; *ptr; ptr++) {
2817 case '<': ret +=
"<";
break;
2818 case '>': ret +=
">";
break;
2819 case '&': ret +=
"&";
break;
2820 case '"': ret +=
""";
break;
2821 case '\'': ret +=
"'";
break;
2822 default: ret += *ptr;
void signal_exit(int signal_code)
const char * kOldVarsFile
Dict & getDict() override
const char * GetUnichar(int unichar_id)
float Confidence(PageIteratorLevel level) const
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
GenericVector< DoubleParam * > double_params
float angle() const
find angle
void SetFillLatticeFunc(FillLatticeFunc f)
virtual Pix * GetPixRectGrey()
bool PTIsTextType(PolyBlockType type)
const char * WordRecognitionLanguage() const
ADAPT_TEMPLATES AdaptedTemplates
float base_line(float xpos) const
const char * string() const
void SetEquationDetect(EquationDetect *detector)
void SetRectangle(int left, int top, int width, int height)
WERD_CHOICE * best_choice
C_BLOB_LIST * blob_list()
get blobs
PageIterator * AnalyseLayout()
void InitForAnalysePage()
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA *> *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel *> *models)
char * GetOsdText(int page_number)
void SetRectangle(int left, int top, int width, int height)
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
const int kMaxBytesPerLine
bool textord_equation_detect
bool tessedit_train_from_boxes
constexpr int kMinCredibleResolution
char * GetTSVText(int page_number)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
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)
double min_orientation_margin
bool GetTextDirection(int *out_offset, float *out_slope)
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
Tesseract * osd_tesseract_
For orientation & script detection.
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
void SetBlackAndWhitelist()
static TESS_LOCAL int TesseractExtractResult(char **text, int **lengths, float **costs, int **x0, int **y0, int **x1, int **y1, PAGE_RES *page_res)
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
int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
void delete_data_pointers()
void InitAdaptiveClassifier(TessdataManager *mgr)
PolyBlockType BlockType() const
Boxa * GetRegions(Pixa **pixa)
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
#define PERF_COUNT_START(FUNCT_NAME)
int GetScaledYResolution() const
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
bool tessedit_train_line_recognizer
GenericVector< IntParam * > int_params
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
void split(const char c, GenericVector< STRING > *splited)
void assign(const char *cstr, int len)
GenericVector< ParagraphModel * > * paragraph_models_
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)
static void ResetToDefaults(ParamsVectors *member_params)
Tesseract * get_sub_lang(int index) const
STRING * input_file_
Name used by training code.
void * cancel_this
called whenever progress increases
void ExtractFontName(const STRING &filename, STRING *fontname)
void ReSegmentByClassification(PAGE_RES *page_res)
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
int InitLangMod(const char *datapath, const char *language)
Tesseract * tesseract_
The underlying data object.
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
BOOL8 flag(WERD_FLAGS mask) const
EquationDetect * equ_detect_
The equation detector.
bool tessedit_ambigs_training
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
void add_str_double(const char *str, double number)
void LearnWord(const char *fontname, WERD_RES *word)
int IsValidWord(const char *word)
MutableIterator * GetMutableIterator()
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
int Recognize(ETEXT_DESC *monitor)
void SetSourceResolution(int ppi)
void SetPageSegMode(PageSegMode mode)
int OrientationIdToValue(const int &id)
char * GetUTF8Text(PageIteratorLevel level) const
virtual bool Next(PageIteratorLevel level)
void add_str_int(const char *str, int number)
const TBOX & BlobBox(int index) const
void CorrectClassifyWords(PAGE_RES *page_res)
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
bool DetectOS(OSResults *)
TESS_LOCAL LTRResultIterator * GetLTRIterator()
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
bool recognition_done_
page_res_ contains recognition data.
void set_unlv_suspects(WERD_RES *word)
FileReader reader_
Reads files from any filesystem.
STRING HOcrEscape(const char *text)
int GetThresholdedImageScaleFactor() const
bool tessedit_make_boxes_from_boxes
C_OUTLINE_LIST * out_list()
bool GetDoubleVariable(const char *name, double *value) const
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
const char * GetDatapath()
FILE * init_recog_training(const STRING &fname)
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
const STRING & unichar_lengths() const
virtual Pix * GetPixRectThresholds()
STRING * language_
Last initialized language.
virtual char * GetUTF8Text(PageIteratorLevel level) const
bool WriteTRFile(const STRING &filename)
bool IsEmpty() const
Return true if no image has been set.
void ResetAdaptiveClassifier()
Assume a single uniform block of text. (Default.)
void extract_edges(Pix *pix, BLOCK *block)
bool IsValidCharacter(const char *utf8_character)
OcrEngineMode oem() const
Tesseract * tesseract() const
PageSegMode GetPageSegMode() const
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
void SavePixForCrash(int resolution, Pix *pix)
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, TessdataManager *mgr)
const int kBytesPerNumber
bool SetDebugVariable(const char *name, const char *value)
void set_deadline_msecs(int32_t deadline_msecs)
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)
#define BOOL_VAR(name, val, comment)
UNICHAR_ID unichar_id() const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
void set_pix_original(Pix *original_pix)
const char * GetInputName()
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
const int kBytesPerBoxFileLine
TruthCallback * truth_cb_
STRING * output_file_
Name used by debug code.
void chomp_string(char *str)
void pgeditor_main(int width, int height, PAGE_RES *page_res)
GenericVector< BoolParam * > bool_params
TBOX bounding_box() const
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
bool IsBinary() const
Returns true if the source image is binary.
#define ELISTIZE(CLASSNAME)
virtual TESS_LOCAL bool Threshold(Pix **pix)
void BestChoiceToCorrectText()
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
CRUNCH_MODE unlv_crunch_mode
void SetInputName(const char *name)
bool tessedit_write_images
ROW_LIST * row_list()
get rows
void SetDictFunc(DictFunc f)
int RecognizeForChopTest(ETEXT_DESC *monitor)
void PrintVariables(FILE *fp) const
const int kBytesPer64BitNumber
bool tessedit_resegment_from_line_boxes
void ClearAdaptiveClassifier()
bool interactive_display_mode
static size_t getOpenCLDevice(void **device)
const STRING & unichar_string() const
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
double matcher_good_threshold
void set_min_orientation_margin(double margin)
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
ImageThresholder * thresholder_
Image thresholding module.
TESS_LOCAL int TextLength(int *blob_count)
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
Pix * pix_original() const
Orientation and script detection only.
void SetInputImage(Pix *pix)
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
bool LoadMemBuffer(const char *name, const char *data, int size)
PAGE_RES * page_res_
The page-level data.
tesseract::BoxWord * box_word
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
bool classify_bln_numeric_mode
void set_pix_grey(Pix *grey_pix)
GenericVector< StringParam * > string_params
WERD_CHOICE * prev_word_best_choice_
static DawgCache * GlobalDawgCache()
#define PERF_COUNT_SUB(SUB)
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
#define ELISTIZEH(CLASSNAME)
TESS_LOCAL bool InternalSetImage()
WERD_RES * restart_page()
bool PSM_OSD_ENABLED(int pageseg_mode)
bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf)
BLOCK_LIST * block_list_
The page layout.
STRING * datapath_
Current location of tessdata.
Boxa * GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
int GetSourceYResolution()
Pix * GetBinaryImage(PageIteratorLevel level) const
char * GetBoxText(int page_number)
Boxa * GetConnectedComponents(Pixa **cc)
Pix * GetThresholdedImage()
static const char * Version()
void set_source_resolution(int ppi)
bool Empty(PageIteratorLevel level) const
BLOCK_LIST * FindLinesCreateBlockList()
int num_sub_langs() const
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
const int kNumbersPerBlob
bool GetBoolVariable(const char *name, bool *value) const
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language, TessdataManager *mgr)
const Dawg * GetDawg(int i) const
int * AllWordConfidences()
const char * c_str() const
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
int GetScaledEstimatedResolution() const
CANCEL_FUNC cancel
for errcode use
const char * string() const
const UNICHARSET & getUnicharset() const
TBOX bounding_box() const
void SetOutputName(const char *name)
void RowAttributes(float *row_height, float *descenders, float *ascenders) const
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
static void DeleteBlockList(BLOCK_LIST *block_list)
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
bool AddImage(TessBaseAPI *api)
const char * GetStringVariable(const char *name) const
void set_pix_thresholds(Pix *thresholds)
TESS_LOCAL int FindLines()
const char * id_to_unichar(UNICHAR_ID id) const
int tessedit_pageseg_mode
Boxa * GetStrips(Pixa **pixa, int **blockids)
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
Boxa * GetWords(Pixa **pixa)
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
int IntCastRounded(double x)
tesseract::ParamsVectors * GlobalParams()
bool contains_unichar(const char *const unichar_repr) const
constexpr int kMaxCredibleResolution
BLOCK_RES * block() const
virtual void Run(A1, A2, A3, A4)=0
static void ClearPersistentCache()
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
bool major_overlap(const TBOX &box) const
Automatic page segmentation, but no OSD, or OCR.
ResultIterator * GetIterator()
const char * GetInitLanguagesAsString() 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.
const char kTesseractReject
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
void set_text(const char *new_text)
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
void ReadConfigFile(const char *filename)
const int kBlnBaselineOffset
void SetSourceYResolution(int ppi)
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
void ReadDebugConfigFile(const char *filename)
bool GetVariableAsString(const char *name, STRING *val)
bool BeginDocument(const char *title)
TBOX intersection(const TBOX &box) const
const char * get_script_from_script_id(int id) const
static TBLOB * MakeTBLOB(Pix *pix)
void TrainLineRecognizer(const STRING &input_imagename, const STRING &output_basename, BLOCK_LIST *block_list)
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
StrongScriptDirection WordDirection() const
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
bool GetIntVariable(const char *name, int *value) const
TBOX bounding_box() const
void TidyUp(PAGE_RES *page_res)
void ResetDocumentDictionary()
Pix ** mutable_pix_binary()
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
TESS_API int get_best_script(int orientation_id) const
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
virtual bool Next(PageIteratorLevel level)
static void CatchSignals()
bool SetVariable(const char *name, const char *value)
char * GetHOCRText(ETEXT_DESC *monitor, int page_number)
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
void read_config_file(const char *filename, SetParamConstraint constraint)
TESS_CHAR(float _cost, const char *repr, int len=-1)
int GetScaleFactor() const
int GetSourceYResolution() const
bool tessedit_resegment_from_boxes
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
#define MAX_NUM_INT_FEATURES
bool ParagraphIsLtr() const
virtual bool ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
Returns false on error.