tesseract  3.05.02
imagedata.h
Go to the documentation of this file.
1 // File: imagedata.h
3 // Description: Class to hold information about a single image and its
4 // corresponding boxes or text file.
5 // Author: Ray Smith
6 // Created: Mon Jul 22 14:17:06 PDT 2013
7 //
8 // (C) Copyright 2013, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 
20 #ifndef TESSERACT_IMAGE_IMAGEDATA_H_
21 #define TESSERACT_IMAGE_IMAGEDATA_H_
22 
23 
24 #include "genericvector.h"
25 #include "normalis.h"
26 #include "rect.h"
27 #include "strngs.h"
28 #include "svutil.h"
29 
30 struct Pix;
31 
32 namespace tesseract {
33 
34 // Amount of padding to apply in output pixels in feature mode.
35 const int kFeaturePadding = 2;
36 // Number of pixels to pad around text boxes.
37 const int kImagePadding = 4;
38 
39 // Enum to determine the caching and data sequencing strategy.
41  // Reads all of one file before moving on to the next. Requires samples to be
42  // shuffled across files. Uses the count of samples in the first file as
43  // the count in all the files to achieve high-speed random access. As a
44  // consequence, if subsequent files are smaller, they get entries used more
45  // than once, and if subsequent files are larger, some entries are not used.
46  // Best for larger data sets that don't fit in memory.
48  // Reads one sample from each file in rotation. Does not require shuffled
49  // samples, but is extremely disk-intensive. Samples in smaller files also
50  // get used more often than samples in larger files.
51  // Best for smaller data sets that mostly fit in memory.
53 };
54 
55 class WordFeature {
56  public:
57  WordFeature();
58  WordFeature(const FCOORD& fcoord, uinT8 dir);
59 
60  // Computes the maximum x and y value in the features.
61  static void ComputeSize(const GenericVector<WordFeature>& features,
62  int* max_x, int* max_y);
63  // Draws the features in the given window.
64  static void Draw(const GenericVector<WordFeature>& features,
65  ScrollView* window);
66 
67  // Accessors.
68  int x() const { return x_; }
69  int y() const { return y_; }
70  int dir() const { return dir_; }
71 
72  // Writes to the given file. Returns false in case of error.
73  bool Serialize(FILE* fp) const;
74  // Reads from the given file. Returns false in case of error.
75  // If swap is true, assumes a big/little-endian swap is needed.
76  bool DeSerialize(bool swap, FILE* fp);
77 
78  private:
79  inT16 x_;
80  uinT8 y_;
81  uinT8 dir_;
82 };
83 
84 // A floating-point version of WordFeature, used as an intermediate during
85 // scaling.
87  static void FromWordFeatures(const GenericVector<WordFeature>& word_features,
88  GenericVector<FloatWordFeature>* float_features);
89  // Sort function to sort first by x-bucket, then by y.
90  static int SortByXBucket(const void*, const void*);
91 
92  float x;
93  float y;
94  float dir;
95  int x_bucket;
96 };
97 
98 // Class to hold information on a single image:
99 // Filename, cached image as a Pix*, character boxes, text transcription.
100 // The text transcription is the ground truth UTF-8 text for the image.
101 // Character boxes are optional and indicate the desired segmentation of
102 // the text into recognition units.
103 class ImageData {
104  public:
105  ImageData();
106  // Takes ownership of the pix.
107  ImageData(bool vertical, Pix* pix);
108  ~ImageData();
109 
110  // Builds and returns an ImageData from the basic data. Note that imagedata,
111  // truth_text, and box_text are all the actual file data, NOT filenames.
112  static ImageData* Build(const char* name, int page_number, const char* lang,
113  const char* imagedata, int imagedatasize,
114  const char* truth_text, const char* box_text);
115 
116  // Writes to the given file. Returns false in case of error.
117  bool Serialize(TFile* fp) const;
118  // Reads from the given file. Returns false in case of error.
119  // If swap is true, assumes a big/little-endian swap is needed.
120  bool DeSerialize(bool swap, TFile* fp);
121  // As DeSerialize, but only seeks past the data - hence a static method.
122  static bool SkipDeSerialize(bool swap, tesseract::TFile* fp);
123 
124  // Other accessors.
125  const STRING& imagefilename() const {
126  return imagefilename_;
127  }
128  void set_imagefilename(const STRING& name) {
129  imagefilename_ = name;
130  }
131  int page_number() const {
132  return page_number_;
133  }
134  void set_page_number(int num) {
135  page_number_ = num;
136  }
138  return image_data_;
139  }
140  const STRING& language() const {
141  return language_;
142  }
143  void set_language(const STRING& lang) {
144  language_ = lang;
145  }
146  const STRING& transcription() const {
147  return transcription_;
148  }
149  const GenericVector<TBOX>& boxes() const {
150  return boxes_;
151  }
153  return box_texts_;
154  }
155  const STRING& box_text(int index) const {
156  return box_texts_[index];
157  }
158  // Saves the given Pix as a PNG-encoded string and destroys it.
159  void SetPix(Pix* pix);
160  // Returns the Pix image for *this. Must be pixDestroyed after use.
161  Pix* GetPix() const;
162  // Gets anything and everything with a non-NULL pointer, prescaled to a
163  // given target_height (if 0, then the original image height), and aligned.
164  // Also returns (if not NULL) the width and height of the scaled image.
165  // The return value is the scaled Pix, which must be pixDestroyed after use,
166  // and scale_factor (if not NULL) is set to the scale factor that was applied
167  // to the image to achieve the target_height.
168  Pix* PreScale(int target_height, int max_height, float* scale_factor,
169  int* scaled_width, int* scaled_height,
170  GenericVector<TBOX>* boxes) const;
171 
172  int MemoryUsed() const;
173 
174  // Draws the data in a new window.
175  void Display() const;
176 
177  // Adds the supplied boxes and transcriptions that correspond to the correct
178  // page number.
179  void AddBoxes(const GenericVector<TBOX>& boxes,
180  const GenericVector<STRING>& texts,
181  const GenericVector<int>& box_pages);
182 
183  private:
184  // Saves the given Pix as a PNG-encoded string and destroys it.
185  static void SetPixInternal(Pix* pix, GenericVector<char>* image_data);
186  // Returns the Pix image for the image_data. Must be pixDestroyed after use.
187  static Pix* GetPixInternal(const GenericVector<char>& image_data);
188  // Parses the text string as a box file and adds any discovered boxes that
189  // match the page number. Returns false on error.
190  bool AddBoxes(const char* box_text);
191 
192  private:
193  STRING imagefilename_; // File to read image from.
194  inT32 page_number_; // Page number if multi-page tif or -1.
195  GenericVector<char> image_data_; // PNG file data.
196  STRING language_; // Language code for image.
197  STRING transcription_; // UTF-8 ground truth of image.
198  GenericVector<TBOX> boxes_; // If non-empty boxes of the image.
199  GenericVector<STRING> box_texts_; // String for text in each box.
200  bool vertical_text_; // Image has been rotated from vertical.
201 };
202 
203 // A collection of ImageData that knows roughly how much memory it is using.
205  friend void* ReCachePagesFunc(void* data);
206 
207  public:
208  explicit DocumentData(const STRING& name);
209  ~DocumentData();
210 
211  // Reads all the pages in the given lstmf filename to the cache. The reader
212  // is used to read the file.
213  bool LoadDocument(const char* filename, const char* lang, int start_page,
214  inT64 max_memory, FileReader reader);
215  // Sets up the document, without actually loading it.
216  void SetDocument(const char* filename, const char* lang, inT64 max_memory,
217  FileReader reader);
218  // Writes all the pages to the given filename. Returns false on error.
219  bool SaveDocument(const char* filename, FileWriter writer);
220  bool SaveToBuffer(GenericVector<char>* buffer);
221 
222  // Adds the given page data to this document, counting up memory.
223  void AddPageToDocument(ImageData* page);
224 
225  const STRING& document_name() const {
226  SVAutoLock lock(&general_mutex_);
227  return document_name_;
228  }
229  int NumPages() const {
230  SVAutoLock lock(&general_mutex_);
231  return total_pages_;
232  }
233  inT64 memory_used() const {
234  SVAutoLock lock(&general_mutex_);
235  return memory_used_;
236  }
237  // If the given index is not currently loaded, loads it using a separate
238  // thread. Note: there are 4 cases:
239  // Document uncached: IsCached() returns false, total_pages_ < 0.
240  // Required page is available: IsPageAvailable returns true. In this case,
241  // total_pages_ > 0 and
242  // pages_offset_ <= index%total_pages_ <= pages_offset_+pages_.size()
243  // Pages are loaded, but the required one is not.
244  // The requested page is being loaded by LoadPageInBackground. In this case,
245  // index == pages_offset_. Once the loading starts, the pages lock is held
246  // until it completes, at which point IsPageAvailable will unblock and return
247  // true.
248  void LoadPageInBackground(int index);
249  // Returns a pointer to the page with the given index, modulo the total
250  // number of pages. Blocks until the background load is completed.
251  const ImageData* GetPage(int index);
252  // Returns true if the requested page is available, and provides a pointer,
253  // which may be NULL if the document is empty. May block, even though it
254  // doesn't guarantee to return true.
255  bool IsPageAvailable(int index, ImageData** page);
256  // Takes ownership of the given page index. The page is made NULL in *this.
257  ImageData* TakePage(int index) {
258  SVAutoLock lock(&pages_mutex_);
259  ImageData* page = pages_[index];
260  pages_[index] = NULL;
261  return page;
262  }
263  // Returns true if the document is currently loaded or in the process of
264  // loading.
265  bool IsCached() const { return NumPages() >= 0; }
266  // Removes all pages from memory and frees the memory, but does not forget
267  // the document metadata. Returns the memory saved.
268  inT64 UnCache();
269 
270  private:
271  // Sets the value of total_pages_ behind a mutex.
272  void set_total_pages(int total) {
273  SVAutoLock lock(&general_mutex_);
274  total_pages_ = total;
275  }
276  void set_memory_used(inT64 memory_used) {
277  SVAutoLock lock(&general_mutex_);
278  memory_used_ = memory_used;
279  }
280  // Locks the pages_mutex_ and Loads as many pages can fit in max_memory_
281  // starting at index pages_offset_.
282  bool ReCachePages();
283 
284  private:
285  // A name for this document.
286  STRING document_name_;
287  // The language of this document.
288  STRING lang_;
289  // A group of pages that corresponds in some loose way to a document.
290  PointerVector<ImageData> pages_;
291  // Page number of the first index in pages_.
292  int pages_offset_;
293  // Total number of pages in document (may exceed size of pages_.)
294  int total_pages_;
295  // Total of all pix sizes in the document.
296  inT64 memory_used_;
297  // Max memory to use at any time.
298  inT64 max_memory_;
299  // Saved reader from LoadDocument to allow re-caching.
300  FileReader reader_;
301  // Mutex that protects pages_ and pages_offset_ against multiple parallel
302  // loads, and provides a wait for page.
303  SVMutex pages_mutex_;
304  // Mutex that protects other data members that callers want to access without
305  // waiting for a load operation.
306  mutable SVMutex general_mutex_;
307 };
308 
309 // A collection of DocumentData that knows roughly how much memory it is using.
310 // Note that while it supports background read-ahead, it assumes that a single
311 // thread is accessing documents, ie it is not safe for multiple threads to
312 // access different documents in parallel, as one may de-cache the other's
313 // content.
315  public:
316  explicit DocumentCache(inT64 max_memory);
317  ~DocumentCache();
318 
319  // Deletes all existing documents from the cache.
320  void Clear() {
321  documents_.clear();
322  num_pages_per_doc_ = 0;
323  }
324  // Adds all the documents in the list of filenames, counting memory.
325  // The reader is used to read the files.
326  bool LoadDocuments(const GenericVector<STRING>& filenames, const char* lang,
327  CachingStrategy cache_strategy, FileReader reader);
328 
329  // Adds document to the cache.
330  bool AddToCache(DocumentData* data);
331 
332  // Finds and returns a document by name.
333  DocumentData* FindDocument(const STRING& document_name) const;
334 
335  // Returns a page by serial number using the current cache_strategy_ to
336  // determine the mapping from serial number to page.
337  const ImageData* GetPageBySerial(int serial) {
338  if (cache_strategy_ == CS_SEQUENTIAL)
339  return GetPageSequential(serial);
340  else
341  return GetPageRoundRobin(serial);
342  }
343 
345  return documents_;
346  }
347  // Returns the total number of pages in an epoch. For CS_ROUND_ROBIN cache
348  // strategy, could take a long time.
349  int TotalPages();
350 
351  private:
352  // Returns a page by serial number, selecting them in a round-robin fashion
353  // from all the documents. Highly disk-intensive, but doesn't need samples
354  // to be shuffled between files to begin with.
355  const ImageData* GetPageRoundRobin(int serial);
356  // Returns a page by serial number, selecting them in sequence from each file.
357  // Requires the samples to be shuffled between the files to give a random or
358  // uniform distribution of data. Less disk-intensive than GetPageRoundRobin.
359  const ImageData* GetPageSequential(int serial);
360 
361  // Helper counts the number of adjacent cached neighbour documents_ of index
362  // looking in direction dir, ie index+dir, index+2*dir etc.
363  int CountNeighbourDocs(int index, int dir);
364 
365  // A group of pages that corresponds in some loose way to a document.
366  PointerVector<DocumentData> documents_;
367  // Strategy to use for caching and serializing data samples.
368  CachingStrategy cache_strategy_;
369  // Number of pages in the first document, used as a divisor in
370  // GetPageSequential to determine the document index.
371  int num_pages_per_doc_;
372  // Max memory allowed in this cache.
373  inT64 max_memory_;
374 };
375 
376 } // namespace tesseract
377 
378 
379 #endif // TESSERACT_IMAGE_IMAGEDATA_H_
const ImageData * GetPageBySerial(int serial)
Definition: imagedata.h:337
void SetPix(Pix *pix)
Definition: imagedata.cpp:209
static void ComputeSize(const GenericVector< WordFeature > &features, int *max_x, int *max_y)
Definition: imagedata.cpp:55
Pix * GetPix() const
Definition: imagedata.cpp:214
bool LoadDocument(const char *filename, const char *lang, int start_page, inT64 max_memory, FileReader reader)
Definition: imagedata.cpp:387
short inT16
Definition: host.h:33
bool SaveDocument(const char *filename, FileWriter writer)
Definition: imagedata.cpp:408
bool SaveToBuffer(GenericVector< char > *buffer)
Definition: imagedata.cpp:418
static void Draw(const GenericVector< WordFeature > &features, ScrollView *window)
Definition: imagedata.cpp:66
friend void * ReCachePagesFunc(void *data)
Definition: imagedata.cpp:366
const int kImagePadding
Definition: imagedata.h:37
int NumPages() const
Definition: imagedata.h:229
void SetDocument(const char *filename, const char *lang, inT64 max_memory, FileReader reader)
Definition: imagedata.cpp:396
const GenericVector< TBOX > & boxes() const
Definition: imagedata.h:149
bool DeSerialize(bool swap, FILE *fp)
Definition: imagedata.cpp:91
ImageData * TakePage(int index)
Definition: imagedata.h:257
void set_page_number(int num)
Definition: imagedata.h:134
unsigned char uinT8
Definition: host.h:32
bool IsCached() const
Definition: imagedata.h:265
const GenericVector< char > & image_data() const
Definition: imagedata.h:137
void set_language(const STRING &lang)
Definition: imagedata.h:143
const int kFeaturePadding
Definition: imagedata.h:35
bool Serialize(TFile *fp) const
Definition: imagedata.cpp:165
const PointerVector< DocumentData > & documents() const
Definition: imagedata.h:344
const ImageData * GetPage(int index)
Definition: imagedata.cpp:448
bool LoadDocuments(const GenericVector< STRING > &filenames, const char *lang, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:558
DocumentCache(inT64 max_memory)
Definition: imagedata.cpp:552
static ImageData * Build(const char *name, int page_number, const char *lang, const char *imagedata, int imagedatasize, const char *truth_text, const char *box_text)
Definition: imagedata.cpp:134
bool AddToCache(DocumentData *data)
Definition: imagedata.cpp:584
void LoadPageInBackground(int index)
Definition: imagedata.cpp:434
void set_imagefilename(const STRING &name)
Definition: imagedata.h:128
CachingStrategy
Definition: imagedata.h:40
const STRING & document_name() const
Definition: imagedata.h:225
bool IsPageAvailable(int index, ImageData **page)
Definition: imagedata.cpp:472
long long int inT64
Definition: host.h:41
const GenericVector< STRING > & box_texts() const
Definition: imagedata.h:152
void Display() const
Definition: imagedata.cpp:273
int page_number() const
Definition: imagedata.h:131
const STRING & transcription() const
Definition: imagedata.h:146
bool Serialize(FILE *fp) const
Definition: imagedata.cpp:83
DocumentData(const STRING &name)
Definition: imagedata.cpp:372
int inT32
Definition: host.h:35
static int SortByXBucket(const void *, const void *)
Definition: imagedata.cpp:114
Definition: strngs.h:44
Definition: points.h:189
const STRING & box_text(int index) const
Definition: imagedata.h:155
bool DeSerialize(bool swap, TFile *fp)
Definition: imagedata.cpp:180
Definition: svutil.h:90
Pix * PreScale(int target_height, int max_height, float *scale_factor, int *scaled_width, int *scaled_height, GenericVector< TBOX > *boxes) const
Definition: imagedata.cpp:224
void AddBoxes(const GenericVector< TBOX > &boxes, const GenericVector< STRING > &texts, const GenericVector< int > &box_pages)
Definition: imagedata.cpp:311
inT64 memory_used() const
Definition: imagedata.h:233
void AddPageToDocument(ImageData *page)
Definition: imagedata.cpp:426
static void FromWordFeatures(const GenericVector< WordFeature > &word_features, GenericVector< FloatWordFeature > *float_features)
Definition: imagedata.cpp:99
int MemoryUsed() const
Definition: imagedata.cpp:268
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
static bool SkipDeSerialize(bool swap, tesseract::TFile *fp)
Definition: imagedata.cpp:196
const STRING & imagefilename() const
Definition: imagedata.h:125
const STRING & language() const
Definition: imagedata.h:140
DocumentData * FindDocument(const STRING &document_name) const
Definition: imagedata.cpp:591
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)