|
tesseract 3.04.01
|
00001 /********************************************************************** 00002 * File: boxread.cpp 00003 * Description: Read data from a box file. 00004 * Author: Ray Smith 00005 * Created: Fri Aug 24 17:47:23 PDT 2007 00006 * 00007 * (C) Copyright 2007, Google Inc. 00008 ** Licensed under the Apache License, Version 2.0 (the "License"); 00009 ** you may not use this file except in compliance with the License. 00010 ** You may obtain a copy of the License at 00011 ** http://www.apache.org/licenses/LICENSE-2.0 00012 ** Unless required by applicable law or agreed to in writing, software 00013 ** distributed under the License is distributed on an "AS IS" BASIS, 00014 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00015 ** See the License for the specific language governing permissions and 00016 ** limitations under the License. 00017 * 00018 **********************************************************************/ 00019 00020 #include "boxread.h" 00021 #include <string.h> 00022 00023 #include "fileerr.h" 00024 #include "rect.h" 00025 #include "strngs.h" 00026 #include "tprintf.h" 00027 #include "unichar.h" 00028 00029 // Special char code used to identify multi-blob labels. 00030 static const char* kMultiBlobLabelCode = "WordStr"; 00031 00032 // Open the boxfile based on the given image filename. 00033 FILE* OpenBoxFile(const STRING& fname) { 00034 STRING filename = BoxFileName(fname); 00035 FILE* box_file = NULL; 00036 if (!(box_file = fopen(filename.string(), "rb"))) { 00037 CANTOPENFILE.error("read_next_box", TESSEXIT, 00038 "Can't open box file %s", 00039 filename.string()); 00040 } 00041 return box_file; 00042 } 00043 00044 // Reads all boxes from the given filename. 00045 // Reads a specific target_page number if >= 0, or all pages otherwise. 00046 // Skips blanks if skip_blanks is true. 00047 // The UTF-8 label of the box is put in texts, and the full box definition as 00048 // a string is put in box_texts, with the corresponding page number in pages. 00049 // Each of the output vectors is optional (may be NULL). 00050 // Returns false if no boxes are found. 00051 bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING& filename, 00052 GenericVector<TBOX>* boxes, 00053 GenericVector<STRING>* texts, 00054 GenericVector<STRING>* box_texts, 00055 GenericVector<int>* pages) { 00056 GenericVector<char> box_data; 00057 if (!tesseract::LoadDataFromFile(BoxFileName(filename), &box_data)) 00058 return false; 00059 return ReadMemBoxes(target_page, skip_blanks, &box_data[0], boxes, texts, 00060 box_texts, pages); 00061 } 00062 00063 // Reads all boxes from the string. Otherwise, as ReadAllBoxes. 00064 bool ReadMemBoxes(int target_page, bool skip_blanks, const char* box_data, 00065 GenericVector<TBOX>* boxes, 00066 GenericVector<STRING>* texts, 00067 GenericVector<STRING>* box_texts, 00068 GenericVector<int>* pages) { 00069 STRING box_str(box_data); 00070 GenericVector<STRING> lines; 00071 box_str.split('\n', &lines); 00072 if (lines.empty()) return false; 00073 int num_boxes = 0; 00074 for (int i = 0; i < lines.size(); ++i) { 00075 int page = 0; 00076 STRING utf8_str; 00077 TBOX box; 00078 if (!ParseBoxFileStr(lines[i].string(), &page, &utf8_str, &box)) { 00079 continue; 00080 } 00081 if (skip_blanks && (utf8_str == " " || utf8_str == "\t")) continue; 00082 if (target_page >= 0 && page != target_page) continue; 00083 if (boxes != NULL) boxes->push_back(box); 00084 if (texts != NULL) texts->push_back(utf8_str); 00085 if (box_texts != NULL) { 00086 STRING full_text; 00087 MakeBoxFileStr(utf8_str.string(), box, target_page, &full_text); 00088 box_texts->push_back(full_text); 00089 } 00090 if (pages != NULL) pages->push_back(page); 00091 ++num_boxes; 00092 } 00093 return num_boxes > 0; 00094 } 00095 00096 // Returns the box file name corresponding to the given image_filename. 00097 STRING BoxFileName(const STRING& image_filename) { 00098 STRING box_filename = image_filename; 00099 const char *lastdot = strrchr(box_filename.string(), '.'); 00100 if (lastdot != NULL) 00101 box_filename.truncate_at(lastdot - box_filename.string()); 00102 00103 box_filename += ".box"; 00104 return box_filename; 00105 } 00106 00107 // TODO(rays) convert all uses of ReadNextBox to use the new ReadAllBoxes. 00108 // Box files are used ONLY DURING TRAINING, but by both processes of 00109 // creating tr files with tesseract, and unicharset_extractor. 00110 // ReadNextBox factors out the code to interpret a line of a box 00111 // file so that applybox and unicharset_extractor interpret the same way. 00112 // This function returns the next valid box file utf8 string and coords 00113 // and returns true, or false on eof (and closes the file). 00114 // It ignores the utf8 file signature ByteOrderMark (U+FEFF=EF BB BF), checks 00115 // for valid utf-8 and allows space or tab between fields. 00116 // utf8_str is set with the unichar string, and bounding box with the box. 00117 // If there are page numbers in the file, it reads them all. 00118 bool ReadNextBox(int *line_number, FILE* box_file, 00119 STRING* utf8_str, TBOX* bounding_box) { 00120 return ReadNextBox(-1, line_number, box_file, utf8_str, bounding_box); 00121 } 00122 00123 // As ReadNextBox above, but get a specific page number. (0-based) 00124 // Use -1 to read any page number. Files without page number all 00125 // read as if they are page 0. 00126 bool ReadNextBox(int target_page, int *line_number, FILE* box_file, 00127 STRING* utf8_str, TBOX* bounding_box) { 00128 int page = 0; 00129 char buff[kBoxReadBufSize]; // boxfile read buffer 00130 char *buffptr = buff; 00131 00132 while (fgets(buff, sizeof(buff) - 1, box_file)) { 00133 (*line_number)++; 00134 00135 buffptr = buff; 00136 const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr); 00137 if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf) 00138 buffptr += 3; // Skip unicode file designation. 00139 // Check for blank lines in box file 00140 if (*buffptr == '\n' || *buffptr == '\0') continue; 00141 // Skip blank boxes. 00142 if (*buffptr == ' ' || *buffptr == '\t') continue; 00143 if (*buffptr != '\0') { 00144 if (!ParseBoxFileStr(buffptr, &page, utf8_str, bounding_box)) { 00145 tprintf("Box file format error on line %i; ignored\n", *line_number); 00146 continue; 00147 } 00148 if (target_page >= 0 && target_page != page) 00149 continue; // Not on the appropriate page. 00150 return true; // Successfully read a box. 00151 } 00152 } 00153 fclose(box_file); 00154 return false; // EOF 00155 } 00156 00157 // Parses the given box file string into a page_number, utf8_str, and 00158 // bounding_box. Returns true on a successful parse. 00159 // The box file is assumed to contain box definitions, one per line, of the 00160 // following format for blob-level boxes: 00161 // <UTF8 str> <left> <bottom> <right> <top> <page id> 00162 // and for word/line-level boxes: 00163 // WordStr <left> <bottom> <right> <top> <page id> #<space-delimited word str> 00164 // See applyybox.cpp for more information. 00165 bool ParseBoxFileStr(const char* boxfile_str, int* page_number, 00166 STRING* utf8_str, TBOX* bounding_box) { 00167 *bounding_box = TBOX(); // Initialize it to empty. 00168 *utf8_str = ""; 00169 char uch[kBoxReadBufSize]; 00170 const char *buffptr = boxfile_str; 00171 // Read the unichar without messing up on Tibetan. 00172 // According to issue 253 the utf-8 surrogates 85 and A0 are treated 00173 // as whitespace by sscanf, so it is more reliable to just find 00174 // ascii space and tab. 00175 int uch_len = 0; 00176 // Skip unicode file designation, if present. 00177 const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr); 00178 if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf) 00179 buffptr += 3; 00180 // Allow a single blank as the UTF-8 string. Check for empty string and 00181 // then blindly eat the first character. 00182 if (*buffptr == '\0') return false; 00183 do { 00184 uch[uch_len++] = *buffptr++; 00185 } while (*buffptr != '\0' && *buffptr != ' ' && *buffptr != '\t' && 00186 uch_len < kBoxReadBufSize - 1); 00187 uch[uch_len] = '\0'; 00188 if (*buffptr != '\0') ++buffptr; 00189 int x_min, y_min, x_max, y_max; 00190 *page_number = 0; 00191 int count = sscanf(buffptr, "%d %d %d %d %d", 00192 &x_min, &y_min, &x_max, &y_max, page_number); 00193 if (count != 5 && count != 4) { 00194 tprintf("Bad box coordinates in boxfile string! %s\n", ubuf); 00195 return false; 00196 } 00197 // Test for long space-delimited string label. 00198 if (strcmp(uch, kMultiBlobLabelCode) == 0 && 00199 (buffptr = strchr(buffptr, '#')) != NULL) { 00200 strncpy(uch, buffptr + 1, kBoxReadBufSize - 1); 00201 uch[kBoxReadBufSize - 1] = '\0'; // Prevent buffer overrun. 00202 chomp_string(uch); 00203 uch_len = strlen(uch); 00204 } 00205 // Validate UTF8 by making unichars with it. 00206 int used = 0; 00207 while (used < uch_len) { 00208 UNICHAR ch(uch + used, uch_len - used); 00209 int new_used = ch.utf8_len(); 00210 if (new_used == 0) { 00211 tprintf("Bad UTF-8 str %s starts with 0x%02x at col %d\n", 00212 uch + used, uch[used], used + 1); 00213 return false; 00214 } 00215 used += new_used; 00216 } 00217 *utf8_str = uch; 00218 if (x_min > x_max) Swap(&x_min, &x_max); 00219 if (y_min > y_max) Swap(&y_min, &y_max); 00220 bounding_box->set_to_given_coords(x_min, y_min, x_max, y_max); 00221 return true; // Successfully read a box. 00222 } 00223 00224 // Creates a box file string from a unichar string, TBOX and page number. 00225 void MakeBoxFileStr(const char* unichar_str, const TBOX& box, int page_num, 00226 STRING* box_str) { 00227 *box_str = unichar_str; 00228 box_str->add_str_int(" ", box.left()); 00229 box_str->add_str_int(" ", box.bottom()); 00230 box_str->add_str_int(" ", box.right()); 00231 box_str->add_str_int(" ", box.top()); 00232 box_str->add_str_int(" ", page_num); 00233 } 00234