22 #include "config_auto.h" 34 #undef __STRICT_ANSI__ 42 #include <sys/types.h> 53 #include "allheaders.h" 108 static void addAvailableLanguages(
const STRING &datadir,
const STRING &base,
111 const STRING base2 = (base.
string()[0] ==
'\0') ? base : base +
"/";
112 const size_t extlen =
sizeof(kTrainedDataSuffix);
114 WIN32_FIND_DATA data;
115 HANDLE handle = FindFirstFile((datadir + base2 +
"*").
string(), &data);
116 if (handle != INVALID_HANDLE_VALUE) {
119 char *name = data.cFileName;
121 if (name[0] !=
'.') {
122 if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
123 FILE_ATTRIBUTE_DIRECTORY) {
124 addAvailableLanguages(datadir, base2 + name, langs);
126 size_t len = strlen(name);
127 if (len > extlen && name[len - extlen] ==
'.' &&
128 strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
129 name[len - extlen] =
'\0';
134 result = FindNextFile(handle, &data);
139 DIR* dir = opendir((datadir + base).
string());
142 while ((de = readdir(dir))) {
143 char *name = de->d_name;
145 if (name[0] !=
'.') {
147 if (stat((datadir + base2 + name).
string(), &st) == 0 &&
148 (st.st_mode & S_IFDIR) == S_IFDIR) {
149 addAvailableLanguages(datadir, base2 + name, langs);
151 size_t len = strlen(name);
152 if (len > extlen && name[len - extlen] ==
'.' &&
153 strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
154 name[len - extlen] =
'\0';
166 : tesseract_(nullptr),
167 osd_tesseract_(nullptr),
168 equ_detect_(nullptr),
173 thresholder_(nullptr),
174 paragraph_models_(nullptr),
175 block_list_(nullptr),
177 input_file_(nullptr),
178 output_file_(nullptr),
182 recognition_done_(false),
199 #if defined(GIT_REV) && (defined(DEBUG) || defined(_DEBUG)) 214 #if USE_DEVICE_SELECTION 220 #if USE_DEVICE_SELECTION 221 ds_device device = OpenclDevice::getDeviceSelection();
222 if (device.type == DS_DEVICE_OPENCL_DEVICE) {
223 *data =
new cl_device_id;
224 memcpy(*data, &device.oclDeviceID,
sizeof(cl_device_id));
225 return sizeof(cl_device_id);
240 struct sigaction action;
241 memset(&action, 0,
sizeof(action));
243 action.sa_flags = SA_RESETHAND;
244 sigaction(SIGSEGV, &action, NULL);
245 sigaction(SIGFPE, &action, NULL);
246 sigaction(SIGBUS, &action, NULL);
249 tprintf(
"CatchSignals has no non-linux implementation!\n");
285 IntParam *p = ParamUtils::FindParam<IntParam>(
287 if (p == NULL)
return false;
288 *value = (
inT32)(*p);
293 BoolParam *p = ParamUtils::FindParam<BoolParam>(
295 if (p == NULL)
return false;
296 *value = (
BOOL8)(*p);
301 StringParam *p = ParamUtils::FindParam<StringParam>(
303 return (p != NULL) ? p->
string() : NULL;
307 DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
309 if (p == NULL)
return false;
310 *value = (double)(*p);
336 bool set_only_non_debug_params) {
337 return Init(datapath, 0, language, oem, configs, configs_size, vars_vec,
338 vars_values, set_only_non_debug_params,
nullptr);
348 bool set_only_non_debug_params,
FileReader reader) {
351 if (language ==
nullptr) language =
"eng";
352 STRING datapath = data_size == 0 ? data : language;
371 bool reset_classifier =
true;
373 reset_classifier =
false;
375 if (reader !=
nullptr)
reader_ = reader;
377 if (data_size != 0) {
383 language,
oem, configs, configs_size, vars_vec, vars_values,
384 set_only_non_debug_params, &mgr) != 0) {
405 if (reset_classifier) {
437 for (
int i = 0; i < num_subs; ++i)
529 int width,
int height) {
530 if (
tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize)
535 int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
536 SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
537 bytes_per_pixel, bytes_per_line);
562 int width,
int height,
563 int bytes_per_pixel,
int bytes_per_line) {
566 bytes_per_pixel, bytes_per_line);
575 tprintf(
"Please call SetImage before SetSourceResolution.\n");
636 Pixa** pixa,
int** blockids,
int** paraids) {
638 pixa, blockids, paraids);
681 bool text_only,
bool raw_image,
682 const int raw_padding,
683 Pixa** pixa,
int** blockids,
692 int component_count = 0;
693 int left, top, right, bottom;
700 &left, &top, &right, &bottom);
706 level, &left, &top, &right, &bottom);
709 if (get_bbox->
Run() &&
712 }
while (page_it->
Next(level));
714 Boxa* boxa = boxaCreate(component_count);
716 *pixa = pixaCreate(component_count);
717 if (blockids != NULL)
718 *blockids =
new int[component_count];
720 *paraids =
new int[component_count];
724 int component_index = 0;
727 if (get_bbox->
Run() &&
729 Box* lbox = boxCreate(left, top, right - left, bottom - top);
730 boxaAddBox(boxa, lbox, L_INSERT);
739 pixaAddPix(*pixa, pix, L_INSERT);
740 pixaAddBox(*pixa, lbox, L_CLONE);
742 if (paraids != NULL) {
743 (*paraids)[component_index] = paraid;
747 if (blockids != NULL) {
748 (*blockids)[component_index] = blockid;
756 }
while (page_it->
Next(level));
773 FILE *fp = fopen(filename,
"wb");
775 int width = pixGetWidth(pix);
776 int height = pixGetHeight(pix);
777 l_uint32* data = pixGetData(pix);
778 fprintf(fp,
"P5 %d %d 255\n", width, height);
779 for (
int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
780 for (
int x = 0; x < width; ++x) {
781 uint8_t b = GET_DATA_BIT(data, x) ? 0 : 255;
782 fwrite(&b, 1, 1, fp);
871 #ifndef GRAPHICS_DISABLED 873 #endif // GRAPHICS_DISABLED 888 fclose(training_output_file);
891 bool wait_for_text =
true;
908 tprintf(
"Please call SetImage before attempting recognition.\n");
925 while (page_res_it.
word() != NULL) {
929 page_res_it.
row()->
row, word_res);
958 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
960 const char* retry_config,
961 int timeout_millisec,
963 int tessedit_page_number) {
964 if (!flist && !buf)
return false;
965 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
970 buf->
split(
'\n', &lines);
971 if (lines.
empty())
return false;
975 for (
int i = 0; i < page; i++) {
977 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
989 if (fgets(pagename,
sizeof(pagename), flist) == NULL)
break;
991 if (page >= lines.
size())
break;
992 snprintf(pagename,
sizeof(pagename),
"%s", lines[page].c_str());
995 Pix *pix = pixRead(pagename);
997 tprintf(
"Image file %s cannot be read!\n", pagename);
1000 tprintf(
"Page %d : %s\n", page, pagename);
1001 bool r =
ProcessPage(pix, page, pagename, retry_config,
1002 timeout_millisec, renderer);
1004 if (!r)
return false;
1005 if (tessedit_page_number >= 0)
break;
1016 bool TessBaseAPI::ProcessPagesMultipageTiff(
const l_uint8 *data,
1019 const char* retry_config,
1020 int timeout_millisec,
1022 int tessedit_page_number) {
1023 #ifndef ANDROID_BUILD 1025 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1028 if (tessedit_page_number >= 0)
1029 page = tessedit_page_number;
1030 pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
1031 : pixReadFromMultipageTiff(filename, &offset);
1032 if (pix == NULL)
break;
1033 tprintf(
"Page %d\n", page + 1);
1035 snprintf(page_str, kMaxIntSize - 1,
"%d", page);
1037 bool r =
ProcessPage(pix, page, filename, retry_config,
1038 timeout_millisec, renderer);
1040 if (!r)
return false;
1041 if (tessedit_page_number >= 0)
break;
1053 int timeout_millisec,
1079 const char* retry_config,
1080 int timeout_millisec,
1083 bool stdInput = !strcmp(filename,
"stdin") || !strcmp(filename,
"-");
1086 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1087 tprintf(
"ERROR: cin to binary: %s", strerror(errno));
1092 return ProcessPagesFileList(stdin, NULL, retry_config,
1093 timeout_millisec, renderer,
1101 const l_uint8 *data = NULL;
1103 buf.
assign((std::istreambuf_iterator<char>(std::cin)),
1104 (std::istreambuf_iterator<char>()));
1105 data =
reinterpret_cast<const l_uint8 *
>(buf.data());
1110 int r = (stdInput) ?
1111 findFileFormatBuffer(data, &format) :
1112 findFileFormat(filename, &format);
1115 if (r != 0 || format == IFF_UNKNOWN) {
1120 std::ifstream t(filename);
1121 std::string u((std::istreambuf_iterator<char>(t)),
1122 std::istreambuf_iterator<char>());
1125 return ProcessPagesFileList(NULL, &s, retry_config,
1126 timeout_millisec, renderer,
1131 bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1132 format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1133 format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1134 format == IFF_TIFF_ZIP);
1139 pix = (stdInput) ? pixReadMem(data, buf.size()) : pixRead(filename);
1153 ProcessPagesMultipageTiff(data, buf.size(),
filename, retry_config,
1154 timeout_millisec, renderer,
1157 timeout_millisec, renderer);
1163 if (!r || (renderer && !renderer->EndDocument())) {
1171 const char* retry_config,
int timeout_millisec,
1176 bool failed =
false;
1189 }
else if (timeout_millisec > 0) {
1204 #ifndef ANDROID_BUILD 1206 pixWrite(
"tessinput.tif", page_pix, IFF_TIFF_G4);
1207 #endif // ANDROID_BUILD 1210 if (failed && retry_config != NULL && retry_config[0] !=
'\0') {
1212 FILE* fp = fopen(kOldVarsFile,
"wb");
1223 if (renderer && !failed) {
1224 failed = !renderer->
AddImage(
this);
1288 text += para_text.get();
1290 char* result =
new char[text.
length() + 1];
1304 it->
Orientation(&orientation, &writing_direction, &textline_order,
1317 static void AddBaselineCoordsTohOCR(
const PageIterator *it,
1322 hocr_str->
add_str_int(
"; textangle ", 360 - orientation * 90);
1326 int left, top, right, bottom;
1327 it->
BoundingBox(level, &left, &top, &right, &bottom);
1331 if (!it->
Baseline(level, &x1, &y1, &x2, &y2))
1349 p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1350 p0 = y1 -
static_cast<double>(p1 * x1);
1352 hocr_str->
add_str_double(
"; baseline ", round(p1 * 1000.0) / 1000.0);
1356 static void AddIdTohOCR(
STRING* hocr_str,
const std::string base,
int num1,
1358 const size_t BUFSIZE = 64;
1359 char id_buffer[BUFSIZE];
1361 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d_%d", base.c_str(), num1, num2);
1363 snprintf(id_buffer, BUFSIZE - 1,
"%s_%d", base.c_str(), num1);
1365 id_buffer[BUFSIZE - 1] =
'\0';
1366 *hocr_str +=
" id='";
1367 *hocr_str += id_buffer;
1373 int left, top, right, bottom;
1374 it->
BoundingBox(level, &left, &top, &right, &bottom);
1383 AddBaselineCoordsTohOCR(it, level, hocr_str);
1385 float row_height, descenders, ascenders;
1397 int left, top, right, bottom;
1398 it->
BoundingBox(level, &left, &top, &right, &bottom);
1431 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1432 int page_id = page_number + 1;
1433 bool para_is_ltr =
true;
1434 const char* paragraph_lang = NULL;
1435 bool font_info =
false;
1447 wchar_t *uni16_str =
new WCHAR[str16_len];
1449 uni16_str, str16_len);
1450 int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, 0,
1452 char *utf8_str =
new char[utf8_len];
1453 WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1454 utf8_len, NULL, NULL);
1460 hocr_str +=
" <div class='ocr_page'";
1461 AddIdTohOCR(&hocr_str,
"page", page_id, -1);
1462 hocr_str +=
" title='image \"";
1466 hocr_str +=
"unknown";
1485 hocr_str +=
" <div class='ocr_carea'";
1486 AddIdTohOCR(&hocr_str,
"block", page_id, bcnt);
1487 AddBoxTohOCR(res_it,
RIL_BLOCK, &hocr_str);
1490 hocr_str +=
"\n <p class='ocr_par'";
1493 hocr_str +=
" dir='rtl'";
1495 AddIdTohOCR(&hocr_str,
"par", page_id, pcnt);
1497 if (paragraph_lang) {
1498 hocr_str +=
" lang='";
1499 hocr_str += paragraph_lang;
1502 AddBoxTohOCR(res_it,
RIL_PARA, &hocr_str);
1505 hocr_str +=
"\n <span class='ocr_line'";
1506 AddIdTohOCR(&hocr_str,
"line", page_id, lcnt);
1511 hocr_str +=
"<span class='ocrx_word'";
1512 AddIdTohOCR(&hocr_str,
"word", page_id, wcnt);
1513 int left, top, right, bottom;
1514 bool bold, italic, underlined, monospace, serif, smallcaps;
1515 int pointsize, font_id;
1516 const char *font_name;
1519 &monospace, &serif, &smallcaps,
1520 &pointsize, &font_id);
1528 hocr_str +=
"; x_font ";
1535 if (lang && (!paragraph_lang || strcmp(lang, paragraph_lang))) {
1536 hocr_str +=
" lang='";
1543 if (!para_is_ltr) hocr_str +=
" dir='ltr'";
1546 if (para_is_ltr) hocr_str +=
" dir='rtl'";
1557 if (bold) hocr_str +=
"<strong>";
1558 if (italic) hocr_str +=
"<em>";
1560 const std::unique_ptr<const char[]> grapheme(
1562 if (grapheme && grapheme[0] != 0) {
1567 if (italic) hocr_str +=
"</em>";
1568 if (bold) hocr_str +=
"</strong>";
1569 hocr_str +=
"</span> ";
1572 if (last_word_in_line) {
1573 hocr_str +=
"\n </span>";
1576 if (last_word_in_para) {
1577 hocr_str +=
"\n </p>\n";
1581 if (last_word_in_block) {
1582 hocr_str +=
" </div>\n";
1586 hocr_str +=
" </div>\n";
1588 char *ret =
new char[hocr_str.
length() + 1];
1589 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;
1691 char* ret =
new char[tsv_str.
length() + 1];
1692 strcpy(ret, tsv_str.
string());
1733 int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
1735 char* result =
new char[total_length];
1737 int output_length = 0;
1740 int left, top, right, bottom;
1742 const std::unique_ptr<
char[]> text(
1746 for (
int i = 0; text[i] !=
'\0'; ++i) {
1750 snprintf(result + output_length, total_length - output_length,
1751 "%s %d %d %d %d %d\n", text.get(), left,
image_height_ - bottom,
1753 output_length += strlen(result + output_length);
1755 if (output_length + kMaxBytesPerLine > total_length)
1769 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1773 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1785 bool tilde_crunch_written =
false;
1786 bool last_char_was_newline =
true;
1787 bool last_char_was_tilde =
false;
1791 char* result =
new char[total_length];
1799 (!tilde_crunch_written ||
1810 last_char_was_tilde =
false;
1812 if (!last_char_was_tilde) {
1814 last_char_was_tilde =
true;
1816 tilde_crunch_written =
true;
1817 last_char_was_newline =
false;
1822 tilde_crunch_written =
false;
1826 int length = lengths.
length();
1830 if (last_char_was_tilde &&
1831 word->
word->
space() == 0 && wordstr[offset] ==
' ') {
1835 offset = lengths[i++];
1837 if (i < length && wordstr[offset] != 0) {
1838 if (!last_char_was_newline)
1841 last_char_was_newline =
false;
1842 for (; i < length; offset += lengths[i++]) {
1843 if (wordstr[offset] ==
' ' ||
1844 wordstr[offset] == kTesseractReject) {
1846 last_char_was_tilde =
true;
1849 *ptr++ = kUNLVSuspect;
1850 UNICHAR ch(wordstr + offset, lengths[i]);
1852 for (
int j = 0; kUniChs[j] != 0; ++j) {
1853 if (kUniChs[j] == uni_ch) {
1854 uni_ch = kLatinChs[j];
1858 if (uni_ch <= 0xff) {
1859 *ptr++ =
static_cast<char>(uni_ch);
1860 last_char_was_tilde =
false;
1863 last_char_was_tilde =
true;
1872 tilde_crunch_written =
false;
1873 last_char_was_newline =
true;
1874 last_char_was_tilde =
false;
1892 const char** script_name,
1893 float* script_conf) {
1904 if (orient_deg) *orient_deg = orient_id * 90;
1909 *script_name = script;
1925 const char* script_name;
1935 const int kOsdBufsize = 255;
1936 char* osd_buf =
new char[kOsdBufsize];
1937 snprintf(osd_buf, kOsdBufsize,
1939 "Orientation in degrees: %d\n" 1941 "Orientation confidence: %.2f\n" 1943 "Script confidence: %.2f\n",
1944 page_number, orient_deg, rotate, orient_conf, script_name,
1953 if (!conf)
return 0;
1956 while (*pt >= 0) sum += *pt++;
1957 if (pt != conf) sum /= pt - conf;
1972 int* conf =
new int[n_word+1];
1977 int w_conf =
static_cast<int>(100 + 5 * choice->
certainty());
1979 if (w_conf < 0) w_conf = 0;
1980 if (w_conf > 100) w_conf = 100;
1981 conf[n_word++] = w_conf;
2000 bool success =
true;
2004 const std::unique_ptr<const char[]> text(
GetUTF8Text());
2006 tprintf(
"Trying to adapt \"%s\" to \"%s\"\n", text.get(), wordstr);
2011 if (word_res != NULL) {
2019 for (t = 0; text[t] !=
'\0'; ++t) {
2020 if (text[t] ==
'\n' || text[t] ==
' ')
2022 while (wordstr[w] ==
' ') ++w;
2023 if (text[t] != wordstr[w])
2027 if (text[t] !=
'\0' || wordstr[w] !=
'\0') {
2035 if (pr_it.
word() == NULL)
2038 word_res = pr_it.
word();
2134 if (x2 <= x1) x2 = x1 + 1;
2136 *out_slope =
static_cast<float>(y2 - y1) / (x2 - x1);
2137 *out_offset =
static_cast<int>(y1 - *out_slope * x1);
2140 int left, top, right, bottom;
2150 *out_offset += bottom -
MAX(left_y, right_y);
2153 *out_slope = -*out_slope;
2180 for (
int i = 0; i < num_subs; ++i) {
2194 tprintf(
"Please call Init before attempting to set an image.\n");
2218 tprintf(
"Warning. Invalid resolution %d dpi. Using %d instead.\n", y_res,
2244 tprintf(
"Estimated resolution %d out of range! Corrected to %d\n",
2255 tprintf(
"Please call SetImage before attempting recognition.\n");
2279 tprintf(
"Warning: Could not set equation detector\n");
2288 osd_tess ==
nullptr) {
2295 tprintf(
"Warning: Auto orientation and script detection requested," 2296 " but data path is undefined\n");
2301 nullptr, 0,
nullptr,
nullptr,
2302 false, &mgr) == 0) {
2307 tprintf(
"Warning: Auto orientation and script detection requested," 2308 " but osd language failed to load\n");
2357 int total_length = 2;
2358 int total_blobs = 0;
2364 if (choice != NULL) {
2365 total_blobs += choice->
length() + 2;
2373 if (blob_count != NULL)
2374 *blob_count = total_blobs;
2375 return total_length;
2414 bool** vertical_writing) {
2415 delete[] *block_orientation;
2416 *block_orientation = NULL;
2417 delete[] *vertical_writing;
2418 *vertical_writing = NULL;
2421 block_it.move_to_first();
2423 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2424 if (!block_it.data()->poly_block()->IsText()) {
2430 tprintf(
"WARNING: Found no blocks\n");
2433 *block_orientation =
new int[num_blocks];
2434 *vertical_writing =
new bool[num_blocks];
2435 block_it.move_to_first();
2437 for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2438 block_it.forward()) {
2439 if (!block_it.data()->poly_block()->IsText()) {
2442 FCOORD re_rotation = block_it.data()->re_rotation();
2443 float re_theta = re_rotation.
angle();
2444 FCOORD classify_rotation = block_it.data()->classify_rotation();
2445 float classify_theta = classify_rotation.
angle();
2446 double rot_theta = - (re_theta - classify_theta) * 2.0 /
PI;
2447 if (rot_theta < 0) rot_theta += 4;
2448 int num_rotations =
static_cast<int>(rot_theta + 0.5);
2449 (*block_orientation)[i] = num_rotations;
2452 (*vertical_writing)[i] = classify_rotation.
y() != 0.0f;
2482 inT32 xstarts[] = {-32000};
2483 double quad_coeffs[] = {0, 0, baseline};
2488 ascender - (baseline + xheight),
2489 descender - baseline,
2496 int width = pixGetWidth(pix);
2497 int height = pixGetHeight(pix);
2498 BLOCK block(
"a character",
TRUE, 0, 0, 0, 0, width, height);
2505 C_BLOB_IT c_blob_it(list);
2506 if (c_blob_it.empty())
2509 C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2510 for (c_blob_it.forward();
2511 !c_blob_it.at_first();
2512 c_blob_it.forward()) {
2513 C_BLOB *c_blob = c_blob_it.data();
2514 ol_it.add_list_after(c_blob->
out_list());
2527 float x_center = (box.
left() + box.
right()) / 2.0f;
2530 tblob->
Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
2539 float descender,
float ascender,
2540 bool numeric_mode, Pix* pix) {
2567 float best_rating = -100;
2571 BLOB_CHOICE_LIST choices;
2573 BLOB_CHOICE_IT choice_it;
2574 choice_it.set_to_list(&choices);
2575 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2576 choice_it.forward()) {
2577 if (choice_it.data()->rating() > best_rating) {
2578 best_rating = choice_it.data()->rating();
2601 pass1_result =
new PAGE_RES(
false, block_list,
2604 return pass1_result;
2608 int debug_level = 0;
2616 result_it, &models);
2628 TESS_CHAR(
float _cost,
const char *repr,
int len = -1) : cost(_cost) {
2629 length = (len == -1 ? strlen(repr) : len);
2630 unicode_repr =
new char[length + 1];
2631 strncpy(unicode_repr, repr, length);
2637 delete [] unicode_repr;
2644 static void add_space(TESS_CHAR_IT* it) {
2646 it->add_after_then_move(t);
2650 static float rating_to_cost(
float rating) {
2651 rating = 100 + rating;
2655 if (rating < 0) rating = 0;
2663 static void extract_result(TESS_CHAR_IT* out,
2667 while (page_res_it.
word() != NULL) {
2675 int n = strlen(len);
2676 for (
int i = 0; i < n; i++) {
2680 out->add_after_then_move(tc);
2701 TESS_CHAR_LIST tess_chars;
2702 TESS_CHAR_IT tess_chars_it(&tess_chars);
2703 extract_result(&tess_chars_it, page_res);
2704 tess_chars_it.move_to_first();
2705 int n = tess_chars.length();
2707 *lengths =
new int[n];
2708 *costs =
new float[n];
2714 for (tess_chars_it.mark_cycle_pt();
2715 !tess_chars_it.cycled_list();
2716 tess_chars_it.forward(), i++) {
2718 text_len += (*lengths)[i] = tc->
length;
2719 (*costs)[i] = tc->
cost;
2723 (*y1)[i] = tc->
box.
top();
2725 char *p = *text =
new char[text_len];
2727 tess_chars_it.move_to_first();
2728 for (tess_chars_it.mark_cycle_pt();
2729 !tess_chars_it.cycled_list();
2730 tess_chars_it.forward()) {
2748 int* feature_outline_index) {
2754 &cn_features, &fx_info, &outline_counts);
2759 *num_features = cn_features.
size();
2760 memcpy(int_features, &cn_features[0], *num_features *
sizeof(cn_features[0]));
2762 if (feature_outline_index != NULL) {
2764 for (
int i = 0; i < outline_counts.
size(); ++i) {
2765 while (f < outline_counts[i])
2766 feature_outline_index[f++] = i;
2774 int left,
int top,
int right,
int bottom) {
2775 TBOX box(left, bottom, right, top);
2776 BLOCK_IT b_it(blocks);
2777 for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2778 BLOCK* block = b_it.data();
2782 for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2783 ROW* row = r_it.data();
2787 for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2788 WERD* word = w_it.data();
2799 int num_max_matches,
2802 int* num_matches_returned) {
2803 BLOB_CHOICE_LIST* choices =
new BLOB_CHOICE_LIST;
2805 BLOB_CHOICE_IT choices_it(choices);
2806 int& index = *num_matches_returned;
2808 for (choices_it.mark_cycle_pt();
2809 !choices_it.cycled_list() && index < num_max_matches;
2810 choices_it.forward()) {
2813 ratings[index] = choice->
rating();
2816 *num_matches_returned = index;
2840 for (ptr = text; *ptr; ptr++) {
2842 case '<': ret +=
"<";
break;
2843 case '>': ret +=
">";
break;
2844 case '&': ret +=
"&";
break;
2845 case '"': ret +=
""";
break;
2846 case '\'': ret +=
"'";
break;
2847 default: ret += *ptr;
void LearnWord(const char *fontname, WERD_RES *word)
ADAPT_TEMPLATES AdaptedTemplates
tesseract::ParamsVectors * GlobalParams()
static void CatchSignals()
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Tesseract * tesseract() const
GenericVector< IntParam * > int_params
TESS_CHAR(float _cost, const char *repr, int len=-1)
C_BLOB_LIST * blob_list()
get blobs
int GetScaledEstimatedResolution() const
void InitForAnalysePage()
bool PSM_OSD_ENABLED(int pageseg_mode)
bool PTIsTextType(PolyBlockType type)
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
bool textord_equation_detect
Dict & getDict() override
bool AddImage(TessBaseAPI *api)
void set_unlv_suspects(WERD_RES *word)
double min_orientation_margin
Tesseract * osd_tesseract_
For orientation & script detection.
bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf)
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
bool tessedit_make_boxes_from_boxes
GenericVector< DoubleParam * > double_params
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)
Boxa * GetConnectedComponents(Pixa **cc)
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
TBOX intersection(const TBOX &box) const
WERD_RES * restart_page()
constexpr int kMinCredibleResolution
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
STRING * language_
Last initialized language.
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
const int kBytesPerNumber
bool tessedit_train_line_recognizer
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
bool GetIntVariable(const char *name, int *value) const
GenericVector< ParagraphModel * > * paragraph_models_
void ReSegmentByClassification(PAGE_RES *page_res)
void TidyUp(PAGE_RES *page_res)
bool tessedit_train_from_boxes
Tesseract * tesseract_
The underlying data object.
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)
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)
char * GetTSVText(int page_number)
bool SetDebugVariable(const char *name, const char *value)
Assume a single uniform block of text. (Default.)
const char kTesseractReject
EquationDetect * equ_detect_
The equation detector.
#define PERF_COUNT_SUB(SUB)
bool GetTextDirection(int *out_offset, float *out_slope)
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
void set_pix_original(Pix *original_pix)
const char * GetInputName()
WERD_CHOICE * prev_word_best_choice_
const char * get_script_from_script_id(int id) const
TruthCallback * truth_cb_
STRING * output_file_
Name used by debug code.
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
void pgeditor_main(int width, int height, PAGE_RES *page_res)
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
virtual bool Next(PageIteratorLevel level)
GenericVector< BoolParam * > bool_params
bool ParagraphIsLtr() const
void add_str_int(const char *str, int number)
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)
Tesseract * get_sub_lang(int index) const
STRING * input_file_
Name used by training code.
ROW_LIST * row_list()
get rows
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
void * cancel_this
called whenever progress increases
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
BLOCK_LIST * FindLinesCreateBlockList()
float Confidence(PageIteratorLevel level) const
int OrientationIdToValue(const int &id)
void PrintVariables(FILE *fp) const
FileReader reader_
Reads files from any filesystem.
int Recognize(ETEXT_DESC *monitor)
bool tessedit_resegment_from_line_boxes
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
static size_t getOpenCLDevice(void **device)
STRING HOcrEscape(const char *text)
void SetPageSegMode(PageSegMode mode)
const char * GetDatapath()
FILE * init_recog_training(const STRING &fname)
void SetEquationDetect(EquationDetect *detector)
TESS_LOCAL int TextLength(int *blob_count)
Pix * pix_original() const
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
WERD_CHOICE * best_choice
PAGE_RES * page_res_
The page-level data.
void CorrectClassifyWords(PAGE_RES *page_res)
#define MAX_NUM_INT_FEATURES
const char * GetUnichar(int unichar_id)
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 SetSourceYResolution(int ppi)
C_OUTLINE_LIST * out_list()
void delete_data_pointers()
TESS_LOCAL bool InternalSetImage()
PolyBlockType BlockType() const
void chomp_string(char *str)
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
void SetRectangle(int left, int top, int width, int height)
bool WriteTRFile(const STRING &filename)
char * GetBoxText(int page_number)
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
void assign(const char *cstr, int len)
virtual TESS_LOCAL bool Threshold(Pix **pix)
void SetInputName(const char *name)
int RecognizeForChopTest(ETEXT_DESC *monitor)
PageSegMode GetPageSegMode() const
int InitLangMod(const char *datapath, const char *language)
void SetSourceResolution(int ppi)
float angle() const
find angle
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
void ClearAdaptiveClassifier()
void SetFillLatticeFunc(FillLatticeFunc f)
static void ClearPersistentCache()
UNICHAR_ID unichar_id() const
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
bool contains_unichar(const char *const unichar_repr) const
bool interactive_display_mode
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
void add_str_double(const char *str, double number)
int num_sub_langs() const
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
double matcher_good_threshold
bool IsValidCharacter(const char *utf8_character)
int GetScaleFactor() const
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 * string() const
char * GetUTF8Text(PageIteratorLevel level) const
void RowAttributes(float *row_height, float *descenders, float *ascenders) const
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
const TBOX & BlobBox(int index) const
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
bool LoadMemBuffer(const char *name, const char *data, int size)
void set_deadline_msecs(inT32 deadline_msecs)
void SetRectangle(int left, int top, int width, int height)
void set_pix_thresholds(Pix *thresholds)
const int kNumbersPerBlob
TESS_LOCAL LTRResultIterator * GetLTRIterator()
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
Boxa * GetStrips(Pixa **pixa, int **blockids)
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
Pix * GetThresholdedImage()
static DawgCache * GlobalDawgCache()
bool GetDoubleVariable(const char *name, double *value) const
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
const char * string() const
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
bool major_overlap(const TBOX &box) const
ImageThresholder * thresholder_
Image thresholding module.
#define PERF_COUNT_START(FUNCT_NAME)
const STRING & unichar_lengths() const
STRING * datapath_
Current location of tessdata.
int GetSourceYResolution()
virtual char * GetUTF8Text(PageIteratorLevel level) const
bool IsEmpty() const
Return true if no image has been set.
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
void ResetAdaptiveClassifier()
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)
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
const Dawg * GetDawg(int i) const
Automatic page segmentation, but no OSD, or OCR.
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
OcrEngineMode oem() const
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.
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
#define BOOL_VAR(name, val, comment)
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
BLOCK_LIST * block_list_
The page layout.
CANCEL_FUNC cancel
for errcode use
void SetOutputName(const char *name)
Pix * GetBinaryImage(PageIteratorLevel level) const
virtual bool ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
Returns false on error.
void DumpPGM(const char *filename)
void BestChoiceToCorrectText()
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
CRUNCH_MODE unlv_crunch_mode
bool tessedit_write_images
int tessedit_pageseg_mode
static const char * Version()
void set_source_resolution(int ppi)
bool Empty(PageIteratorLevel level) const
virtual bool Next(PageIteratorLevel level)
bool BeginDocument(const char *title)
virtual void Run(A1, A2, A3, A4)=0
float base_line(float xpos) const
GenericVector< StringParam * > string_params
void read_config_file(const char *filename, SetParamConstraint constraint)
TBOX bounding_box() const
bool GetBoolVariable(const char *name, bool *value) const
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language, TessdataManager *mgr)
const char * GetInitLanguagesAsString() const
int GetThresholdedImageScaleFactor() const
char * GetOsdText(int page_number)
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
#define ELISTIZE(CLASSNAME)
constexpr int kMaxCredibleResolution
void extract_edges(Pix *pix, BLOCK *block)
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
const char * GetStringVariable(const char *name) const
const int kBytesPer64BitNumber
tesseract::BoxWord * box_word
void SavePixForCrash(int resolution, Pix *pix)
void ReadDebugConfigFile(const char *filename)
void signal_exit(int signal_code)
const int kMaxBytesPerLine
BOOL8 flag(WERD_FLAGS mask) const
bool classify_bln_numeric_mode
static void DeleteBlockList(BLOCK_LIST *block_list)
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
void set_pix_grey(Pix *grey_pix)
void set_min_orientation_margin(double margin)
const char * WordRecognitionLanguage() const
const int kBytesPerBoxFileLine
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
int IsValidWord(const char *word)
BLOCK_RES * block() const
PageIterator * AnalyseLayout()
bool GetVariableAsString(const char *name, STRING *val)
const int kBlnBaselineOffset
void ExtractFontName(const STRING &filename, STRING *fontname)
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
void SetDictFunc(DictFunc f)
virtual Pix * GetPixRectThresholds()
int GetScaledYResolution() const
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA *> *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel *> *models)
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
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.
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
TBOX bounding_box() const
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
void ReadConfigFile(const char *filename)
void set_text(const char *new_text)
static TBLOB * MakeTBLOB(Pix *pix)
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
Boxa * GetRegions(Pixa **pixa)
Pix ** mutable_pix_binary()
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void SetBlackAndWhitelist()
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 IntCastRounded(double x)
bool SetVariable(const char *name, const char *value)
void InitAdaptiveClassifier(TessdataManager *mgr)
#define ELISTIZEH(CLASSNAME)
const char * kOldVarsFile
int GetSourceYResolution() const
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
bool tessedit_resegment_from_boxes
const char * c_str() const
void TrainLineRecognizer(const STRING &input_imagename, const STRING &output_basename, BLOCK_LIST *block_list)
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
MutableIterator * GetMutableIterator()
const UNICHARSET & getUnicharset() const
char * GetHOCRText(ETEXT_DESC *monitor, int page_number)
TBOX bounding_box() const
int * AllWordConfidences()
StrongScriptDirection WordDirection() const
void split(const char c, GenericVector< STRING > *splited)
bool IsBinary() const
Returns true if the source image is binary.
#define TESSERACT_VERSION_STR
static void ResetToDefaults(ParamsVectors *member_params)
TESS_LOCAL int FindLines()
const char * id_to_unichar(UNICHAR_ID id) const
void ResetDocumentDictionary()
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
Orientation and script detection only.
TESS_API int get_best_script(int orientation_id) const
ResultIterator * GetIterator()
bool tessedit_ambigs_training
const STRING & unichar_string() const
virtual Pix * GetPixRectGrey()
Boxa * GetWords(Pixa **pixa)