22 #include "config_auto.h"
35 #undef __STRICT_ANSI__
52 #include "allheaders.h"
114 osd_tesseract_(
NULL),
120 paragraph_models_(
NULL),
129 recognition_done_(false),
131 rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0),
132 image_width_(0), image_height_(0) {
143 #if defined(GIT_REV) && (defined(DEBUG) || defined(_DEBUG))
158 #if USE_DEVICE_SELECTION
164 #if USE_DEVICE_SELECTION
165 ds_device device = OpenclDevice::getDeviceSelection();
166 if (device.type == DS_DEVICE_OPENCL_DEVICE) {
167 *data =
reinterpret_cast<void*
>(
new cl_device_id);
168 memcpy(*data, &device.oclDeviceID,
sizeof(cl_device_id));
169 return sizeof(cl_device_id);
184 struct sigaction action;
185 memset(&action, 0,
sizeof(action));
187 action.sa_flags = SA_RESETHAND;
188 sigaction(SIGSEGV, &action,
NULL);
189 sigaction(SIGFPE, &action,
NULL);
190 sigaction(SIGBUS, &action,
NULL);
193 tprintf(
"CatchSignals has no non-linux implementation!\n");
229 IntParam *p = ParamUtils::FindParam<IntParam>(
231 if (p ==
NULL)
return false;
232 *value = (
inT32)(*p);
237 BoolParam *p = ParamUtils::FindParam<BoolParam>(
239 if (p ==
NULL)
return false;
240 *value = (
BOOL8)(*p);
245 StringParam *p = ParamUtils::FindParam<StringParam>(
251 DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
253 if (p ==
NULL)
return false;
254 *value = (double)(*p);
280 bool set_only_non_debug_params) {
283 if (language ==
NULL) language =
"eng";
302 bool reset_classifier =
true;
304 reset_classifier =
false;
308 language,
oem, configs, configs_size, vars_vec, vars_values,
309 set_only_non_debug_params) != 0) {
330 if (reset_classifier) {
362 for (
int i = 0; i < num_subs; ++i)
376 char fname[_MAX_FNAME];
377 WIN32_FIND_DATA data;
379 HANDLE handle = FindFirstFile(pattern.
string(), &data);
380 if (handle != INVALID_HANDLE_VALUE) {
381 for (; result; result = FindNextFile(handle, &data)) {
389 struct dirent *dirent;
396 while ((dirent = readdir(dir))) {
398 if (dirent->d_name[0] !=
'.') {
399 if (strstr(dirent->d_name, extension.
string()) !=
NULL) {
400 dot = strrchr(dirent->d_name,
'.');
402 if (strncmp(dot, extension.
string(),
403 strlen(extension.
string())) == 0) {
491 int width,
int height) {
492 if (
tesseract_ ==
NULL || width < kMinRectSize || height < kMinRectSize)
497 int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
498 SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
499 bytes_per_pixel, bytes_per_line);
526 int width,
int height,
527 int bytes_per_pixel,
int bytes_per_line) {
530 bytes_per_pixel, bytes_per_line);
537 tprintf(
"Please call SetImage before SetSourceResolution.\n");
598 Pixa** pixa,
int** blockids,
int** paraids) {
600 pixa, blockids, paraids);
643 bool text_only,
bool raw_image,
644 const int raw_padding,
645 Pixa** pixa,
int** blockids,
654 int component_count = 0;
655 int left, top, right, bottom;
662 &left, &top, &right, &bottom);
668 level, &left, &top, &right, &bottom);
671 if (get_bbox->
Run() &&
674 }
while (page_it->
Next(level));
676 Boxa* boxa = boxaCreate(component_count);
678 *pixa = pixaCreate(component_count);
679 if (blockids !=
NULL)
680 *blockids =
new int[component_count];
682 *paraids =
new int[component_count];
686 int component_index = 0;
689 if (get_bbox->
Run() &&
691 Box* lbox = boxCreate(left, top, right - left, bottom - top);
692 boxaAddBox(boxa, lbox, L_INSERT);
701 pixaAddPix(*pixa, pix, L_INSERT);
702 pixaAddBox(*pixa, lbox, L_CLONE);
704 if (paraids !=
NULL) {
705 (*paraids)[component_index] = paraid;
709 if (blockids !=
NULL) {
710 (*blockids)[component_index] = blockid;
718 }
while (page_it->
Next(level));
735 FILE *fp = fopen(filename,
"wb");
737 int width = pixGetWidth(pix);
738 int height = pixGetHeight(pix);
739 l_uint32* data = pixGetData(pix);
740 fprintf(fp,
"P5 %d %d 255\n", width, height);
741 for (
int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
742 for (
int x = 0; x < width; ++x) {
743 uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255;
744 fwrite(&b, 1, 1, fp);
750 #ifndef ANDROID_BUILD
758 Boxa* boxa_words, Pixa* pixa_words,
759 const FCOORD& reskew, Pix* page_pix,
761 int block_count = boxaGetCount(boxa_blocks);
762 ASSERT_HOST(block_count == pixaGetCount(pixa_blocks));
764 for (
int i = 0; i < block_count; ++i) {
765 Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE);
766 pixDisplayWrite(pix, 1);
768 int word_count = boxaGetCount(boxa_words);
769 ASSERT_HOST(word_count == pixaGetCount(pixa_words));
773 page_res_it.
forward(), ++pr_word) {
779 if (choice !=
NULL) {
783 filename +=
"unclassified";
784 snprintf(numbuf, 32,
"%03d", pr_word);
788 Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE);
789 pixWrite(filename.
string(), pix, IFF_TIFF_G4);
872 #ifndef GRAPHICS_DISABLED
874 #endif // GRAPHICS_DISABLED
889 fclose(training_output_file);
892 bool wait_for_text =
true;
909 tprintf(
"Please call SetImage before attempting recognition.");
926 while (page_res_it.
word() !=
NULL) {
930 page_res_it.
row()->
row, word_res);
966 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
968 const char* retry_config,
969 int timeout_millisec,
971 int tessedit_page_number) {
972 if (!flist && !buf)
return false;
973 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
978 buf->
split(
'\n', &lines);
979 if (lines.
empty())
return false;
983 for (
int i = 0; i < page; i++) {
985 if (fgets(pagename,
sizeof(pagename), flist) ==
NULL)
break;
990 const char* kUnknownTitle =
"";
998 if (fgets(pagename,
sizeof(pagename), flist) ==
NULL)
break;
1000 if (page >= lines.
size())
break;
1001 snprintf(pagename,
sizeof(pagename),
"%s", lines[page].c_str());
1004 Pix *pix = pixRead(pagename);
1006 tprintf(
"Image file %s cannot be read!\n", pagename);
1009 tprintf(
"Page %d : %s\n", page, pagename);
1010 bool r =
ProcessPage(pix, page, pagename, retry_config,
1011 timeout_millisec, renderer);
1013 if (!r)
return false;
1014 if (tessedit_page_number >= 0)
break;
1025 bool TessBaseAPI::ProcessPagesMultipageTiff(
const l_uint8 *data,
1028 const char* retry_config,
1029 int timeout_millisec,
1031 int tessedit_page_number) {
1032 #ifndef ANDROID_BUILD
1037 int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1039 if (tessedit_page_number >= 0)
1040 page = tessedit_page_number;
1042 if ( od.selectedDeviceIsOpenCL() ) {
1044 pix = od.pixReadMemTiffCl(data, size, page);
1047 pix = pixReadMemTiff(data, size, page);
1051 if (pix ==
NULL)
break;
1052 tprintf(
"Page %d\n", page + 1);
1054 snprintf(page_str, kMaxIntSize - 1,
"%d", page);
1056 bool r =
ProcessPage(pix, page, filename, retry_config,
1057 timeout_millisec, renderer);
1059 if (!r)
return false;
1060 if (tessedit_page_number >= 0)
break;
1071 int timeout_millisec,
1098 const char* retry_config,
1099 int timeout_millisec,
1101 #ifndef ANDROID_BUILD
1103 bool stdInput = !strcmp(filename,
"stdin") || !strcmp(filename,
"-");
1106 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1107 tprintf(
"ERROR: cin to binary: %s", strerror(errno));
1112 return ProcessPagesFileList(stdin,
NULL, retry_config,
1113 timeout_millisec, renderer,
1123 buf.
assign((std::istreambuf_iterator<char>(std::cin)),
1124 (std::istreambuf_iterator<char>()));
1126 std::ifstream ifs(filename, std::ios::binary);
1128 buf.assign((std::istreambuf_iterator<char>(ifs)),
1129 (std::istreambuf_iterator<char>()));
1131 tprintf(
"ERROR: Can not open input file %s\n", filename);
1138 const l_uint8 * data =
reinterpret_cast<const l_uint8 *
>(buf.c_str());
1139 findFileFormatBuffer(data, &format);
1142 if (format == IFF_UNKNOWN) {
1144 return ProcessPagesFileList(
NULL, &s, retry_config,
1145 timeout_millisec, renderer,
1150 bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1151 format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1152 format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1153 format == IFF_TIFF_ZIP);
1158 pix = pixReadMem(data, buf.size());
1165 const char* kUnknownTitle =
"";
1174 r = ProcessPagesMultipageTiff(data, buf.size(),
filename, retry_config,
1175 timeout_millisec, renderer,
1179 timeout_millisec, renderer);
1184 if (!r || (renderer && !renderer->
EndDocument())) {
1195 const char* retry_config,
int timeout_millisec,
1200 bool failed =
false;
1201 if (timeout_millisec > 0) {
1225 #ifndef ANDROID_BUILD
1227 pixWrite(
"tessinput.tif", page_pix, IFF_TIFF_G4);
1230 if (failed && retry_config !=
NULL && retry_config[0] !=
'\0') {
1232 FILE* fp = fopen(kOldVarsFile,
"wb");
1243 if (renderer && !failed) {
1244 failed = !renderer->
AddImage(
this);
1310 char* result =
new char[text.
length() + 1];
1324 it->
Orientation(&orientation, &writing_direction, &textline_order,
1337 static void AddBaselineCoordsTohOCR(
const PageIterator *it,
1342 hocr_str->
add_str_int(
"; textangle ", 360 - orientation * 90);
1346 int left, top, right, bottom;
1347 it->BoundingBox(level, &left, &top, &right, &bottom);
1351 if (!it->Baseline(level, &x1, &y1, &x2, &y2))
1369 p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1370 p0 = y1 -
static_cast<double>(p1 * x1);
1376 static void AddBoxTohOCR(
const PageIterator *it,
1379 int left, top, right, bottom;
1380 it->BoundingBox(level, &left, &top, &right, &bottom);
1387 AddBaselineCoordsTohOCR(it, level, hocr_str);
1404 int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1405 int page_id = page_number + 1;
1406 bool font_info =
false;
1418 wchar_t *uni16_str =
new WCHAR[str16_len];
1420 uni16_str, str16_len);
1421 int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len,
NULL,
1423 char *utf8_str =
new char[utf8_len];
1424 WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1431 hocr_str.
add_str_int(
" <div class='ocr_page' id='page_", page_id);
1432 hocr_str +=
"' title='image \"";
1436 hocr_str +=
"unknown";
1454 hocr_str.
add_str_int(
" <div class='ocr_carea' id='block_", page_id);
1456 AddBoxTohOCR(res_it,
RIL_BLOCK, &hocr_str);
1460 hocr_str.
add_str_int(
"\n <p class='ocr_par' dir='ltr' id='par_",
1464 hocr_str.
add_str_int(
"\n <p class='ocr_par' dir='rtl' id='par_",
1468 AddBoxTohOCR(res_it,
RIL_PARA, &hocr_str);
1471 hocr_str.
add_str_int(
"\n <span class='ocr_line' id='line_", page_id);
1477 hocr_str.
add_str_int(
"<span class='ocrx_word' id='word_", page_id);
1479 int left, top, right, bottom;
1480 bool bold, italic, underlined, monospace, serif, smallcaps;
1481 int pointsize, font_id;
1482 const char *font_name;
1485 &monospace, &serif, &smallcaps,
1486 &pointsize, &font_id);
1494 hocr_str +=
"; x_font ";
1501 hocr_str +=
" lang='";
1515 if (bold) hocr_str +=
"<strong>";
1516 if (italic) hocr_str +=
"<em>";
1519 if (grapheme && grapheme[0] != 0) {
1525 if (italic) hocr_str +=
"</em>";
1526 if (bold) hocr_str +=
"</strong>";
1527 hocr_str +=
"</span> ";
1530 if (last_word_in_line) {
1531 hocr_str +=
"\n </span>";
1534 if (last_word_in_para) {
1535 hocr_str +=
"\n </p>\n";
1538 if (last_word_in_block) {
1539 hocr_str +=
" </div>\n";
1543 hocr_str +=
" </div>\n";
1545 char *ret =
new char[hocr_str.
length() + 1];
1546 strcpy(ret, hocr_str.
string());
1587 int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
1589 char* result =
new char[total_length];
1590 strcpy(result,
"\0");
1591 int output_length = 0;
1594 int left, top, right, bottom;
1599 for (
int i = 0; text[i] !=
'\0'; ++i) {
1603 snprintf(result + output_length, total_length - output_length,
1604 "%s %d %d %d %d %d\n",
1607 output_length += strlen(result + output_length);
1610 if (output_length + kMaxBytesPerLine > total_length)
1624 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1628 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1640 bool tilde_crunch_written =
false;
1641 bool last_char_was_newline =
true;
1642 bool last_char_was_tilde =
false;
1646 char* result =
new char[total_length];
1654 (!tilde_crunch_written ||
1665 last_char_was_tilde =
false;
1667 if (!last_char_was_tilde) {
1669 last_char_was_tilde =
true;
1671 tilde_crunch_written =
true;
1672 last_char_was_newline =
false;
1677 tilde_crunch_written =
false;
1681 int length = lengths.
length();
1685 if (last_char_was_tilde &&
1686 word->
word->
space() == 0 && wordstr[offset] ==
' ') {
1690 offset = lengths[i++];
1692 if (i < length && wordstr[offset] != 0) {
1693 if (!last_char_was_newline)
1696 last_char_was_newline =
false;
1697 for (; i < length; offset += lengths[i++]) {
1698 if (wordstr[offset] ==
' ' ||
1699 wordstr[offset] == kTesseractReject) {
1701 last_char_was_tilde =
true;
1704 *ptr++ = kUNLVSuspect;
1705 UNICHAR ch(wordstr + offset, lengths[i]);
1707 for (
int j = 0; kUniChs[j] != 0; ++j) {
1708 if (kUniChs[j] == uni_ch) {
1709 uni_ch = kLatinChs[j];
1713 if (uni_ch <= 0xff) {
1714 *ptr++ =
static_cast<char>(uni_ch);
1715 last_char_was_tilde =
false;
1718 last_char_was_tilde =
true;
1727 tilde_crunch_written =
false;
1728 last_char_was_newline =
true;
1729 last_char_was_tilde =
false;
1740 if (!conf)
return 0;
1743 while (*pt >= 0) sum += *pt++;
1744 if (pt != conf) sum /= pt - conf;
1759 int* conf =
new int[n_word+1];
1764 int w_conf =
static_cast<int>(100 + 5 * choice->
certainty());
1766 if (w_conf < 0) w_conf = 0;
1767 if (w_conf > 100) w_conf = 100;
1768 conf[n_word++] = w_conf;
1787 bool success =
true;
1793 tprintf(
"Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
1798 if (word_res !=
NULL) {
1806 for (t = 0; text[t] !=
'\0'; ++t) {
1807 if (text[t] ==
'\n' || text[t] ==
' ')
1809 while (wordstr[w] !=
'\0' && wordstr[w] ==
' ')
1811 if (text[t] != wordstr[w])
1815 if (text[t] !=
'\0' || wordstr[w] !=
'\0') {
1826 word_res = pr_it.
word();
1947 if (x2 <= x1) x2 = x1 + 1;
1949 *out_slope =
static_cast<float>(y2 - y1) / (x2 - x1);
1950 *out_offset =
static_cast<int>(y1 - *out_slope * x1);
1953 int left, top, right, bottom;
1963 *out_offset += bottom -
MAX(left_y, right_y);
1966 *out_slope = -*out_slope;
1993 for (
int i = 0; i < num_subs; ++i) {
2007 tprintf(
"Please call Init before attempting to set an image.");
2028 if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) {
2055 tprintf(
"Estimated resolution %d out of range! Corrected to %d\n",
2065 tprintf(
"Please call SetImage before attempting recognition.");
2081 tprintf(
"Image too large: (%d, %d)\n",
2109 tprintf(
"Warning: Auto orientation and script detection requested,"
2110 " but osd language failed to load\n");
2159 int total_length = 2;
2160 int total_blobs = 0;
2166 if (choice !=
NULL) {
2167 total_blobs += choice->
length() + 2;
2175 if (blob_count !=
NULL)
2176 *blob_count = total_blobs;
2177 return total_length;
2214 bool** vertical_writing) {
2215 delete[] *block_orientation;
2216 *block_orientation =
NULL;
2217 delete[] *vertical_writing;
2218 *vertical_writing =
NULL;
2221 block_it.move_to_first();
2223 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2224 if (!block_it.data()->poly_block()->IsText()) {
2230 tprintf(
"WARNING: Found no blocks\n");
2233 *block_orientation =
new int[num_blocks];
2234 *vertical_writing =
new bool[num_blocks];
2235 block_it.move_to_first();
2237 for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2238 block_it.forward()) {
2239 if (!block_it.data()->poly_block()->IsText()) {
2242 FCOORD re_rotation = block_it.data()->re_rotation();
2243 float re_theta = re_rotation.
angle();
2244 FCOORD classify_rotation = block_it.data()->classify_rotation();
2245 float classify_theta = classify_rotation.
angle();
2246 double rot_theta = - (re_theta - classify_theta) * 2.0 /
PI;
2247 if (rot_theta < 0) rot_theta += 4;
2248 int num_rotations =
static_cast<int>(rot_theta + 0.5);
2249 (*block_orientation)[i] = num_rotations;
2252 (*vertical_writing)[i] = classify_rotation.
y() != 0.0f;
2282 inT32 xstarts[] = {-32000};
2283 double quad_coeffs[] = {0, 0, baseline};
2288 ascender - (baseline + xheight),
2289 descender - baseline,
2296 int width = pixGetWidth(pix);
2297 int height = pixGetHeight(pix);
2298 BLOCK block(
"a character",
TRUE, 0, 0, 0, 0, width, height);
2305 C_BLOB_IT c_blob_it(list);
2306 if (c_blob_it.empty())
2309 C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2310 for (c_blob_it.forward();
2311 !c_blob_it.at_first();
2312 c_blob_it.forward()) {
2313 C_BLOB *c_blob = c_blob_it.data();
2314 ol_it.add_list_after(c_blob->
out_list());
2327 float x_center = (box.
left() + box.
right()) / 2.0f;
2339 float descender,
float ascender,
2340 bool numeric_mode, Pix* pix) {
2367 float best_rating = -100;
2371 BLOB_CHOICE_LIST choices;
2373 BLOB_CHOICE_IT choice_it;
2374 choice_it.set_to_list(&choices);
2375 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2376 choice_it.forward()) {
2377 if (choice_it.data()->rating() > best_rating) {
2378 best_rating = choice_it.data()->rating();
2401 pass1_result =
new PAGE_RES(
false, block_list,
2404 return pass1_result;
2408 int debug_level = 0;
2416 result_it, &models);
2428 TESS_CHAR(
float _cost,
const char *repr,
int len = -1) : cost(_cost) {
2429 length = (len == -1 ? strlen(repr) : len);
2430 unicode_repr =
new char[length + 1];
2431 strncpy(unicode_repr, repr, length);
2444 static
void add_space(TESS_CHAR_IT* it) {
2445 TESS_CHAR *t =
new TESS_CHAR(0,
" ");
2446 it->add_after_then_move(t);
2450 static float rating_to_cost(
float rating) {
2451 rating = 100 + rating;
2455 if (rating < 0) rating = 0;
2463 static void extract_result(TESS_CHAR_IT* out,
2467 while (page_res_it.word() !=
NULL) {
2475 int n = strlen(len);
2476 for (
int i = 0; i < n; i++) {
2480 out->add_after_then_move(tc);
2484 page_res_it.forward();
2501 TESS_CHAR_LIST tess_chars;
2502 TESS_CHAR_IT tess_chars_it(&tess_chars);
2503 extract_result(&tess_chars_it, page_res);
2504 tess_chars_it.move_to_first();
2505 int n = tess_chars.length();
2507 *lengths =
new int[n];
2508 *costs =
new float[n];
2514 for (tess_chars_it.mark_cycle_pt();
2515 !tess_chars_it.cycled_list();
2516 tess_chars_it.forward(), i++) {
2518 text_len += (*lengths)[i] = tc->
length;
2519 (*costs)[i] = tc->
cost;
2523 (*y1)[i] = tc->
box.
top();
2525 char *p = *text =
new char[text_len];
2527 tess_chars_it.move_to_first();
2528 for (tess_chars_it.mark_cycle_pt();
2529 !tess_chars_it.cycled_list();
2530 tess_chars_it.forward()) {
2548 int* feature_outline_index) {
2554 &cn_features, &fx_info, &outline_counts);
2559 *num_features = cn_features.
size();
2560 memcpy(int_features, &cn_features[0], *num_features *
sizeof(cn_features[0]));
2562 if (feature_outline_index !=
NULL) {
2564 for (
int i = 0; i < outline_counts.
size(); ++i) {
2565 while (f < outline_counts[i])
2566 feature_outline_index[f++] = i;
2574 int left,
int top,
int right,
int bottom) {
2575 TBOX box(left, bottom, right, top);
2576 BLOCK_IT b_it(blocks);
2577 for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2578 BLOCK* block = b_it.data();
2582 for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2583 ROW* row = r_it.data();
2587 for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2588 WERD* word = w_it.data();
2599 int num_max_matches,
2602 int* num_matches_returned) {
2603 BLOB_CHOICE_LIST* choices =
new BLOB_CHOICE_LIST;
2605 BLOB_CHOICE_IT choices_it(choices);
2606 int& index = *num_matches_returned;
2608 for (choices_it.mark_cycle_pt();
2609 !choices_it.cycled_list() && index < num_max_matches;
2610 choices_it.forward()) {
2613 ratings[index] = choice->
rating();
2616 *num_matches_returned = index;
2636 #ifndef ANDROID_BUILD
2647 for (ptr = text; *ptr; ptr++) {
2649 case '<': ret +=
"<";
break;
2650 case '>': ret +=
">";
break;
2651 case '&': ret +=
"&";
break;
2652 case '"': ret +=
""";
break;
2653 case '\'': ret +=
"'";
break;
2654 default: ret += *ptr;
C_BLOB_LIST * blob_list()
get blobs
void SavePixForCrash(int resolution, Pix *pix)
void extract_edges(Pix *pix, BLOCK *block)
const int kBytesPerNumber
static void ResetToDefaults(ParamsVectors *member_params)
Pix * GetThresholdedImage()
static void DeleteBlockList(BLOCK_LIST *block_list)
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
static const char * Version()
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 GetIntVariable(const char *name, int *value) const
const char kTesseractReject
void CorrectClassifyWords(PAGE_RES *page_res)
static size_t getOpenCLDevice(void **device)
tesseract::BoxWord * box_word
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
const int kBytesPer64BitNumber
bool DetectOS(OSResults *)
bool classify_bln_numeric_mode
const UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
int Recognize(ETEXT_DESC *monitor)
EquationDetect * equ_detect_
The equation detector.
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
void set_text(const char *new_text)
bool tessedit_train_from_boxes
void ExtractFontName(const STRING &filename, STRING *fontname)
void set_deadline_msecs(inT32 deadline_msecs)
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
struct TessResultRenderer TessResultRenderer
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
WERD_CHOICE * best_choice
void ResetDocumentDictionary()
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
void set_pix_thresholds(Pix *thresholds)
virtual Pix * GetPixRectThresholds()
const int kMaxCredibleResolution
void SetDictFunc(DictFunc f)
TruthCallback * truth_cb_
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
void SetBlackAndWhitelist()
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
PageIterator * AnalyseLayout()
ResultIterator * GetIterator()
const char * WordRecognitionLanguage() const
bool AddImage(TessBaseAPI *api)
#define PERF_COUNT_SUB(SUB)
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
const TBOX & BlobBox(int index) const
Pix ** mutable_pix_binary()
double matcher_good_threshold
void ResetAdaptiveClassifier()
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
bool Empty(PageIteratorLevel level) const
bool ParagraphIsLtr() const
bool textord_equation_detect
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)
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
void split(const char c, GenericVector< STRING > *splited)
virtual bool Next(PageIteratorLevel level)
void ReadConfigFile(const char *filename)
const STRING & unichar_lengths() const
const int kBytesPerBoxFileLine
#define BOOL_VAR(name, val, comment)
GenericVector< ParagraphModel * > * paragraph_models_
static TBLOB * MakeTBLOB(Pix *pix)
const char * GetUnichar(int unichar_id)
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) 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)
TBOX bounding_box() const
ImageThresholder * thresholder_
Image thresholding module.
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
virtual char * GetUTF8Text(PageIteratorLevel level) const
bool SetVariable(const char *name, const char *value)
TESS_LOCAL int TextLength(int *blob_count)
void set_pix_grey(Pix *grey_pix)
void set_source_resolution(int ppi)
TESS_CHAR(float _cost, const char *repr, int len=-1)
Pix * input_image_
Image used for searchable PDF.
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
STRING * language_
Last initialized language.
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
bool GetDoubleVariable(const char *name, double *value) const
Tesseract * get_sub_lang(int index) const
CubeRecoContext * GetCubeRecoContext() const
FILE * init_recog_training(const STRING &fname)
bool tessedit_write_images
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
Pix * GetBinaryImage(PageIteratorLevel level) const
const int kNumbersPerBlob
const char * GetInitLanguagesAsString() const
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
int tessedit_pageseg_mode
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
const char * GetInputName()
TESS_LOCAL bool InternalSetImage()
bool IsBinary() const
Returns true if the source image is binary.
int GetScaledYResolution() const
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
bool GetVariableAsString(const char *name, STRING *val)
float base_line(float xpos) const
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
const char * GetDatapath()
WERD_CHOICE * prev_word_best_choice_
Boxa * GetRegions(Pixa **pixa)
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
const STRING & unichar_string() const
PageSegMode GetPageSegMode() const
PolyBlockType BlockType() const
float angle() const
find angle
BLOCK_RES * block() const
STRING * output_file_
Name used by debug code.
void SetSourceResolution(int ppi)
C_OUTLINE_LIST * out_list()
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
StrongScriptDirection WordDirection() const
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
void SetRectangle(int left, int top, int width, int height)
int RecognizeForChopTest(ETEXT_DESC *monitor)
void ClearAdaptiveClassifier()
bool GetBoolVariable(const char *name, bool *value) const
void TidyUp(PAGE_RES *page_res)
void set_min_orientation_margin(double margin)
Boxa * GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
WERD_RES * restart_page()
static DawgCache * GlobalDawgCache()
virtual Pix * GetPixRectGrey()
CubeRecoContext * GetCubeRecoContext()
Tesseract *const tesseract() const
const int kMinCredibleResolution
Minimum believable resolution.
void chomp_string(char *str)
void SetInputName(const char *name)
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
int * AllWordConfidences()
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
int num_sub_langs() const
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
bool tessedit_resegment_from_line_boxes
void delete_data_pointers()
bool interactive_display_mode
int GetScaledEstimatedResolution() const
const char *const id_to_unichar(UNICHAR_ID id) const
GenericVector< IntParam * > int_params
Orientation and script detection only.
PAGE_RES * page_res_
The page-level data.
int GetSourceYResolution() const
char * GetBoxText(int page_number)
virtual TESS_LOCAL void Threshold(Pix **pix)
void read_config_file(const char *filename, SetParamConstraint constraint)
Automatic page segmentation, but no OSD, or OCR.
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
int GetSourceYResolution()
STRING * datapath_
Current location of tessdata.
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
STRING HOcrEscape(const char *text)
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
TBOX bounding_box() const
#define PERF_COUNT_START(FUNCT_NAME)
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void pgeditor_main(int width, int height, PAGE_RES *page_res)
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
#define MAX_NUM_INT_FEATURES
TESS_LOCAL int FindLines()
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
bool tessedit_resegment_from_boxes
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
const int kBlnBaselineOffset
virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
GenericVector< BoolParam * > bool_params
void SetInputImage(Pix *pix)
bool tessedit_ambigs_training
Boxa * GetStrips(Pixa **pixa, int **blockids)
void SetRectangle(int left, int top, int width, int height)
int GetScaleFactor() const
void signal_exit(int signal_code)
void SetSourceYResolution(int ppi)
void InitForAnalysePage()
const int kMaxBytesPerLine
const Dawg * GetDawg(int i) const
int Init(const char *datapath, const char *language, OcrEngineMode mode, char **configs, int configs_size, const GenericVector< STRING > *vars_vec, const GenericVector< STRING > *vars_values, bool set_only_non_debug_params)
Assume a single uniform block of text. (Default.)
void set_unlv_suspects(WERD_RES *word)
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
bool major_overlap(const TBOX &box) const
void ReadDebugConfigFile(const char *filename)
void SetOutputName(const char *name)
virtual void Run(A1, A2, A3, A4)=0
bool SetDebugVariable(const char *name, const char *value)
const char * GetStringVariable(const char *name) const
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
const int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
void add_str_int(const char *str, int number)
static TESS_LOCAL int TesseractExtractResult(char **text, int **lengths, float **costs, int **x0, int **y0, int **x1, int **y1, PAGE_RES *page_res)
bool IsEmpty() const
Return true if no image has been set.
#define TESSERACT_VERSION_STR
void assign(const char *cstr, int len)
TBOX intersection(const TBOX &box) const
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA * > *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel * > *models)
BLOCK_LIST * FindLinesCreateBlockList()
double min_orientation_margin
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
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)
const UNICHARSET & getUnicharset() const
Tesseract * osd_tesseract_
For orientation & script detection.
char * GetHOCRText(int page_number)
GenericVector< DoubleParam * > double_params
bool IsValidCharacter(const char *utf8_character)
int IntCastRounded(double x)
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)
void SetEquationDetect(EquationDetect *detector)
BLOCK_LIST * block_list_
The page layout.
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
const char * kOldVarsFile
bool PTIsTextType(PolyBlockType type)
static void CatchSignals()
bool GetTextDirection(int *out_offset, float *out_slope)
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
int InitLangMod(const char *datapath, const char *language)
BOOL8 flag(WERD_FLAGS mask) const
bool WriteTRFile(const STRING &filename)
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
bool contains_unichar(const char *const unichar_repr) const
void add_str_double(const char *str, double number)
float Confidence(PageIteratorLevel level) const
char * GetUTF8Text(PageIteratorLevel level) const
int IsValidWord(const char *word)
CRUNCH_MODE unlv_crunch_mode
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
tesseract::ParamsVectors * GlobalParams()
void InitAdaptiveClassifier(bool load_pre_trained_templates)
bool BeginDocument(const char *title)
virtual bool Next(PageIteratorLevel level)
bool PSM_OSD_ENABLED(int pageseg_mode)
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 LearnWord(const char *fontname, WERD_RES *word)
OcrEngineMode const oem() const
TBOX bounding_box() const
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
ROW_LIST * row_list()
get rows
Tesseract * tesseract_
The underlying data object.
Boxa * GetWords(Pixa **pixa)
int GetThresholdedImageScaleFactor() const
const char * string() const
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
void PrintVariables(FILE *fp) const
static void ClearPersistentCache()
MutableIterator * GetMutableIterator()
void SetPageSegMode(PageSegMode mode)
void SetFillLatticeFunc(FillLatticeFunc f)
bool tessedit_make_boxes_from_boxes
STRING * input_file_
Name used by training code.
void BestChoiceToCorrectText()
GenericVector< StringParam * > string_params
UNICHAR_ID unichar_id() const
void DumpPGM(const char *filename)
ADAPT_TEMPLATES AdaptedTemplates
bool recognition_done_
page_res_ contains recognition data.
const char * string() const
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language)
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
void ReSegmentByClassification(PAGE_RES *page_res)
TESS_LOCAL LTRResultIterator * GetLTRIterator()
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Boxa * GetConnectedComponents(Pixa **cc)
const char * c_str() const