Update Tesseract to version 4.

This commit is contained in:
Damiano Galassi committed 2019-06-01 14:16:05 +02:00
1 parent d157ebda2d
commit d0696c4df9
56 files changed
+10765 -3462

No files matched your search

+3 -3
View File
@@ -17,8 +17,8 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_APITYPES_H__
#define TESSERACT_API_APITYPES_H__
#ifndef TESSERACT_API_APITYPES_H_
#define TESSERACT_API_APITYPES_H_
#include "publictypes.h"
@@ -30,4 +30,4 @@
// than the lower-level one, and lower-level code should be sure to include
// only the lower-level file.
#endif // TESSERACT_API_APITYPES_H__
#endif // TESSERACT_API_APITYPES_H_
+292 -159
View File
@@ -2,7 +2,6 @@
// File: baseapi.h
// Description: Simple API for calling tesseract.
// Author: Ray Smith
// Created: Fri Oct 06 15:35:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,32 +16,32 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_BASEAPI_H__
#define TESSERACT_API_BASEAPI_H__
#ifndef TESSERACT_API_BASEAPI_H_
#define TESSERACT_API_BASEAPI_H_
#include <stdio.h>
#include <cstdio>
// To avoid collision with other typenames include the ABSOLUTE MINIMUM
// complexity of includes here. Use forward declarations wherever possible
// and hide includes of complex types in baseapi.cpp.
#include "platform.h"
#include "tess_version.h"
#include "apitypes.h"
#include "pageiterator.h"
#include "platform.h"
#include "publictypes.h"
#include "resultiterator.h"
#include "serialis.h"
#include "tesscallback.h"
#include "thresholder.h"
#include "unichar.h"
#include "tesscallback.h"
#include "publictypes.h"
#include "pageiterator.h"
#include "resultiterator.h"
template <typename T> class GenericVector;
class PAGE_RES;
class PAGE_RES_IT;
class ParagraphModel;
class BlamerBundle;
struct BlamerBundle;
class BLOCK_LIST;
class DENORM;
class IMAGE;
class MATRIX;
class PBLOB;
class ROW;
class STRING;
class WERD;
@@ -54,42 +53,42 @@ class ETEXT_DESC;
struct OSResults;
class TBOX;
class UNICHARSET;
class WERD_CHOICE_LIST;
// From oldlist.h
// TODO(antonova): remove when oldlist is deprecated.
struct list_rec;
typedef list_rec *LIST;
#define MAX_NUM_INT_FEATURES 512
struct INT_FEATURE_STRUCT;
typedef INT_FEATURE_STRUCT *INT_FEATURE;
typedef INT_FEATURE_STRUCT INT_FEATURE_ARRAY[MAX_NUM_INT_FEATURES];
struct TBLOB;
namespace tesseract {
class CubeRecoContext;
class Dawg;
class Dict;
class EquationDetect;
class PageIterator;
class LTRResultIterator;
class ResultIterator;
class MutableIterator;
class TessResultRenderer;
class Tesseract;
class Trie;
class Wordrec;
typedef int (Dict::*DictFunc)(void* void_dawg_args,
const UNICHARSET& unicharset,
UNICHAR_ID unichar_id, bool word_end) const;
typedef double (Dict::*ProbabilityInContextFunc)(const char* lang,
const char* context,
int context_bytes,
const char* character,
int character_bytes);
typedef float (Dict::*ParamsModelClassifyFunc)(
const char *lang, void *path);
typedef void (Wordrec::*FillLatticeFunc)(const MATRIX &ratings,
const LIST &best_choices,
const WERD_CHOICE_LIST &best_choices,
const UNICHARSET &unicharset,
BlamerBundle *blamer_bundle);
typedef TessCallback3<const UNICHARSET &, int, PAGE_RES *> TruthCallback;
typedef TessCallback4<const UNICHARSET &, int, PageIterator *, Pix *>
TruthCallback;
/**
* Base class for all tesseract APIs.
@@ -110,10 +109,38 @@ class TESS_API TessBaseAPI {
static const char* Version();
/**
* Set the name of the input file. Needed only for training and
* reading a UNLV zone file.
* If compiled with OpenCL AND an available OpenCL
* device is deemed faster than serial code, then
* "device" is populated with the cl_device_id
* and returns sizeof(cl_device_id)
* otherwise *device=nullptr and returns 0.
*/
static size_t getOpenCLDevice(void **device);
/**
* Writes the thresholded image to stderr as a PBM file on receipt of a
* SIGSEGV, SIGFPE, or SIGBUS signal. (Linux/Unix only).
*/
static void CatchSignals();
/**
* Set the name of the input file. Needed for training and
* reading a UNLV zone file, and for searchable PDF output.
*/
void SetInputName(const char* name);
/**
* These functions are required for searchable PDF output.
* We need our hands on the input file so that we can include
* it in the PDF without transcoding. If that is not possible,
* we need the original image. Finally, resolution metadata
* is stored in the PDF so we need that as well.
*/
const char* GetInputName();
// Takes ownership of the input pix.
void SetInputImage(Pix *pix);
Pix* GetInputImage();
int GetSourceYResolution();
const char* GetDatapath();
/** Set the name of the bonus output files. Needed only for debugging. */
void SetOutputName(const char* name);
@@ -127,8 +154,6 @@ class TESS_API TessBaseAPI {
* Or SetVariable("classify_bln_numeric_mode", "1"); to set numeric-only mode.
* SetVariable may be used before Init, but settings will revert to
* defaults on End().
* TODO(rays) Add a command-line option to dump the parameters to stdout
* and add a pointer to it in the FAQ
*
* Note: Must be called after Init(). Only works for non-init variables
* (init variables should be passed to Init()).
@@ -173,7 +198,7 @@ class TESS_API TessBaseAPI {
*
* The datapath must be the name of the parent directory of tessdata and
* must end in / . Any name after the last / will be stripped.
* The language is (usually) an ISO 639-3 string or NULL will default to eng.
* The language is (usually) an ISO 639-3 string or nullptr will default to eng.
* It is entirely safe (and eventually will be efficient too) to call
* Init multiple times on the same instance to change language, or just
* to reset the classifier.
@@ -204,11 +229,18 @@ class TESS_API TessBaseAPI {
const GenericVector<STRING> *vars_values,
bool set_only_non_debug_params);
int Init(const char* datapath, const char* language, OcrEngineMode oem) {
return Init(datapath, language, oem, NULL, 0, NULL, NULL, false);
return Init(datapath, language, oem, nullptr, 0, nullptr, nullptr, false);
}
int Init(const char* datapath, const char* language) {
return Init(datapath, language, OEM_DEFAULT, NULL, 0, NULL, NULL, false);
return Init(datapath, language, OEM_DEFAULT, nullptr, 0, nullptr, nullptr, false);
}
// In-memory version reads the traineddata file directly from the given
// data[data_size] array, and/or reads data via a FileReader.
int Init(const char* data, int data_size, 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, FileReader reader);
/**
* Returns the languages string used in the last valid initialization.
@@ -228,7 +260,7 @@ class TESS_API TessBaseAPI {
void GetLoadedLanguagesAsVector(GenericVector<STRING>* langs) const;
/**
* Returns the available languages in the vector of STRINGs.
* Returns the available languages in the sorted vector of STRINGs.
*/
void GetAvailableLanguagesAsVector(GenericVector<STRING>* langs) const;
@@ -303,9 +335,7 @@ class TESS_API TessBaseAPI {
/**
* Provide an image for Tesseract to recognize. Format is as
* TesseractRect above. Does not copy the image buffer, or take
* ownership. The source image may be destroyed after Recognize is called,
* either explicitly or implicitly via one of the Get*Text functions.
* TesseractRect above. Copies the image buffer and converts to Pix.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
@@ -315,15 +345,13 @@ class TESS_API TessBaseAPI {
/**
* Provide an image for Tesseract to recognize. As with SetImage above,
* Tesseract doesn't take a copy or ownership or pixDestroy the image, so
* it must persist until after Recognize.
* Tesseract takes its own copy of the image, so it need not persist until
* after Recognize.
* Pix vs raw, which to use?
* Use Pix where possible. A future version of Tesseract may choose to use Pix
* as its internal representation and discard IMAGE altogether.
* Because of that, an implementation that sources and targets Pix may end up
* with less copies than an implementation that does not.
* Use Pix where possible. Tesseract uses Pix as its internal representation
* and it is therefore more efficient to provide a Pix directly.
*/
void SetImage(const Pix* pix);
void SetImage(Pix* pix);
/**
* Set the resolution of the source image in pixels per inch so font size
@@ -346,8 +374,7 @@ class TESS_API TessBaseAPI {
* delete it when it it is replaced or the API is destructed.
*/
void SetThresholder(ImageThresholder* thresholder) {
if (thresholder_ != NULL)
delete thresholder_;
delete thresholder_;
thresholder_ = thresholder;
ClearResults();
}
@@ -370,17 +397,28 @@ class TESS_API TessBaseAPI {
* Get the textlines as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each line is also returned
* as an array of one element per line. delete [] after use.
* If raw_image is true, then extract from the original image instead of the
* thresholded image and pad by raw_padding pixels.
* If blockids is not nullptr, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
* If paraids is not nullptr, the paragraph-id of each line within its block is
* also returned as an array of one element per line. delete [] after use.
*/
Boxa* GetTextlines(Pixa** pixa, int** blockids);
Boxa* GetTextlines(const bool raw_image, const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
/*
Helper method to extract from the thresholded image. (most common usage)
*/
Boxa* GetTextlines(Pixa** pixa, int** blockids) {
return GetTextlines(false, 0, pixa, blockids, nullptr);
}
/**
* Get textlines and strips of image regions as a leptonica-style Boxa, Pixa
* pair, in reading order. Enables downstream handling of non-rectangular
* regions.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each line is also returned as an
* If blockids is not nullptr, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
*/
Boxa* GetStrips(Pixa** pixa, int** blockids);
@@ -406,13 +444,25 @@ class TESS_API TessBaseAPI {
* Get the given level kind of components (block, textline, word etc.) as a
* leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each component is also returned
* If blockids is not nullptr, the block-id of each component is also returned
* as an array of one element per component. delete [] after use.
* If blockids is not nullptr, the paragraph-id of each component with its block
* is also returned as an array of one element per component. delete [] after
* use.
* If raw_image is true, then portions of the original image are extracted
* instead of the thresholded image and padded with raw_padding.
* If text_only is true, then only text components are returned.
*/
Boxa* GetComponentImages(PageIteratorLevel level,
bool text_only,
Pixa** pixa, int** blockids);
Boxa* GetComponentImages(const PageIteratorLevel level,
const bool text_only, const bool raw_image,
const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
// Helper function to get binary images with no padding (most common usage).
Boxa* GetComponentImages(const PageIteratorLevel level,
const bool text_only,
Pixa** pixa, int** blockids) {
return GetComponentImages(level, text_only, false, 0, pixa, blockids, nullptr);
}
/**
* Returns the scale factor of the thresholded image that would be returned by
@@ -422,18 +472,15 @@ class TESS_API TessBaseAPI {
*/
int GetThresholdedImageScaleFactor() const;
/**
* Dump the internal binary image to a PGM file.
* @deprecated Use GetThresholdedImage and write the image using pixWrite
* instead if possible.
*/
void DumpPGM(const char* filename);
/**
* Runs page layout analysis in the mode set by SetPageSegMode.
* May optionally be called prior to Recognize to get access to just
* the page layout results. Returns an iterator to the results.
* Returns NULL on error.
* If merge_similar_words is true, words are combined where suitable for use
* with a line recognizer. Use if you want to use AnalyseLayout to find the
* textlines, and then want to process textline fragments with an external
* line recognizer.
* Returns nullptr on error or an empty page.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
@@ -441,6 +488,7 @@ class TESS_API TessBaseAPI {
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
PageIterator* AnalyseLayout();
PageIterator* AnalyseLayout(bool merge_similar_words);
/**
* Recognize the image from SetAndThresholdImage, generating Tesseract
@@ -455,43 +503,51 @@ class TESS_API TessBaseAPI {
* Recognize() or TesseractRect(). (Recognize is called implicitly if needed.)
*/
#ifndef DISABLED_LEGACY_ENGINE
/** Variant on Recognize used for testing chopper. */
int RecognizeForChopTest(ETEXT_DESC* monitor);
#endif
/**
* Recognizes all the pages in the named file, as a multi-page tiff or
* list of filenames, or single image, and gets the appropriate kind of text
* according to parameters: tessedit_create_boxfile,
* tessedit_make_boxes_from_boxes, tessedit_write_unlv, tessedit_create_hocr.
* Calls ProcessPage on each page in the input file, which may be a
* multi-page tiff, single-page other file format, or a plain text list of
* images to read. If tessedit_page_number is non-negative, processing begins
* at that page of a multi-page tiff file, or filelist.
* The text is returned in text_out. Returns false on error.
* If non-zero timeout_millisec terminates processing after the timeout on
* a single page.
* If non-NULL and non-empty, and some page fails for some reason,
* the page is reprocessed with the retry_config config file. Useful
* for interactively debugging a bad page.
* Turns images into symbolic text.
*
* filename can point to a single image, a multi-page TIFF,
* or a plain text list of image filenames.
*
* retry_config is useful for debugging. If not nullptr, you can fall
* back to an alternate configuration if a page fails for some
* reason.
*
* timeout_millisec terminates processing if any single page
* takes too long. Set to 0 for unlimited time.
*
* renderer is responible for creating the output. For example,
* use the TessTextRenderer if you want plaintext output, or
* the TessPDFRender to produce searchable PDF.
*
* If tessedit_page_number is non-negative, will only process that
* single page. Works for multi-page tiff file, or filelist.
*
* Returns true if successful, false on error.
*/
bool ProcessPages(const char* filename,
const char* retry_config, int timeout_millisec,
STRING* text_out);
bool ProcessPages(const char* filename, const char* retry_config,
int timeout_millisec, TessResultRenderer* renderer);
// Does the real work of ProcessPages.
bool ProcessPagesInternal(const char* filename, const char* retry_config,
int timeout_millisec, TessResultRenderer* renderer);
/**
* Recognizes a single page for ProcessPages, appending the text to text_out.
* The pix is the image processed - filename and page_index are metadata
* used by side-effect processes, such as reading a box file or formatting
* as hOCR.
* If non-zero timeout_millisec terminates processing after the timeout.
* If non-NULL and non-empty, and some page fails for some reason,
* the page is reprocessed with the retry_config config file. Useful
* for interactively debugging a bad page.
* The text is returned in text_out. Returns false on error.
* Turn a single image into symbolic text.
*
* The pix is the image processed. filename and page_index are
* metadata used by side-effect processes, such as reading a box
* file or formatting as hOCR.
*
* See ProcessPages for desciptions of other parameters.
*/
bool ProcessPage(Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec,
STRING* text_out);
TessResultRenderer* renderer);
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
@@ -523,22 +579,63 @@ class TESS_API TessBaseAPI {
* Make a HTML-formatted string with hOCR markup from the internal
* data structures.
* page_number is 0-based but will appear in the output as 1-based.
* monitor can be used to
* cancel the recognition
* receive progress callbacks
* Returned string must be freed with the delete [] operator.
*/
char* GetHOCRText(ETEXT_DESC* monitor, int page_number);
/**
* Make a HTML-formatted string with hOCR markup from the internal
* data structures.
* page_number is 0-based but will appear in the output as 1-based.
* Returned string must be freed with the delete [] operator.
*/
char* GetHOCRText(int page_number);
/**
* Make a TSV-formatted string from the internal data structures.
* page_number is 0-based but will appear in the output as 1-based.
* Returned string must be freed with the delete [] operator.
*/
char* GetTSVText(int page_number);
/**
* The recognized text is returned as a char* which is coded in the same
* format as a box file used in training. Returned string must be freed with
* the delete [] operator.
* format as a box file used in training.
* Constructs coordinates in the original image - not just the rectangle.
* page_number is a 0-based page index that will appear in the box file.
* Returned string must be freed with the delete [] operator.
*/
char* GetBoxText(int page_number);
/**
* The recognized text is returned as a char* which is coded
* as UNLV format Latin-1 with specific reject and suspect codes
* and must be freed with the delete [] operator.
* as UNLV format Latin-1 with specific reject and suspect codes.
* Returned string must be freed with the delete [] operator.
*/
char* GetUNLVText();
/**
* Detect the orientation of the input image and apparent script (alphabet).
* orient_deg is the detected clockwise rotation of the input image in degrees
* (0, 90, 180, 270)
* orient_conf is the confidence (15.0 is reasonably confident)
* script_name is an ASCII string, the name of the script, e.g. "Latin"
* script_conf is confidence level in the script
* Returns true on success and writes values to each parameter as an output
*/
bool DetectOrientationScript(int* orient_deg, float* orient_conf,
const char** script_name, float* script_conf);
/**
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
* page_number is a 0-based page index that will appear in the osd file.
*/
char* GetOsdText(int page_number);
/** Returns the (average) confidence value between 0 and 100. */
int MeanTextConf();
/**
@@ -549,6 +646,7 @@ class TESS_API TessBaseAPI {
*/
int* AllWordConfidences();
#ifndef DISABLED_LEGACY_ENGINE
/**
* Applies the given word to the adaptive classifier if possible.
* The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can
@@ -560,6 +658,7 @@ class TESS_API TessBaseAPI {
* Returns false if adaption was not possible for some reason.
*/
bool AdaptToWordStr(PageSegMode mode, const char* wordstr);
#endif // ndef DISABLED_LEGACY_ENGINE
/**
* Free up recognition results and any stored image data, without actually
@@ -577,6 +676,15 @@ class TESS_API TessBaseAPI {
*/
void End();
/**
* Clear any library-level memory caches.
* There are a variety of expensive-to-load constant data structures (mostly
* language dictionaries) that are cached globally -- surviving the Init()
* and End() of individual TessBaseAPI's. This function allows the clearing
* of these caches.
**/
static void ClearPersistentCache();
/**
* Check whether a word is valid according to Tesseract's language model
* @return 0 if the word is invalid, non-zero if valid.
@@ -584,6 +692,9 @@ class TESS_API TessBaseAPI {
* in a separate API at some future time.
*/
int IsValidWord(const char *word);
// Returns true if utf8_character is defined in the UniCharset.
bool IsValidCharacter(const char *utf8_character);
bool GetTextDirection(int* out_offset, float* out_slope);
@@ -595,45 +706,34 @@ class TESS_API TessBaseAPI {
*/
void SetProbabilityInContextFunc(ProbabilityInContextFunc f);
/** Sets Wordrec::fill_lattice_ function to point to the given function. */
void SetFillLatticeFunc(FillLatticeFunc f);
/**
* Estimates the Orientation And Script of the image.
* @return true if the image was processed successfully.
*/
bool DetectOS(OSResults*);
/** This method returns the features associated with the input image. */
void GetFeaturesForBlob(TBLOB* blob, const DENORM& denorm,
INT_FEATURE_ARRAY int_features,
int* num_features, int* FeatureOutlineIndex);
/**
* Return text orientation of each block as determined by an earlier run
* of layout analysis.
*/
void GetBlockTextOrientations(int** block_orientation,
bool** vertical_writing);
#ifndef DISABLED_LEGACY_ENGINE
/** Sets Wordrec::fill_lattice_ function to point to the given function. */
void SetFillLatticeFunc(FillLatticeFunc f);
/** Find lines from the image making the BLOCK_LIST. */
BLOCK_LIST* FindLinesCreateBlockList();
/**
* This method returns the row to which a box of specified dimensions would
* belong. If no good match is found, it returns NULL.
* Delete a block list.
* This is to keep BLOCK_LIST pointer opaque
* and let go of including the other headers.
*/
static ROW* FindRowForBox(BLOCK_LIST* blocks, int left, int top,
int right, int bottom);
/**
* Method to run adaptive classifier on a blob.
* It returns at max num_max_matches results.
*/
void RunAdaptiveClassifier(TBLOB* blob, const DENORM& denorm,
int num_max_matches,
int* unichar_ids,
float* ratings,
int* num_matches_returned);
/** This method returns the string form of the specified unichar. */
const char* GetUnichar(int unichar_id);
/** Return the pointer to the i-th dawg loaded into tesseract_ object. */
const Dawg *GetDawg(int i) const;
/** Return the number of dawgs loaded into tesseract_ object. */
int NumDawgs() const;
static void DeleteBlockList(BLOCK_LIST* block_list);
/** Returns a ROW object created from the input row specification. */
static ROW *MakeTessOCRRow(float baseline, float xheight,
@@ -647,40 +747,46 @@ class TESS_API TessBaseAPI {
* for normalization. The denorm is an optional parameter in which the
* normalization-antidote is returned.
*/
static void NormalizeTBLOB(TBLOB *tblob, ROW *row,
bool numeric_mode, DENORM *denorm);
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode);
Tesseract* const tesseract() const {
return tesseract_;
}
OcrEngineMode const oem() const {
return last_oem_requested_;
}
/** This method returns the features associated with the input image. */
void GetFeaturesForBlob(TBLOB* blob, INT_FEATURE_STRUCT* int_features,
int* num_features, int* feature_outline_index);
/**
* This method returns the row to which a box of specified dimensions would
* belong. If no good match is found, it returns nullptr.
*/
static ROW* FindRowForBox(BLOCK_LIST* blocks, int left, int top,
int right, int bottom);
/**
* Method to run adaptive classifier on a blob.
* It returns at max num_max_matches results.
*/
void RunAdaptiveClassifier(TBLOB* blob,
int num_max_matches,
int* unichar_ids,
float* ratings,
int* num_matches_returned);
#endif // ndef DISABLED_LEGACY_ENGINE
/** This method returns the string form of the specified unichar. */
const char* GetUnichar(int unichar_id);
/** Return the pointer to the i-th dawg loaded into tesseract_ object. */
const Dawg *GetDawg(int i) const;
/** Return the number of dawgs loaded into tesseract_ object. */
int NumDawgs() const;
Tesseract* tesseract() const { return tesseract_; }
OcrEngineMode oem() const { return last_oem_requested_; }
void InitTruthCallback(TruthCallback *cb) { truth_cb_ = cb; }
/** Return a pointer to underlying CubeRecoContext object if present. */
CubeRecoContext *GetCubeRecoContext() const;
void set_min_orientation_margin(double margin);
/**
* Return text orientation of each block as determined by an earlier run
* of layout analysis.
*/
void GetBlockTextOrientations(int** block_orientation,
bool** vertical_writing);
/** Find lines from the image making the BLOCK_LIST. */
BLOCK_LIST* FindLinesCreateBlockList();
/**
* Delete a block list.
* This is to keep BLOCK_LIST pointer opaque
* and let go of including the other headers.
*/
static void DeleteBlockList(BLOCK_LIST* block_list);
/* @} */
protected:
@@ -689,10 +795,10 @@ class TESS_API TessBaseAPI {
TESS_LOCAL bool InternalSetImage();
/**
* Run the thresholder to make the thresholded image. If pix is not NULL,
* Run the thresholder to make the thresholded image. If pix is not nullptr,
* the source is thresholded to pix instead of the internal IMAGE.
*/
TESS_LOCAL virtual void Threshold(Pix** pix);
TESS_LOCAL virtual bool Threshold(Pix** pix);
/**
* Find lines from the image making the BLOCK_LIST.
@@ -701,7 +807,7 @@ class TESS_API TessBaseAPI {
TESS_LOCAL int FindLines();
/** Delete the pageres and block list ready for a new page. */
TESS_LOCAL void ClearResults();
void ClearResults();
/**
* Return an LTR Result Iterator -- used only for training, as we really want
@@ -718,6 +824,11 @@ class TESS_API TessBaseAPI {
*/
TESS_LOCAL int TextLength(int* blob_count);
//// paragraphs.cpp ////////////////////////////////////////////////////
TESS_LOCAL void DetectParagraphs(bool after_text_recognition);
#ifndef DISABLED_LEGACY_ENGINE
/** @defgroup ocropusAddOns ocropus add-ons */
/* @{ */
@@ -734,10 +845,9 @@ class TESS_API TessBaseAPI {
/** Recognize text doing one pass only, using settings for a given pass. */
TESS_LOCAL PAGE_RES* RecognitionPass1(BLOCK_LIST* block_list);
TESS_LOCAL PAGE_RES* RecognitionPass2(BLOCK_LIST* block_list, PAGE_RES* pass1_result);
//// paragraphs.cpp ////////////////////////////////////////////////////
TESS_LOCAL void DetectParagraphs(bool after_text_recognition);
TESS_LOCAL PAGE_RES* RecognitionPass2(BLOCK_LIST* block_list,
PAGE_RES* pass1_result);
/**
* Extract the OCR results, costs (penalty points for uncertainty),
@@ -752,15 +862,15 @@ class TESS_API TessBaseAPI {
int** y1,
PAGE_RES* page_res);
TESS_LOCAL const PAGE_RES* GetPageRes() const {
return page_res_;
};
TESS_LOCAL const PAGE_RES* GetPageRes() const { return page_res_; }
/* @} */
#endif // ndef DISABLED_LEGACY_ENGINE
protected:
Tesseract* tesseract_; ///< The underlying data object.
Tesseract* osd_tesseract_; ///< For orientation & script detection.
EquationDetect* equ_detect_; ///<The equation detector.
FileReader reader_; ///< Reads files from any filesystem.
ImageThresholder* thresholder_; ///< Image thresholding module.
GenericVector<ParagraphModel *>* paragraph_models_;
BLOCK_LIST* block_list_; ///< The page layout.
@@ -786,8 +896,31 @@ class TESS_API TessBaseAPI {
int image_height_;
/* @} */
};
private:
// A list of image filenames gets special consideration
bool ProcessPagesFileList(FILE *fp,
STRING *buf,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number);
// TIFF supports multipage so gets special consideration.
bool ProcessPagesMultipageTiff(const unsigned char *data,
size_t size,
const char* filename,
const char* retry_config,
int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number);
// There's currently no way to pass a document title from the
// Tesseract command line, and we have multiple places that choose
// to set the title to an empty string. Using a single named
// variable will hopefully reduce confusion if the situation changes
// in the future.
const char *unknown_title_ = "";
}; // class TessBaseAPI.
/** Escape a char string - remove &<>"' with HTML codes. */
STRING HOcrEscape(const char* text);
} // namespace tesseract.
#endif // TESSERACT_API_BASEAPI_H__
#endif // TESSERACT_API_BASEAPI_H_
-31
View File
@@ -1,31 +0,0 @@
/**********************************************************************
* File: basedir.h (Formerly getpath.h)
* Description: Header file for getpath.c. Provides relocatability of data.
* Author: Ray Smith
* Created: Mon Jul 09 09:13:03 BST 1990
*
* (C) Copyright 1990, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef BASEDIR_H
#define BASEDIR_H
#include "platform.h"
#include "strngs.h"
// Returns the given code_path truncated to the last slash.
// Useful for getting to the directory of argv[0], but does not search
// any paths.
TESS_API void truncate_path(const char *code_path, STRING* trunc_path);
#endif
+227 -73
View File
@@ -1,12 +1,36 @@
#ifndef TESSERACT_API_CAPI_H__
#define TESSERACT_API_CAPI_H__
///////////////////////////////////////////////////////////////////////
// File: capi.h
// Description: C-API TessBaseAPI
//
// (C) Copyright 2012, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef API_CAPI_H_
#define API_CAPI_H_
#if defined(TESSERACT_API_BASEAPI_H_) && !defined(TESS_CAPI_INCLUDE_BASEAPI)
# define TESS_CAPI_INCLUDE_BASEAPI
#endif
#ifdef TESS_CAPI_INCLUDE_BASEAPI
# include "baseapi.h"
# include "ocrclass.h"
# include "pageiterator.h"
# include "resultiterator.h"
# include "renderer.h"
#else
# include "platform.h"
# include <stdbool.h>
# include <stdio.h>
#endif
@@ -29,48 +53,67 @@ extern "C" {
#endif
#ifdef TESS_CAPI_INCLUDE_BASEAPI
typedef tesseract::TessResultRenderer TessResultRenderer;
typedef tesseract::TessTextRenderer TessTextRenderer;
typedef tesseract::TessHOcrRenderer TessHOcrRenderer;
typedef tesseract::TessPDFRenderer TessPDFRenderer;
typedef tesseract::TessUnlvRenderer TessUnlvRenderer;
typedef tesseract::TessBoxTextRenderer TessBoxTextRenderer;
typedef tesseract::TessBaseAPI TessBaseAPI;
typedef tesseract::PageIterator TessPageIterator;
typedef tesseract::ResultIterator TessResultIterator;
typedef tesseract::MutableIterator TessMutableIterator;
typedef tesseract::ChoiceIterator TessChoiceIterator;
typedef tesseract::OcrEngineMode TessOcrEngineMode;
typedef tesseract::PageSegMode TessPageSegMode;
typedef tesseract::ImageThresholder TessImageThresholder;
typedef tesseract::PageIteratorLevel TessPageIteratorLevel;
typedef tesseract::DictFunc TessDictFunc;
typedef tesseract::ProbabilityInContextFunc TessProbabilityInContextFunc;
// typedef tesseract::ParamsModelClassifyFunc TessParamsModelClassifyFunc;
typedef tesseract::FillLatticeFunc TessFillLatticeFunc;
typedef tesseract::Dawg TessDawg;
typedef tesseract::TruthCallback TessTruthCallback;
typedef tesseract::CubeRecoContext TessCubeRecoContext;
typedef tesseract::Orientation TessOrientation;
typedef tesseract::ParagraphJustification TessParagraphJustification;
typedef tesseract::WritingDirection TessWritingDirection;
typedef tesseract::TextlineOrder TessTextlineOrder;
typedef PolyBlockType TessPolyBlockType;
typedef Pix PIX;
typedef Boxa BOXA;
typedef Pixa PIXA;
#else
typedef struct TessResultRenderer TessResultRenderer;
typedef struct TessTextRenderer TessTextRenderer;
typedef struct TessHOcrRenderer TessHOcrRenderer;
typedef struct TessPDFRenderer TessPDFRenderer;
typedef struct TessUnlvRenderer TessUnlvRenderer;
typedef struct TessBoxTextRenderer TessBoxTextRenderer;
typedef struct TessBaseAPI TessBaseAPI;
typedef struct TessPageIterator TessPageIterator;
typedef struct TessResultIterator TessResultIterator;
typedef struct TessMutableIterator TessMutableIterator;
typedef enum TessOcrEngineMode { OEM_TESSERACT_ONLY, OEM_CUBE_ONLY, OEM_TESSERACT_CUBE_COMBINED, OEM_DEFAULT } TessOcrEngineMode;
typedef struct TessChoiceIterator TessChoiceIterator;
typedef enum TessOcrEngineMode { OEM_TESSERACT_ONLY, OEM_LSTM_ONLY, OEM_TESSERACT_LSTM_COMBINED, OEM_DEFAULT } TessOcrEngineMode;
typedef enum TessPageSegMode { PSM_OSD_ONLY, PSM_AUTO_OSD, PSM_AUTO_ONLY, PSM_AUTO, PSM_SINGLE_COLUMN, PSM_SINGLE_BLOCK_VERT_TEXT,
PSM_SINGLE_BLOCK, PSM_SINGLE_LINE, PSM_SINGLE_WORD, PSM_CIRCLE_WORD, PSM_SINGLE_CHAR, PSM_COUNT } TessPageSegMode;
PSM_SINGLE_BLOCK, PSM_SINGLE_LINE, PSM_SINGLE_WORD, PSM_CIRCLE_WORD, PSM_SINGLE_CHAR, PSM_SPARSE_TEXT,
PSM_SPARSE_TEXT_OSD, PSM_COUNT } TessPageSegMode;
typedef enum TessPageIteratorLevel { RIL_BLOCK, RIL_PARA, RIL_TEXTLINE, RIL_WORD, RIL_SYMBOL} TessPageIteratorLevel;
typedef enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_TABLE, PT_VERTICAL_TEXT,
PT_CAPTION_TEXT, PT_FLOWING_IMAGE, PT_HEADING_IMAGE, PT_PULLOUT_IMAGE, PT_HORZ_LINE, PT_VERT_LINE,
PT_NOISE, PT_COUNT } TessPolyBlockType;
typedef enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_EQUATION, PT_INLINE_EQUATION,
PT_TABLE, PT_VERTICAL_TEXT, PT_CAPTION_TEXT, PT_FLOWING_IMAGE, PT_HEADING_IMAGE,
PT_PULLOUT_IMAGE, PT_HORZ_LINE, PT_VERT_LINE, PT_NOISE, PT_COUNT } TessPolyBlockType;
typedef enum TessOrientation { ORIENTATION_PAGE_UP, ORIENTATION_PAGE_RIGHT, ORIENTATION_PAGE_DOWN, ORIENTATION_PAGE_LEFT } TessOrientation;
typedef enum TessParagraphJustification { JUSTIFICATION_UNKNOWN, JUSTIFICATION_LEFT, JUSTIFICATION_CENTER, JUSTIFICATION_RIGHT } TessParagraphJustification;
typedef enum TessWritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT, WRITING_DIRECTION_RIGHT_TO_LEFT, WRITING_DIRECTION_TOP_TO_BOTTOM } TessWritingDirection;
typedef enum TessTextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT, TEXTLINE_ORDER_RIGHT_TO_LEFT, TEXTLINE_ORDER_TOP_TO_BOTTOM } TessTextlineOrder;
typedef struct ETEXT_DESC ETEXT_DESC;
typedef struct Pix PIX;
typedef struct Boxa BOXA;
typedef struct Pixa PIXA;
#endif
typedef bool (*TessCancelFunc)(void* cancel_this, int words);
typedef bool (*TessProgressFunc)(ETEXT_DESC* ths, int left, int right, int top,
int bottom);
struct Pix;
struct Boxa;
struct Pixa;
/* General free functions */
TESS_API const char*
@@ -78,9 +121,27 @@ TESS_API const char*
TESS_API void TESS_CALL TessDeleteText(char* text);
TESS_API void TESS_CALL TessDeleteTextArray(char** arr);
TESS_API void TESS_CALL TessDeleteIntArray(int* arr);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list);
#endif
/* Renderer API */
TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase);
TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate(const char* outputbase);
TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate2(const char* outputbase, BOOL font_info);
TESS_API TessResultRenderer* TESS_CALL TessPDFRendererCreate(const char* outputbase, const char* datadir,
BOOL textonly);
TESS_API TessResultRenderer* TESS_CALL TessUnlvRendererCreate(const char* outputbase);
TESS_API TessResultRenderer* TESS_CALL TessBoxTextRendererCreate(const char* outputbase);
TESS_API void TESS_CALL TessDeleteResultRenderer(TessResultRenderer* renderer);
TESS_API void TESS_CALL TessResultRendererInsert(TessResultRenderer* renderer, TessResultRenderer* next);
TESS_API TessResultRenderer*
TESS_CALL TessResultRendererNext(TessResultRenderer* renderer);
TESS_API BOOL TESS_CALL TessResultRendererBeginDocument(TessResultRenderer* renderer, const char* title);
TESS_API BOOL TESS_CALL TessResultRendererAddImage(TessResultRenderer* renderer, TessBaseAPI* api);
TESS_API BOOL TESS_CALL TessResultRendererEndDocument(TessResultRenderer* renderer);
TESS_API const char* TESS_CALL TessResultRendererExtention(TessResultRenderer* renderer);
TESS_API const char* TESS_CALL TessResultRendererTitle(TessResultRenderer* renderer);
TESS_API int TESS_CALL TessResultRendererImageNum(TessResultRenderer* renderer);
/* Base API */
@@ -88,35 +149,52 @@ TESS_API TessBaseAPI*
TESS_CALL TessBaseAPICreate();
TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPISetInputName( TessBaseAPI* handle, const char* name);
TESS_API size_t TESS_CALL TessBaseAPIGetOpenCLDevice(TessBaseAPI* handle, void **device);
TESS_API void TESS_CALL TessBaseAPISetInputName(TessBaseAPI* handle, const char* name);
TESS_API const char* TESS_CALL TessBaseAPIGetInputName(TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPISetInputImage(TessBaseAPI* handle, struct Pix* pix);
TESS_API struct Pix* TESS_CALL TessBaseAPIGetInputImage(TessBaseAPI* handle);
TESS_API int TESS_CALL TessBaseAPIGetSourceYResolution(TessBaseAPI* handle);
TESS_API const char* TESS_CALL TessBaseAPIGetDatapath(TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name);
TESS_API BOOL TESS_CALL TessBaseAPISetVariable(TessBaseAPI* handle, const char* name, const char* value);
TESS_API BOOL TESS_CALL TessBaseAPISetDebugVariable(TessBaseAPI* handle, const char* name, const char* value);
TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable( const TessBaseAPI* handle, const char* name, int* value);
TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable( const TessBaseAPI* handle, const char* name, BOOL* value);
TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable(const TessBaseAPI* handle, const char* name, int* value);
TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable(const TessBaseAPI* handle, const char* name, BOOL* value);
TESS_API BOOL TESS_CALL TessBaseAPIGetDoubleVariable(const TessBaseAPI* handle, const char* name, double* value);
TESS_API const char*
TESS_CALL TessBaseAPIGetStringVariable(const TessBaseAPI* handle, const char* name);
TESS_API void TESS_CALL TessBaseAPIPrintVariables( const TessBaseAPI* handle, FILE* fp);
TESS_API void TESS_CALL TessBaseAPIPrintVariables(const TessBaseAPI* handle, FILE* fp);
TESS_API BOOL TESS_CALL TessBaseAPIPrintVariablesToFile(const TessBaseAPI* handle, const char* filename);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val);
#endif
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val);
TESS_API int TESS_CALL TessBaseAPIInit(TessBaseAPI* handle, const char* datapath, const char* language,
TessOcrEngineMode mode, char** configs, int configs_size,
const STRING* vars_vec, size_t vars_vec_size,
const STRING* vars_values, size_t vars_values_size, BOOL set_only_init_params);
#endif
#endif // def TESS_CAPI_INCLUDE_BASEAPI
TESS_API int TESS_CALL TessBaseAPIInit1(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem,
char** configs, int configs_size);
TESS_API int TESS_CALL TessBaseAPIInit2(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem);
TESS_API int TESS_CALL TessBaseAPIInit3(TessBaseAPI* handle, const char* datapath, const char* language);
TESS_API int TESS_CALL TessBaseAPIInit4(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode mode,
char** configs, int configs_size,
char** vars_vec, char** vars_values, size_t vars_vec_size,
BOOL set_only_non_debug_params);
TESS_API const char*
TESS_CALL TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI* handle);
TESS_API char**
@@ -142,7 +220,7 @@ TESS_API void TESS_CALL TessBaseAPIClearAdaptiveClassifier(TessBaseAPI* handle)
TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line);
TESS_API void TESS_CALL TessBaseAPISetImage2(TessBaseAPI* handle, const PIX* pix);
TESS_API void TESS_CALL TessBaseAPISetImage2(TessBaseAPI* handle, struct Pix* pix);
TESS_API void TESS_CALL TessBaseAPISetSourceResolution(TessBaseAPI* handle, int ppi);
@@ -152,27 +230,44 @@ TESS_API void TESS_CALL TessBaseAPISetRectangle(TessBaseAPI* handle, int left,
TESS_API void TESS_CALL TessBaseAPISetThresholder(TessBaseAPI* handle, TessImageThresholder* thresholder);
#endif
TESS_API PIX* TESS_CALL TessBaseAPIGetThresholdedImage( TessBaseAPI* handle);
TESS_API BOXA* TESS_CALL TessBaseAPIGetRegions( TessBaseAPI* handle, PIXA** pixa);
TESS_API BOXA* TESS_CALL TessBaseAPIGetTextlines( TessBaseAPI* handle, PIXA** pixa, int** blockids);
TESS_API BOXA* TESS_CALL TessBaseAPIGetStrips( TessBaseAPI* handle, PIXA** pixa, int** blockids);
TESS_API BOXA* TESS_CALL TessBaseAPIGetWords( TessBaseAPI* handle, PIXA** pixa);
TESS_API BOXA* TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, PIXA** cc);
TESS_API BOXA* TESS_CALL TessBaseAPIGetComponentImages( TessBaseAPI* handle, TessPageIteratorLevel level, BOOL text_only, PIXA** pixa, int** blockids);
TESS_API struct Pix*
TESS_CALL TessBaseAPIGetThresholdedImage(TessBaseAPI* handle);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetRegions(TessBaseAPI* handle, struct Pixa** pixa);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetTextlines(TessBaseAPI* handle, struct Pixa** pixa, int** blockids);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetTextlines1(TessBaseAPI* handle, const BOOL raw_image, const int raw_padding,
struct Pixa** pixa, int** blockids, int** paraids);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetStrips(TessBaseAPI* handle, struct Pixa** pixa, int** blockids);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetWords(TessBaseAPI* handle, struct Pixa** pixa);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, struct Pixa** cc);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetComponentImages(TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only,
struct Pixa** pixa, int** blockids);
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetComponentImages1(TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only,
const BOOL raw_image, const int raw_padding,
struct Pixa** pixa, int** blockids, int** paraids);
TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPIDumpPGM(TessBaseAPI* handle, const char* filename);
TESS_API TessPageIterator*
TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle);
TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor);
#ifndef DISABLED_LEGACY_ENGINE
TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor);
TESS_API char* TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config,
int timeout_millisec);
TESS_API char* TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, PIX* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec);
#endif
TESS_API BOOL TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config,
int timeout_millisec, TessResultRenderer* renderer);
TESS_API BOOL TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, struct Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec, TessResultRenderer* renderer);
TESS_API TessResultIterator*
TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle);
@@ -181,90 +276,98 @@ TESS_API TessMutableIterator*
TESS_API char* TESS_CALL TessBaseAPIGetUTF8Text(TessBaseAPI* handle);
TESS_API char* TESS_CALL TessBaseAPIGetHOCRText(TessBaseAPI* handle, int page_number);
TESS_API char* TESS_CALL TessBaseAPIGetBoxText(TessBaseAPI* handle, int page_number);
TESS_API char* TESS_CALL TessBaseAPIGetUNLVText(TessBaseAPI* handle);
TESS_API int TESS_CALL TessBaseAPIMeanTextConf(TessBaseAPI* handle);
TESS_API int* TESS_CALL TessBaseAPIAllWordConfidences(TessBaseAPI* handle);
#ifndef DISABLED_LEGACY_ENGINE
TESS_API BOOL TESS_CALL TessBaseAPIAdaptToWordStr(TessBaseAPI* handle, TessPageSegMode mode, const char* wordstr);
#endif // ndef DISABLED_LEGACY_ENGINE
TESS_API void TESS_CALL TessBaseAPIClear(TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPIEnd(TessBaseAPI* handle);
TESS_API int TESS_CALL TessBaseAPIIsValidWord(TessBaseAPI* handle, const char *word);
TESS_API int TESS_CALL TessBaseAPIIsValidWord(TessBaseAPI* handle, const char* word);
TESS_API BOOL TESS_CALL TessBaseAPIGetTextDirection(TessBaseAPI* handle, int* out_offset, float* out_slope);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TESS_CALL TessBaseAPISetDictFunc(TessBaseAPI* handle, TessDictFunc f);
TESS_API void TESS_CALL TessBaseAPIClearPersistentCache(TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPISetProbabilityInContextFunc(TessBaseAPI* handle, TessProbabilityInContextFunc f);
TESS_API void TESS_CALL TessBaseAPISetFillLatticeFunc(TessBaseAPI* handle, TessFillLatticeFunc f);
TESS_API BOOL TESS_CALL TessBaseAPIDetectOS(TessBaseAPI* handle, OSResults* results);
TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, const DENORM* denorm, INT_FEATURE_ARRAY int_features,
int* num_features, int* FeatureOutlineIndex);
// Call TessDeleteText(*best_script_name) to free memory allocated by this function
TESS_API BOOL TESS_CALL TessBaseAPIDetectOrientationScript(TessBaseAPI* handle,
int* orient_deg, float* orient_conf, const char **script_name, float* script_conf);
TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom);
TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, const DENORM* denorm, int num_max_matches,
int* unichar_ids, float* ratings, int* num_matches_returned);
#endif
#endif // def TESS_CAPI_INCLUDE_BASEAPI
TESS_API const char*
TESS_CALL TessBaseAPIGetUnichar(TessBaseAPI* handle, int unichar_id);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API const TessDawg*
TESS_CALL TessBaseAPIGetDawg(const TessBaseAPI* handle, int i);
TESS_API int TESS_CALL TessBaseAPINumDawgs(const TessBaseAPI* handle);
#endif
TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API ROW* TESS_CALL TessMakeTessOCRRow(float baseline, float xheight, float descender, float ascender);
TESS_API TBLOB*
TESS_CALL TessMakeTBLOB(Pix *pix);
TESS_API void TESS_CALL TessNormalizeTBLOB(TBLOB *tblob, ROW *row, BOOL numeric_mode, DENORM *denorm);
TESS_API const TessDawg*
TESS_CALL TessBaseAPIGetDawg(const TessBaseAPI* handle, int i);
TESS_API int TESS_CALL TessBaseAPINumDawgs(const TessBaseAPI* handle);
TESS_API TessOcrEngineMode
TESS_CALL TessBaseAPIOem(const TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback *cb);
TESS_API TessCubeRecoContext*
TESS_CALL TessBaseAPIGetCubeRecoContext(const TessBaseAPI* handle);
#endif
TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback* cb);
TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TESS_CALL TessBaseGetBlockTextOrientations(TessBaseAPI* handle, int** block_orientation, bool** vertical_writing);
TESS_API BLOCK_LIST*
TESS_CALL TessBaseAPIFindLinesCreateBlockList(TessBaseAPI* handle);
#endif
/* Page iterator */
TESS_API void TESS_CALL TessPageIteratorDelete(TessPageIterator* handle);
TESS_API TessPageIterator*
TESS_CALL TessPageIteratorCopy(const TessPageIterator* handle);
TESS_API void TESS_CALL TessPageIteratorBegin(TessPageIterator* handle);
TESS_API BOOL TESS_CALL TessPageIteratorNext(TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API BOOL TESS_CALL TessPageIteratorIsAtBeginningOf(const TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API BOOL TESS_CALL TessPageIteratorIsAtFinalElement(const TessPageIterator* handle, TessPageIteratorLevel level,
TessPageIteratorLevel element);
TESS_API BOOL TESS_CALL TessPageIteratorBoundingBox(const TessPageIterator* handle, TessPageIteratorLevel level,
int* left, int* top, int* right, int* bottom);
TESS_API TessPolyBlockType
TESS_CALL TessPageIteratorBlockType(const TessPageIterator* handle);
TESS_API PIX* TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API PIX* TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding,
int* left, int* top);
TESS_API struct Pix*
TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API struct Pix*
TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding,
struct Pix* original_image, int* left, int* top);
TESS_API BOOL TESS_CALL TessPageIteratorBaseline(const TessPageIterator* handle, TessPageIteratorLevel level,
int* x1, int* y1, int* x2, int* y2);
TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation *orientation,
TessWritingDirection *writing_direction, TessTextlineOrder *textline_order,
float *deskew_angle);
TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation* orientation,
TessWritingDirection* writing_direction, TessTextlineOrder* textline_order,
float* deskew_angle);
TESS_API void TESS_CALL TessPageIteratorParagraphInfo(TessPageIterator* handle, TessParagraphJustification* justification,
BOOL *is_list_item, BOOL *is_crown, int *first_line_indent);
/* Result iterator */
@@ -275,10 +378,14 @@ TESS_API TessPageIterator*
TESS_CALL TessResultIteratorGetPageIterator(TessResultIterator* handle);
TESS_API const TessPageIterator*
TESS_CALL TessResultIteratorGetPageIteratorConst(const TessResultIterator* handle);
TESS_API TessChoiceIterator*
TESS_CALL TessResultIteratorGetChoiceIterator(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorNext(TessResultIterator* handle, TessPageIteratorLevel level);
TESS_API char* TESS_CALL TessResultIteratorGetUTF8Text(const TessResultIterator* handle, TessPageIteratorLevel level);
TESS_API float TESS_CALL TessResultIteratorConfidence(const TessResultIterator* handle, TessPageIteratorLevel level);
TESS_API const char*
TESS_CALL TessResultIteratorWordRecognitionLanguage(const TessResultIterator* handle);
TESS_API const char*
TESS_CALL TessResultIteratorWordFontAttributes(const TessResultIterator* handle, BOOL* is_bold, BOOL* is_italic,
BOOL* is_underlined, BOOL* is_monospace, BOOL* is_serif,
@@ -290,8 +397,55 @@ TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSuperscript(const TessResultI
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSubscript(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsDropcap(const TessResultIterator* handle);
TESS_API void TESS_CALL TessChoiceIteratorDelete(TessChoiceIterator* handle);
TESS_API BOOL TESS_CALL TessChoiceIteratorNext(TessChoiceIterator* handle);
TESS_API const char* TESS_CALL TessChoiceIteratorGetUTF8Text(const TessChoiceIterator* handle);
TESS_API float TESS_CALL TessChoiceIteratorConfidence(const TessChoiceIterator* handle);
/* Progress monitor */
TESS_API ETEXT_DESC* TESS_CALL TessMonitorCreate();
TESS_API void TESS_CALL TessMonitorDelete(ETEXT_DESC* monitor);
TESS_API void TESS_CALL TessMonitorSetCancelFunc(ETEXT_DESC* monitor, TessCancelFunc cancelFunc);
TESS_API void TESS_CALL TessMonitorSetCancelThis(ETEXT_DESC* monitor, void* cancelThis);
TESS_API void* TESS_CALL TessMonitorGetCancelThis(ETEXT_DESC* monitor);
TESS_API void TESS_CALL TessMonitorSetProgressFunc(ETEXT_DESC* monitor, TessProgressFunc progressFunc);
TESS_API int TESS_CALL TessMonitorGetProgress(ETEXT_DESC* monitor);
TESS_API void TESS_CALL TessMonitorSetDeadlineMSecs(ETEXT_DESC* monitor, int deadline);
#ifndef DISABLED_LEGACY_ENGINE
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TESS_CALL TessBaseAPISetFillLatticeFunc(TessBaseAPI* handle, TessFillLatticeFunc f);
TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, INT_FEATURE_STRUCT* int_features,
int* num_features, int* FeatureOutlineIndex);
TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom);
TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, int num_max_matches,
int* unichar_ids, float* ratings, int* num_matches_returned);
TESS_API ROW* TESS_CALL TessMakeTessOCRRow(float baseline, float xheight, float descender, float ascender);
TESS_API TBLOB*
TESS_CALL TessMakeTBLOB(Pix* pix);
TESS_API void TESS_CALL TessNormalizeTBLOB(TBLOB* tblob, ROW* row, BOOL numeric_mode);
TESS_API BLOCK_LIST*
TESS_CALL TessBaseAPIFindLinesCreateBlockList(TessBaseAPI* handle);
TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list);
#endif // def TESS_CAPI_INCLUDE_BASEAPI
#endif // ndef DISABLED_LEGACY_ENGINE
#ifdef __cplusplus
}
#endif
#endif /* TESSERACT_API_CAPI_H__ */
#endif // API_CAPI_H_
-105
View File
@@ -1,105 +0,0 @@
/**********************************************************************
* File: errcode.h (Formerly error.h)
* Description: Header file for generic error handler class
* Author: Ray Smith
* Created: Tue May 1 16:23:36 BST 1990
*
* (C) Copyright 1990, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef ERRCODE_H
#define ERRCODE_H
#include "host.h"
/*Control parameters for error()*/
enum TessErrorLogCode {
DBG = -1, /*log without alert */
TESSLOG = 0, /*alert user */
TESSEXIT = 1, /*exit after erro */
ABORT = 2 /*abort after error */
};
/* Explicit Error Abort codes */
#define NO_ABORT_CODE 0
#define LIST_ABORT 1
#define MEMORY_ABORT 2
#define FILE_ABORT 3
/* Location of code at error codes Reserve 0..2 (status codes 0..23 for UNLV)*/
#define LOC_UNUSED0 0
#define LOC_UNUSED1 1
#define LOC_UNUSED2 2
#define LOC_INIT 3
#define LOC_EDGE_PROG 4
#define LOC_TEXT_ORD_ROWS 5
#define LOC_TEXT_ORD_WORDS 6
#define LOC_PASS1 7
#define LOC_PASS2 8
/* Reserve up to 8..13 for adding subloc 0/3 plus subsubloc 0/1/2 */
#define LOC_FUZZY_SPACE 14
/* Reserve up to 14..20 for adding subloc 0/3 plus subsubloc 0/1/2 */
#define LOC_MM_ADAPT 21
#define LOC_DOC_BLK_REJ 22
#define LOC_WRITE_RESULTS 23
#define LOC_ADAPTIVE 24
/* DONT DEFINE ANY LOCATION > 31 !!! */
/* Sub locatation determines whether pass2 was in normal mode or fix xht mode*/
#define SUBLOC_NORM 0
#define SUBLOC_FIX_XHT 3
/* Sub Sub locatation determines whether match_word_pass2 was in Tess
matcher, NN matcher or somewhere else */
#define SUBSUBLOC_OTHER 0
#define SUBSUBLOC_TESS 1
#define SUBSUBLOC_NN 2
class TESS_API ERRCODE { // error handler class
const char *message; // error message
public:
void error( // error print function
const char *caller, // function location
TessErrorLogCode action, // action to take
const char *format, ... // fprintf format
) const;
ERRCODE(const char *string) {
message = string;
} // initialize with string
};
const ERRCODE ASSERT_FAILED = "Assert failed";
#define ASSERT_HOST(x) if (!(x)) \
{ \
ASSERT_FAILED.error(#x,ABORT,"in file %s, line %d", \
__FILE__,__LINE__); \
}
void signal_exit( //
int signal_code //Signal which
);
extern "C"
{
void err_exit();
//The real signal
void signal_termination_handler(int sig);
};
void set_global_loc_code(int loc_code);
void set_global_subloc_code(int loc_code);
void set_global_subsubloc_code(int loc_code);
#endif
-34
View File
@@ -1,34 +0,0 @@
/**********************************************************************
* File: fileerr.h (Formerly filerr.h)
* Description: Errors for file utilities.
* Author: Ray Smith
* Created: Tue Aug 14 15:45:16 BST 1990
*
* (C) Copyright 1990, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef FILEERR_H
#define FILEERR_H
#include "errcode.h"
const ERRCODE CANTOPENFILE = "Can't open file";
const ERRCODE CANTCREATEFILE = "Can't create file";
const ERRCODE CANTMAKEPIPE = "Can't create pipe";
const ERRCODE CANTCONNECTPIPE = "Can't reconnect pipes to stdin/stdout";
const ERRCODE READFAILED = "Read of file failed";
const ERRCODE WRITEFAILED = "Write of file failed";
const ERRCODE SELECTFAILED = "Select failed";
const ERRCODE EXECFAILED = "Could not exec new process";
#endif
+449 -126
View File
@@ -20,13 +20,15 @@
#ifndef TESSERACT_CCUTIL_GENERICVECTOR_H_
#define TESSERACT_CCUTIL_GENERICVECTOR_H_
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "tesscallback.h"
#include "errcode.h"
#include "helpers.h"
#include "ndminx.h"
#include "serialis.h"
#include "strngs.h"
// Use PointerVector<T> below in preference to GenericVector<T*>, as that
// provides automatic deletion of pointers, [De]Serialize that works, and
@@ -34,8 +36,13 @@
template <typename T>
class GenericVector {
public:
GenericVector() { this->init(kDefaultVectorSize); }
explicit GenericVector(int size) { this->init(size); }
GenericVector() {
init(kDefaultVectorSize);
}
GenericVector(int size, const T& init_val) {
init(size);
init_to_size(size, init_val);
}
// Copy
GenericVector(const GenericVector& other) {
@@ -45,7 +52,7 @@ class GenericVector {
GenericVector<T> &operator+=(const GenericVector& other);
GenericVector<T> &operator=(const GenericVector& other);
virtual ~GenericVector();
~GenericVector();
// Reserve some memory.
void reserve(int size);
@@ -53,12 +60,27 @@ class GenericVector {
void double_the_size();
// Resizes to size and sets all values to t.
void init_to_size(int size, T t);
void init_to_size(int size, const T& t);
// Resizes to size without any initialization.
void resize_no_init(int size) {
reserve(size);
size_used_ = size;
}
// Return the size used.
int size() const {
return size_used_;
}
// Workaround to avoid g++ -Wsign-compare warnings.
size_t unsigned_size() const {
static_assert(sizeof(size_used_) <= sizeof(size_t),
"Wow! sizeof(size_t) < sizeof(int32_t)!!");
assert(0 <= size_used_);
return static_cast<size_t>(size_used_);
}
int size_reserved() const {
return size_reserved_;
}
int length() const {
return size_used_;
@@ -73,43 +95,45 @@ class GenericVector {
T &get(int index) const;
T &back() const;
T &operator[](int index) const;
// Returns the last object and removes it.
T pop_back();
// Return the index of the T object.
// This method NEEDS a compare_callback to be passed to
// set_compare_callback.
int get_index(T object) const;
int get_index(const T& object) const;
// Return true if T is in the array
bool contains(T object) const;
bool contains(const T& object) const;
// Return true if the index is valid
T contains_index(int index) const;
// Push an element in the end of the array
int push_back(T object);
void operator+=(T t);
void operator+=(const T& t);
// Push an element in the end of the array if the same
// element is not already contained in the array.
int push_back_new(T object);
int push_back_new(const T& object);
// Push an element in the front of the array
// Note: This function is O(n)
int push_front(T object);
int push_front(const T& object);
// Set the value at the given index
void set(T t, int index);
void set(const T& t, int index);
// Insert t at the given index, push other elements to the right.
void insert(T t, int index);
void insert(const T& t, int index);
// Removes an element at the given index and
// shifts the remaining elements to the left.
virtual void remove(int index);
void remove(int index);
// Truncates the array to the given size by removing the end.
// If the current size is less, the array is not expanded.
virtual void truncate(int size) {
void truncate(int size) {
if (size < size_used_)
size_used_ = size;
}
@@ -125,8 +149,8 @@ class GenericVector {
// Clear the array, calling the clear callback function if any.
// All the owned callbacks are also deleted.
// If you don't want the callbacks to be deleted, before calling clear, set
// the callback to NULL.
virtual void clear();
// the callback to nullptr.
void clear();
// Delete objects pointed to by data_[i]
void delete_data_pointers();
@@ -139,30 +163,41 @@ class GenericVector {
// Read/Write the array to a file. This does _NOT_ read/write the callbacks.
// The callback given must be permanent since they will be called more than
// once. The given callback will be deleted at the end.
// If the callbacks are NULL, then the data is simply read/written using
// If the callbacks are nullptr, then the data is simply read/written using
// fread (and swapping)/fwrite.
// Returns false on error or if the callback returns false.
// DEPRECATED. Use [De]Serialize[Classes] instead.
bool write(FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const;
bool read(FILE* f, TessResultCallback3<bool, FILE*, T*, bool>* cb, bool swap);
bool read(tesseract::TFile* f,
TessResultCallback2<bool, tesseract::TFile*, T*>* cb);
// Writes a vector of simple types to the given file. Assumes that bitwise
// read/write of T will work. Returns false in case of error.
virtual bool Serialize(FILE* fp) const;
// TODO(rays) Change all callers to use TFile and remove deprecated methods.
bool Serialize(FILE* fp) const;
bool Serialize(tesseract::TFile* fp) const;
// Reads a vector of simple types from the given file. Assumes that bitwise
// read/write will work with ReverseN according to sizeof(T).
// Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
virtual bool DeSerialize(bool swap, FILE* fp);
// TFile is assumed to know about swapping.
bool DeSerialize(bool swap, FILE* fp);
bool DeSerialize(tesseract::TFile* fp);
// Skips the deserialization of the vector.
static bool SkipDeSerialize(tesseract::TFile* fp);
// Writes a vector of classes to the given file. Assumes the existence of
// bool T::Serialize(FILE* fp) const that returns false in case of error.
// Returns false in case of error.
bool SerializeClasses(FILE* fp) const;
bool SerializeClasses(tesseract::TFile* fp) const;
// Reads a vector of classes from the given file. Assumes the existence of
// bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
// error. Also needs T::T() and T::T(constT&), as init_to_size is used in
// this function. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerializeClasses(bool swap, FILE* fp);
bool DeSerializeClasses(tesseract::TFile* fp);
// Calls SkipDeSerialize on the elements of the vector.
static bool SkipDeSerializeClasses(tesseract::TFile* fp);
// Allocates a new array of double the current_size, copies over the
// information from data to the new location, deletes data and returns
@@ -176,6 +211,12 @@ class GenericVector {
return data_new;
}
// Reverses the elements of the vector.
void reverse() {
for (int i = 0; i < size_used_ / 2; ++i)
Swap(&data_[i], &data_[size_used_ - 1 - i]);
}
// Sorts the members of this vector using the less than comparator (cmp_lt),
// which compares the values. Useful for GenericVectors to primitive types.
// Will not work so great for pointers (unless you just want to sort some
@@ -209,14 +250,13 @@ class GenericVector {
int binary_search(const T& target) const {
int bottom = 0;
int top = size_used_;
do {
while (top - bottom > 1) {
int middle = (bottom + top) / 2;
if (data_[middle] > target)
top = middle;
else
bottom = middle;
}
while (top - bottom > 1);
return bottom;
}
@@ -257,22 +297,56 @@ class GenericVector {
T dot_product(const GenericVector<T>& other) const {
T result = static_cast<T>(0);
for (int i = MIN(size_used_, other.size_used_) - 1; i >= 0; --i)
for (int i = std::min(size_used_, other.size_used_) - 1; i >= 0; --i)
result += data_[i] * other.data_[i];
return result;
}
// Returns the index of what would be the target_index_th item in the array
// if the members were sorted, without actually sorting. Members are
// shuffled around, but it takes O(n) time.
// NOTE: uses operator< and operator== on the members.
int choose_nth_item(int target_index) {
// Make sure target_index is legal.
if (target_index < 0)
target_index = 0; // ensure legal
else if (target_index >= size_used_)
target_index = size_used_ - 1;
unsigned int seed = 1;
return choose_nth_item(target_index, 0, size_used_, &seed);
}
// Swaps the elements with the given indices.
void swap(int index1, int index2) {
if (index1 != index2) {
T tmp = data_[index1];
data_[index1] = data_[index2];
data_[index2] = tmp;
}
}
// Returns true if all elements of *this are within the given range.
// Only uses operator<
bool WithinBounds(const T& rangemin, const T& rangemax) const {
for (int i = 0; i < size_used_; ++i) {
if (data_[i] < rangemin || rangemax < data_[i])
return false;
}
return true;
}
protected:
// Internal recursive version of choose_nth_item.
int choose_nth_item(int target_index, int start, int end, unsigned int* seed);
// Init the object, allocating size memory.
void init(int size);
// We are assuming that the object generally placed in thie
// vector are small enough that for efficiency it makes sence
// We are assuming that the object generally placed in the
// vector are small enough that for efficiency it makes sense
// to start with a larger initial size.
static const int kDefaultVectorSize = 4;
inT32 size_used_;
inT32 size_reserved_;
int32_t size_used_;
int32_t size_reserved_;
T* data_;
TessCallback1<T>* clear_cb_;
// Mutable because Run method is not const
@@ -281,6 +355,62 @@ class GenericVector {
namespace tesseract {
// Function to read a GenericVector<char> from a whole file.
// Returns false on failure.
typedef bool (*FileReader)(const STRING& filename, GenericVector<char>* data);
// Function to write a GenericVector<char> to a whole file.
// Returns false on failure.
typedef bool (*FileWriter)(const GenericVector<char>& data,
const STRING& filename);
// The default FileReader loads the whole file into the vector of char,
// returning false on error.
inline bool LoadDataFromFile(const char* filename, GenericVector<char>* data) {
bool result = false;
FILE* fp = fopen(filename, "rb");
if (fp != nullptr) {
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
// Trying to open a directory on Linux sets size to LONG_MAX. Catch it here.
if (size > 0 && size < LONG_MAX) {
// reserve an extra byte in case caller wants to append a '\0' character
data->reserve(size + 1);
data->resize_no_init(size);
result = static_cast<long>(fread(&(*data)[0], 1, size, fp)) == size;
}
fclose(fp);
}
return result;
}
inline bool LoadDataFromFile(const STRING& filename,
GenericVector<char>* data) {
return LoadDataFromFile(filename.string(), data);
}
// The default FileWriter writes the vector of char to the filename file,
// returning false on error.
inline bool SaveDataToFile(const GenericVector<char>& data,
const STRING& filename) {
FILE* fp = fopen(filename.string(), "wb");
if (fp == nullptr) return false;
bool result =
static_cast<int>(fwrite(&data[0], 1, data.size(), fp)) == data.size();
fclose(fp);
return result;
}
// Reads a file as a vector of STRING.
inline bool LoadFileLinesToStrings(const STRING& filename,
GenericVector<STRING>* lines) {
GenericVector<char> data;
if (!LoadDataFromFile(filename.string(), &data)) {
return false;
}
STRING lines_str(&data[0], data.size());
lines_str.split('\n', lines);
return true;
}
template <typename T>
bool cmp_eq(T const & t1, T const & t2) {
return t1 == t2;
@@ -309,8 +439,8 @@ int sort_cmp(const void* t1, const void* t2) {
// return > 0 if t1 > t2
template <typename T>
int sort_ptr_cmp(const void* t1, const void* t2) {
const T* a = *reinterpret_cast<T * const *>(t1);
const T* b = *reinterpret_cast<T * const *>(t2);
const T* a = *static_cast<T* const*>(t1);
const T* b = *static_cast<T* const*>(t2);
if (*a < *b) {
return -1;
} else if (*b < *a) {
@@ -328,14 +458,14 @@ class PointerVector : public GenericVector<T*> {
public:
PointerVector() : GenericVector<T*>() { }
explicit PointerVector(int size) : GenericVector<T*>(size) { }
virtual ~PointerVector() {
~PointerVector() {
// Clear must be called here, even though it is called again by the base,
// as the base will call the wrong clear.
clear();
}
// Copy must be deep, as the pointers will be automatically deleted on
// destruction.
PointerVector(const PointerVector& other) {
PointerVector(const PointerVector& other) : GenericVector<T*>(other) {
this->init(other.size());
this->operator+=(other);
}
@@ -348,21 +478,23 @@ class PointerVector : public GenericVector<T*> {
}
PointerVector<T>& operator=(const PointerVector& other) {
this->truncate(0);
this->operator+=(other);
if (&other != this) {
this->truncate(0);
this->operator+=(other);
}
return *this;
}
// Removes an element at the given index and
// shifts the remaining elements to the left.
virtual void remove(int index) {
void remove(int index) {
delete GenericVector<T*>::data_[index];
GenericVector<T*>::remove(index);
}
// Truncates the array to the given size by removing the end.
// If the current size is less, the array is not expanded.
virtual void truncate(int size) {
void truncate(int size) {
for (int i = size; i < GenericVector<T*>::size_used_; ++i)
delete GenericVector<T*>::data_[i];
GenericVector<T*>::truncate(size);
@@ -393,52 +525,121 @@ class PointerVector : public GenericVector<T*> {
// Clear the array, calling the clear callback function if any.
// All the owned callbacks are also deleted.
// If you don't want the callbacks to be deleted, before calling clear, set
// the callback to NULL.
virtual void clear() {
// the callback to nullptr.
void clear() {
GenericVector<T*>::delete_data_pointers();
GenericVector<T*>::clear();
}
// Writes a vector of simple types to the given file. Assumes that bitwise
// read/write of T will work. Returns false in case of error.
virtual bool Serialize(FILE* fp) const {
inT32 used = GenericVector<T*>::size_used_;
// Writes a vector of (pointers to) classes to the given file. Assumes the
// existence of bool T::Serialize(FILE*) const that returns false in case of
// error. There is no Serialize for simple types, as you would have a
// normal GenericVector of those.
// Returns false in case of error.
bool Serialize(FILE* fp) const {
int32_t used = GenericVector<T*>::size_used_;
if (fwrite(&used, sizeof(used), 1, fp) != 1) return false;
for (int i = 0; i < used; ++i) {
inT8 non_null = GenericVector<T*>::data_[i] != NULL;
int8_t non_null = GenericVector<T*>::data_[i] != nullptr;
if (fwrite(&non_null, sizeof(non_null), 1, fp) != 1) return false;
if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
}
return true;
}
// Reads a vector of simple types from the given file. Assumes that bitwise
// read/write will work with ReverseN according to sizeof(T).
bool Serialize(TFile* fp) const {
int32_t used = GenericVector<T*>::size_used_;
if (fp->FWrite(&used, sizeof(used), 1) != 1) return false;
for (int i = 0; i < used; ++i) {
int8_t non_null = GenericVector<T*>::data_[i] != nullptr;
if (fp->FWrite(&non_null, sizeof(non_null), 1) != 1) return false;
if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
}
return true;
}
// Reads a vector of (pointers to) classes to the given file. Assumes the
// existence of bool T::DeSerialize(bool, Tfile*) const that returns false in
// case of error. There is no Serialize for simple types, as you would have a
// normal GenericVector of those.
// If swap is true, assumes a big/little-endian swap is needed.
// Also needs T::T(), as new T is used in this function.
// Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
virtual bool DeSerialize(bool swap, FILE* fp) {
inT32 reserved;
bool DeSerialize(bool swap, FILE* fp) {
uint32_t reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
// Arbitrarily limit the number of elements to protect against bad data.
assert(reserved <= UINT16_MAX);
if (reserved > UINT16_MAX) {
return false;
}
GenericVector<T*>::reserve(reserved);
for (int i = 0; i < reserved; ++i) {
inT8 non_null;
truncate(0);
for (uint32_t i = 0; i < reserved; ++i) {
int8_t non_null;
if (fread(&non_null, sizeof(non_null), 1, fp) != 1) return false;
T* item = NULL;
T* item = nullptr;
if (non_null) {
item = new T;
if (!item->DeSerialize(swap, fp)) return false;
if (!item->DeSerialize(swap, fp)) {
delete item;
return false;
}
this->push_back(item);
} else {
// Null elements should keep their place in the vector.
this->push_back(nullptr);
}
}
return true;
}
bool DeSerialize(TFile* fp) {
int32_t reserved;
if (!DeSerializeSize(fp, &reserved)) return false;
GenericVector<T*>::reserve(reserved);
truncate(0);
for (int i = 0; i < reserved; ++i) {
if (!DeSerializeElement(fp)) return false;
}
return true;
}
// Enables deserialization of a selection of elements. Note that in order to
// retain the integrity of the stream, the caller must call some combination
// of DeSerializeElement and DeSerializeSkip of the exact number returned in
// *size, assuming a true return.
static bool DeSerializeSize(TFile* fp, int32_t* size) {
return fp->FReadEndian(size, sizeof(*size), 1) == 1;
}
// Reads and appends to the vector the next element of the serialization.
bool DeSerializeElement(TFile* fp) {
int8_t non_null;
if (fp->FRead(&non_null, sizeof(non_null), 1) != 1) return false;
T* item = nullptr;
if (non_null) {
item = new T;
if (!item->DeSerialize(fp)) {
delete item;
return false;
}
this->push_back(item);
} else {
// Null elements should keep their place in the vector.
this->push_back(nullptr);
}
return true;
}
// Skips the next element of the serialization.
static bool DeSerializeSkip(TFile* fp) {
int8_t non_null;
if (fp->FRead(&non_null, sizeof(non_null), 1) != 1) return false;
if (non_null) {
if (!T::SkipDeSerialize(fp)) return false;
}
return true;
}
// Sorts the items pointed to by the members of this vector using
// t::operator<().
void sort() {
sort(&sort_ptr_cmp<T>);
}
void sort() { this->GenericVector<T*>::sort(&sort_ptr_cmp<T>); }
};
} // namespace tesseract
@@ -460,11 +661,16 @@ class GenericVectorEqEq : public GenericVector<T> {
template <typename T>
void GenericVector<T>::init(int size) {
size_used_ = 0;
size_reserved_ = 0;
data_ = 0;
clear_cb_ = 0;
compare_cb_ = 0;
reserve(size);
if (size <= 0) {
data_ = nullptr;
size_reserved_ = 0;
} else {
if (size < kDefaultVectorSize) size = kDefaultVectorSize;
data_ = new T[size];
size_reserved_ = size;
}
clear_cb_ = nullptr;
compare_cb_ = nullptr;
}
template <typename T>
@@ -478,10 +684,11 @@ template <typename T>
void GenericVector<T>::reserve(int size) {
if (size_reserved_ >= size || size <= 0)
return;
if (size < kDefaultVectorSize) size = kDefaultVectorSize;
T* new_array = new T[size];
for (int i = 0; i < size_used_; ++i)
new_array[i] = data_[i];
if (data_ != NULL) delete[] data_;
delete[] data_;
data_ = new_array;
size_reserved_ = size;
}
@@ -498,7 +705,7 @@ void GenericVector<T>::double_the_size() {
// Resizes to size and sets all values to t.
template <typename T>
void GenericVector<T>::init_to_size(int size, T t) {
void GenericVector<T>::init_to_size(int size, const T& t) {
reserve(size);
size_used_ = size;
for (int i = 0; i < size; ++i)
@@ -509,25 +716,32 @@ void GenericVector<T>::init_to_size(int size, T t) {
// Return the object from an index.
template <typename T>
T &GenericVector<T>::get(int index) const {
ASSERT_HOST(index >= 0 && index < size_used_);
assert(index >= 0 && index < size_used_);
return data_[index];
}
template <typename T>
T &GenericVector<T>::operator[](int index) const {
return data_[index];
assert(index >= 0 && index < size_used_);
return data_[index];
}
template <typename T>
T &GenericVector<T>::back() const {
ASSERT_HOST(size_used_ > 0);
assert(size_used_ > 0);
return data_[size_used_ - 1];
}
// Returns the last object and removes it.
template <typename T>
T GenericVector<T>::pop_back() {
assert(size_used_ > 0);
return data_[--size_used_];
}
// Return the object from an index.
template <typename T>
void GenericVector<T>::set(T t, int index) {
ASSERT_HOST(index >= 0 && index < size_used_);
void GenericVector<T>::set(const T& t, int index) {
assert(index >= 0 && index < size_used_);
data_[index] = t;
}
@@ -535,8 +749,8 @@ void GenericVector<T>::set(T t, int index) {
// space for the new elements and inserts the given element
// at the specified index.
template <typename T>
void GenericVector<T>::insert(T t, int index) {
ASSERT_HOST(index >= 0 && index < size_used_);
void GenericVector<T>::insert(const T& t, int index) {
assert(index >= 0 && index <= size_used_);
if (size_reserved_ == size_used_)
double_the_size();
for (int i = size_used_; i > index; --i) {
@@ -550,7 +764,7 @@ void GenericVector<T>::insert(T t, int index) {
// shifts the remaining elements to the left.
template <typename T>
void GenericVector<T>::remove(int index) {
ASSERT_HOST(index >= 0 && index < size_used_);
assert(index >= 0 && index < size_used_);
for (int i = index; i < size_used_ - 1; ++i) {
data_[i] = data_[i+1];
}
@@ -565,9 +779,9 @@ T GenericVector<T>::contains_index(int index) const {
// Return the index of the T object.
template <typename T>
int GenericVector<T>::get_index(T object) const {
int GenericVector<T>::get_index(const T& object) const {
for (int i = 0; i < size_used_; ++i) {
ASSERT_HOST(compare_cb_ != NULL);
assert(compare_cb_ != nullptr);
if (compare_cb_->Run(object, data_[i]))
return i;
}
@@ -576,7 +790,7 @@ int GenericVector<T>::get_index(T object) const {
// Return true if T is in the array
template <typename T>
bool GenericVector<T>::contains(T object) const {
bool GenericVector<T>::contains(const T& object) const {
return get_index(object) != -1;
}
@@ -592,7 +806,7 @@ int GenericVector<T>::push_back(T object) {
}
template <typename T>
int GenericVector<T>::push_back_new(T object) {
int GenericVector<T>::push_back_new(const T& object) {
int index = get_index(object);
if (index >= 0)
return index;
@@ -601,7 +815,7 @@ int GenericVector<T>::push_back_new(T object) {
// Add an element in the array (front)
template <typename T>
int GenericVector<T>::push_front(T object) {
int GenericVector<T>::push_front(const T& object) {
if (size_used_ == size_reserved_)
double_the_size();
for (int i = size_used_; i > 0; --i)
@@ -612,7 +826,7 @@ int GenericVector<T>::push_front(T object) {
}
template <typename T>
void GenericVector<T>::operator+=(T t) {
void GenericVector<T>::operator+=(const T& t) {
push_back(t);
}
@@ -627,8 +841,10 @@ GenericVector<T> &GenericVector<T>::operator+=(const GenericVector& other) {
template <typename T>
GenericVector<T> &GenericVector<T>::operator=(const GenericVector& other) {
this->truncate(0);
this->operator+=(other);
if (&other != this) {
this->truncate(0);
this->operator+=(other);
}
return *this;
}
@@ -642,38 +858,33 @@ void GenericVector<T>::set_clear_callback(TessCallback1<T>* cb) {
// Add a callback to be called to delete the elements when the array took
// their ownership.
template <typename T>
void GenericVector<T>::set_compare_callback(TessResultCallback2<bool, T const &, T const &>* cb) {
void GenericVector<T>::set_compare_callback(
TessResultCallback2<bool, T const &, T const &>* cb) {
compare_cb_ = cb;
}
// Clear the array, calling the callback function if any.
template <typename T>
void GenericVector<T>::clear() {
if (size_reserved_ > 0) {
if (clear_cb_ != NULL)
for (int i = 0; i < size_used_; ++i)
clear_cb_->Run(data_[i]);
delete[] data_;
data_ = NULL;
size_used_ = 0;
size_reserved_ = 0;
}
if (clear_cb_ != NULL) {
delete clear_cb_;
clear_cb_ = NULL;
}
if (compare_cb_ != NULL) {
delete compare_cb_;
compare_cb_ = NULL;
if (size_reserved_ > 0 && clear_cb_ != nullptr) {
for (int i = 0; i < size_used_; ++i)
clear_cb_->Run(data_[i]);
}
delete[] data_;
data_ = nullptr;
size_used_ = 0;
size_reserved_ = 0;
delete clear_cb_;
clear_cb_ = nullptr;
delete compare_cb_;
compare_cb_ = nullptr;
}
template <typename T>
void GenericVector<T>::delete_data_pointers() {
for (int i = 0; i < size_used_; ++i)
if (data_[i]) {
delete data_[i];
}
for (int i = 0; i < size_used_; ++i) {
delete data_[i];
}
}
@@ -682,7 +893,7 @@ bool GenericVector<T>::write(
FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const {
if (fwrite(&size_reserved_, sizeof(size_reserved_), 1, f) != 1) return false;
if (fwrite(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
if (cb != NULL) {
if (cb != nullptr) {
for (int i = 0; i < size_used_; ++i) {
if (!cb->Run(f, data_[i])) {
delete cb;
@@ -691,35 +902,30 @@ bool GenericVector<T>::write(
}
delete cb;
} else {
if (fwrite(data_, sizeof(T), size_used_, f) != size_used_) return false;
if (fwrite(data_, sizeof(T), size_used_, f) != unsigned_size())
return false;
}
return true;
}
template <typename T>
bool GenericVector<T>::read(FILE* f,
TessResultCallback3<bool, FILE*, T*, bool>* cb,
bool swap) {
inT32 reserved;
if (fread(&reserved, sizeof(reserved), 1, f) != 1) return false;
if (swap) Reverse32(&reserved);
bool GenericVector<T>::read(
tesseract::TFile* f, TessResultCallback2<bool, tesseract::TFile*, T*>* cb) {
int32_t reserved;
if (f->FReadEndian(&reserved, sizeof(reserved), 1) != 1) return false;
reserve(reserved);
if (fread(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
if (swap) Reverse32(&size_used_);
if (cb != NULL) {
if (f->FReadEndian(&size_used_, sizeof(size_used_), 1) != 1) return false;
if (cb != nullptr) {
for (int i = 0; i < size_used_; ++i) {
if (!cb->Run(f, data_ + i, swap)) {
if (!cb->Run(f, data_ + i)) {
delete cb;
return false;
}
}
delete cb;
} else {
if (fread(data_, sizeof(T), size_used_, f) != size_used_) return false;
if (swap) {
for (int i = 0; i < size_used_; ++i)
ReverseN(&data_[i], sizeof(T));
}
if (f->FReadEndian(data_, sizeof(T), size_used_) != size_used_)
return false;
}
return true;
}
@@ -729,7 +935,14 @@ bool GenericVector<T>::read(FILE* f,
template <typename T>
bool GenericVector<T>::Serialize(FILE* fp) const {
if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false;
if (fwrite(data_, sizeof(*data_), size_used_, fp) != size_used_) return false;
if (fwrite(data_, sizeof(*data_), size_used_, fp) != unsigned_size())
return false;
return true;
}
template <typename T>
bool GenericVector<T>::Serialize(tesseract::TFile* fp) const {
if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
if (fp->FWrite(data_, sizeof(*data_), size_used_) != size_used_) return false;
return true;
}
@@ -739,18 +952,39 @@ bool GenericVector<T>::Serialize(FILE* fp) const {
// If swap is true, assumes a big/little-endian swap is needed.
template <typename T>
bool GenericVector<T>::DeSerialize(bool swap, FILE* fp) {
inT32 reserved;
uint32_t reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
// Arbitrarily limit the number of elements to protect against bad data.
assert(reserved <= UINT16_MAX);
if (reserved > UINT16_MAX) return false;
reserve(reserved);
size_used_ = reserved;
if (fread(data_, sizeof(T), size_used_, fp) != size_used_) return false;
if (fread(data_, sizeof(T), size_used_, fp) != unsigned_size()) return false;
if (swap) {
for (int i = 0; i < size_used_; ++i)
ReverseN(&data_[i], sizeof(data_[i]));
}
return true;
}
template <typename T>
bool GenericVector<T>::DeSerialize(tesseract::TFile* fp) {
uint32_t reserved;
if (fp->FReadEndian(&reserved, sizeof(reserved), 1) != 1) return false;
// Arbitrarily limit the number of elements to protect against bad data.
const uint32_t limit = 50000000;
assert(reserved <= limit);
if (reserved > limit) return false;
reserve(reserved);
size_used_ = reserved;
return fp->FReadEndian(data_, sizeof(T), size_used_) == size_used_;
}
template <typename T>
bool GenericVector<T>::SkipDeSerialize(tesseract::TFile* fp) {
uint32_t reserved;
if (fp->FReadEndian(&reserved, sizeof(reserved), 1) != 1) return false;
return fp->FRead(nullptr, sizeof(T), reserved) == reserved;
}
// Writes a vector of classes to the given file. Assumes the existence of
// bool T::Serialize(FILE* fp) const that returns false in case of error.
@@ -763,15 +997,23 @@ bool GenericVector<T>::SerializeClasses(FILE* fp) const {
}
return true;
}
template <typename T>
bool GenericVector<T>::SerializeClasses(tesseract::TFile* fp) const {
if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
for (int i = 0; i < size_used_; ++i) {
if (!data_[i].Serialize(fp)) return false;
}
return true;
}
// Reads a vector of classes from the given file. Assumes the existence of
// bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
// error. Alse needs T::T() and T::T(constT&), as init_to_size is used in
// error. Also needs T::T() and T::T(constT&), as init_to_size is used in
// this function. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
template <typename T>
bool GenericVector<T>::DeSerializeClasses(bool swap, FILE* fp) {
uinT32 reserved;
int32_t reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
T empty;
@@ -781,6 +1023,26 @@ bool GenericVector<T>::DeSerializeClasses(bool swap, FILE* fp) {
}
return true;
}
template <typename T>
bool GenericVector<T>::DeSerializeClasses(tesseract::TFile* fp) {
int32_t reserved;
if (fp->FReadEndian(&reserved, sizeof(reserved), 1) != 1) return false;
T empty;
init_to_size(reserved, empty);
for (int i = 0; i < reserved; ++i) {
if (!data_[i].DeSerialize(fp)) return false;
}
return true;
}
template <typename T>
bool GenericVector<T>::SkipDeSerializeClasses(tesseract::TFile* fp) {
int32_t reserved;
if (fp->FReadEndian(&reserved, sizeof(reserved), 1) != 1) return false;
for (int i = 0; i < reserved; ++i) {
if (!T::SkipDeSerialize(fp)) return false;
}
return true;
}
// This method clear the current object, then, does a shallow copy of
// its argument, and finally invalidates its argument.
@@ -792,9 +1054,9 @@ void GenericVector<T>::move(GenericVector<T>* from) {
this->size_used_ = from->size_used_;
this->compare_cb_ = from->compare_cb_;
this->clear_cb_ = from->clear_cb_;
from->data_ = NULL;
from->clear_cb_ = NULL;
from->compare_cb_ = NULL;
from->data_ = nullptr;
from->clear_cb_ = nullptr;
from->compare_cb_ = nullptr;
from->size_used_ = 0;
from->size_reserved_ = 0;
}
@@ -804,4 +1066,65 @@ void GenericVector<T>::sort() {
sort(&tesseract::sort_cmp<T>);
}
// Internal recursive version of choose_nth_item.
// The algorithm used comes from "Algorithms" by Sedgewick:
// http://books.google.com/books/about/Algorithms.html?id=idUdqdDXqnAC
// The principle is to choose a random pivot, and move everything less than
// the pivot to its left, and everything greater than the pivot to the end
// of the array, then recurse on the part that contains the desired index, or
// just return the answer if it is in the equal section in the middle.
// The random pivot guarantees average linear time for the same reason that
// n times vector::push_back takes linear time on average.
// target_index, start and and end are all indices into the full array.
// Seed is a seed for rand_r for thread safety purposes. Its value is
// unimportant as the random numbers do not affect the result except
// between equal answers.
template <typename T>
int GenericVector<T>::choose_nth_item(int target_index, int start, int end,
unsigned int* seed) {
// Number of elements to process.
int num_elements = end - start;
// Trivial cases.
if (num_elements <= 1)
return start;
if (num_elements == 2) {
if (data_[start] < data_[start + 1]) {
return target_index > start ? start + 1 : start;
} else {
return target_index > start ? start : start + 1;
}
}
// Place the pivot at start.
#ifndef rand_r // _MSC_VER, ANDROID
srand(*seed);
#define rand_r(seed) rand()
#endif // _MSC_VER
int pivot = rand_r(seed) % num_elements + start;
swap(pivot, start);
// The invariant condition here is that items [start, next_lesser) are less
// than the pivot (which is at index next_lesser) and items
// [prev_greater, end) are greater than the pivot, with items
// [next_lesser, prev_greater) being equal to the pivot.
int next_lesser = start;
int prev_greater = end;
for (int next_sample = start + 1; next_sample < prev_greater;) {
if (data_[next_sample] < data_[next_lesser]) {
swap(next_lesser++, next_sample++);
} else if (data_[next_sample] == data_[next_lesser]) {
++next_sample;
} else {
swap(--prev_greater, next_sample);
}
}
// Now the invariant is set up, we recurse on just the section that contains
// the desired index.
if (target_index < next_lesser)
return choose_nth_item(target_index, start, next_lesser, seed);
else if (target_index < prev_greater)
return next_lesser; // In equal bracket.
else
return choose_nth_item(target_index, prev_greater, end, seed);
}
#endif // TESSERACT_CCUTIL_GENERICVECTOR_H_
+67 -14
View File
@@ -25,12 +25,63 @@
#ifndef TESSERACT_CCUTIL_HELPERS_H_
#define TESSERACT_CCUTIL_HELPERS_H_
#include <stdio.h>
#include <string.h>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <functional>
#include <string>
#include "host.h"
// TODO(rays) Put the rest of the helpers in the namespace.
namespace tesseract {
// A simple linear congruential random number generator, using Knuth's
// constants from:
// http://en.wikipedia.org/wiki/Linear_congruential_generator.
class TRand {
public:
TRand() : seed_(1) {}
// Sets the seed to the given value.
void set_seed(uint64_t seed) {
seed_ = seed;
}
// Sets the seed using a hash of a string.
void set_seed(const std::string& str) {
std::hash<std::string> hasher;
set_seed(static_cast<uint64_t>(hasher(str)));
}
// Returns an integer in the range 0 to INT32_MAX.
int32_t IntRand() {
Iterate();
return seed_ >> 33;
}
// Returns a floating point value in the range [-range, range].
double SignedRand(double range) {
return range * 2.0 * IntRand() / INT32_MAX - range;
}
// Returns a floating point value in the range [0, range].
double UnsignedRand(double range) {
return range * IntRand() / INT32_MAX;
}
private:
// Steps the generator to the next value.
void Iterate() {
seed_ *= 6364136223846793005ULL;
seed_ += 1442695040888963407ULL;
}
// The current value of the seed.
uint64_t seed_;
};
} // namespace tesseract
// Remove newline (if any) at the end of the string.
inline void chomp_string(char *str) {
int last_index = strlen(str) - 1;
int last_index = static_cast<int>(strlen(str)) - 1;
while (last_index >= 0 &&
(str[last_index] == '\n' || str[last_index] == '\r')) {
str[last_index--] = '\0';
@@ -42,16 +93,12 @@ inline void SkipNewline(FILE *file) {
if (fgetc(file) != '\n') fseek(file, -1, SEEK_CUR);
}
// qsort function to sort 2 floats.
inline int sort_floats(const void *arg1, const void *arg2) {
float diff = *((float *) arg1) - *((float *) arg2);
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
// Swaps the two args pointed to by the pointers.
// Operator= and copy constructor must work on T.
template<typename T> inline void Swap(T* p1, T* p2) {
T tmp(*p2);
*p2 = *p1;
*p1 = tmp;
}
// return the smallest multiple of block_size greater than or equal to n.
@@ -122,9 +169,15 @@ inline int IntCastRounded(double x) {
return x >= 0.0 ? static_cast<int>(x + 0.5) : -static_cast<int>(-x + 0.5);
}
// Return a float cast to int with rounding.
inline int IntCastRounded(float x) {
return x >= 0.0f ? static_cast<int>(x + 0.5f) : -static_cast<int>(-x + 0.5f);
}
// Reverse the order of bytes in a n byte quantity for big/little-endian switch.
inline void ReverseN(void* ptr, int num_bytes) {
char *cptr = reinterpret_cast<char *>(ptr);
assert(num_bytes == 1 || num_bytes == 2 || num_bytes == 4 || num_bytes == 8);
char* cptr = static_cast<char*>(ptr);
int halfsize = num_bytes / 2;
for (int i = 0; i < halfsize; ++i) {
char tmp = cptr[i];
+21 -109
View File
@@ -1,34 +1,7 @@
/******************************************************************************
** Filename: Host.h
** Filename: host.h
** Purpose: This is the system independent typedefs and defines
** Author: MN, JG, MD
** Version: 5.4.1
** History: 11/7/94 MCD received the modification that Lennart made
** to port to 32 bit world and modify this file so that it
** will be shared between platform.
** 11/9/94 MCD Make MSW32 subset of MSW. Now MSW means
** MicroSoft Window and MSW32 means the 32 bit worlds
** of MicroSoft Window. Therefore you want the environment
** to be MicroSoft Window and in the 32 bit world -
** _WIN32 must be defined by your compiler.
** 11/30/94 MCD Incorporated comments received for more
** readability and the missing typedef for FLOAT.
** 12/1/94 MCD Added PFVOID typedef
** 5/1/95 MCD. Made many changes based on the inputs.
** Changes:
** 1) Rearrange the #ifdef so that there're definitions for
** particular platforms.
** 2) Took out the #define for computer and environment
** that developer can uncomment
** 3) Added __OLDCODE__ where the defines will be
** obsoleted in the next version and advise not to use.
** 4) Added the definitions for the following:
** FILE_HANDLE, MEMORY_HANDLE, BOOL8,
** MAX_INT8, MAX_INT16, MAX_INT32, MAX_UINT8
** MAX_UINT16, MAX_UINT32, MAX_FLOAT32
** 06/19/96 MCD. Took out MAX_FLOAT32
** 07/15/96 MCD. Fixed the comments error
** Add back BOOL8.
**
** (c) Copyright Hewlett-Packard Company, 1988-1996.
** Licensed under the Apache License, Version 2.0 (the "License");
@@ -42,94 +15,37 @@
** limitations under the License.
*/
#ifndef __HOST__
#define __HOST__
/******************************************************************************
** IMPORTANT!!! **
** **
** Defines either _WIN32, __MAC__, __UNIX__, __OS2__, __PM__ to
** use the specified definitions indicated below in the preprocessor settings. **
** **
** Also define either __FarProc__ or __FarData__ and __MOTO__ to use the
** specified definitions indicated below in the preprocessor settings. **
** **
** If a preprocessor settings is not allow in the compiler that is being use,
** then it is recommended that a "platform.h" is created with the definition
** of the computer and/or operating system.
******************************************************************************/
#ifndef TESSERACT_CCUTIL_HOST_H_
#define TESSERACT_CCUTIL_HOST_H_
#include <limits>
#include "platform.h"
/* _WIN32 */
#ifdef _WIN32
#include <windows.h>
#include <winbase.h> // winbase.h contains windows.h
#undef min
#undef max
#endif
/********************************************************/
/* __MAC__ */
#ifdef __MAC__
#include <Types.h>
/*----------------------------*/
/*----------------------------*/
#endif
/********************************************************/
#if defined(__UNIX__) || defined( __DOS__ ) || defined(__OS2__) || defined(__PM__)
/*----------------------------*/
/* FarProc and FarData */
/*----------------------------*/
/*----------------------------*/
#endif
/*****************************************************************************
**
** Standard GHC Definitions
**
*****************************************************************************/
#ifdef __MOTO__
#define __NATIVE__ MOTO
#else
#define __NATIVE__ INTEL
#endif
//typedef HANDLE FD* PHANDLE;
#include <cinttypes> // PRId32, ...
#include <cstdint> // int32_t, ...
// definitions of portable data types (numbers and characters)
typedef SIGNED char inT8;
typedef unsigned char uinT8;
typedef short inT16;
typedef unsigned short uinT16;
typedef int inT32;
typedef unsigned int uinT32;
#if (_MSC_VER >= 1200) //%%% vkr for VC 6.0
typedef INT64 inT64;
typedef UINT64 uinT64;
#else
typedef long long int inT64;
typedef unsigned long long int uinT64;
#endif //%%% vkr for VC 6.0
typedef float FLOAT32;
typedef double FLOAT64;
typedef unsigned char BOOL8;
using BOOL8 = unsigned char;
#define INT32FORMAT "%d"
#define INT64FORMAT "%lld"
#if defined(_WIN32)
#define MAX_INT8 0x7f
#define MAX_INT16 0x7fff
#define MAX_INT32 0x7fffffff
#define MAX_UINT8 0xff
#define MAX_UINT16 0xffff
#define MAX_UINT32 0xffffffff
#define MAX_FLOAT32 ((float)3.40282347e+38)
/* MinGW defines the standard PRI... macros, but MSVS doesn't. */
#define MIN_INT8 0x80
#define MIN_INT16 0x8000
#define MIN_INT32 0x80000000
#define MIN_UINT8 0x00
#define MIN_UINT16 0x0000
#define MIN_UINT32 0x00000000
#define MIN_FLOAT32 ((float)1.17549435e-38)
#if !defined(PRId32)
#define PRId32 "d"
#endif
#if !defined(PRId64)
#define PRId64 "I64d"
#endif
#endif /* _WIN32 */
// Defines
#ifndef TRUE
@@ -140,14 +56,10 @@ typedef unsigned char BOOL8;
#define FALSE 0
#endif
#ifndef NULL
#define NULL 0L
#endif
// Return true if x is within tolerance of y
template<class T> bool NearlyEqual(T x, T y, T tolerance) {
T diff = x - y;
return diff <= tolerance && -diff <= tolerance;
}
#endif
#endif // TESSERACT_CCUTIL_HOST_H_
+31 -10
View File
@@ -18,14 +18,16 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H__
#define TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H__
#ifndef TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
#define TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
#include "platform.h"
#include "pageiterator.h"
#include "unicharset.h"
#include "pageiterator.h" // for PageIterator
#include "platform.h" // for TESS_API
#include "publictypes.h" // for PageIteratorLevel
#include "unichar.h" // for StrongScriptDirection
class BLOB_CHOICE_IT;
class PAGE_RES;
class WERD_RES;
namespace tesseract {
@@ -62,6 +64,7 @@ class TESS_API LTRResultIterator : public PageIterator {
int scale, int scaled_yres,
int rect_left, int rect_top,
int rect_width, int rect_height);
virtual ~LTRResultIterator();
// LTRResultIterators may be copied! This makes it possible to iterate over
@@ -91,6 +94,10 @@ class TESS_API LTRResultIterator : public PageIterator {
// The number should be interpreted as a percent probability. (0.0f-100.0f)
float Confidence(PageIteratorLevel level) const;
// Returns the attributes of the current row.
void RowAttributes(float* row_height, float* descenders,
float* ascenders) const;
// ============= Functions that refer to words only ============.
// Returns the font attributes of the current word. If iterating at a higher
@@ -111,7 +118,7 @@ class TESS_API LTRResultIterator : public PageIterator {
int* font_id) const;
// Return the name of the language used to recognize this word.
// On error, NULL. Do not delete this pointer.
// On error, nullptr. Do not delete this pointer.
const char* WordRecognitionLanguage() const;
// Return the overall directionality of this word.
@@ -120,6 +127,9 @@ class TESS_API LTRResultIterator : public PageIterator {
// Returns true if the current word was found in a dictionary.
bool WordIsFromDictionary() const;
// Returns the number of blanks before the current word.
int BlanksBeforeWord() const;
// Returns true if the current word is numeric.
bool WordIsNumeric() const;
@@ -128,20 +138,31 @@ class TESS_API LTRResultIterator : public PageIterator {
// Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle
// of the current word.
void *GetParamsTrainingBundle() const;
const void *GetParamsTrainingBundle() const;
// Returns a pointer to the string with blamer information for this word.
// Assumes that the word's blamer_bundle is not NULL.
// Assumes that the word's blamer_bundle is not nullptr.
const char *GetBlamerDebug() const;
// Returns a pointer to the string with misadaption information for this word.
// Assumes that the word's blamer_bundle is not NULL.
// Assumes that the word's blamer_bundle is not nullptr.
const char *GetBlamerMisadaptionDebug() const;
// Returns true if a truth string was recorded for the current word.
bool HasTruthString() const;
// Returns true if the given string is equivalent to the truth string for
// the current word.
bool EquivalentToTruth(const char *str) const;
// Returns a null terminated UTF-8 encoded truth string for the current word.
// Use delete [] to free after use.
char* WordTruthUTF8Text() const;
// Returns a null terminated UTF-8 encoded normalized OCR string for the
// current word. Use delete [] to free after use.
char* WordNormedUTF8Text() const;
// Returns a pointer to serialized choice lattice.
// Fills lattice_size with the number of bytes in lattice data.
const char *WordLattice(int *lattice_size) const;
@@ -200,4 +221,4 @@ class ChoiceIterator {
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H__
#endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
-43
View File
@@ -1,43 +0,0 @@
/**********************************************************************
* File: memry.h (Formerly memory.h)
* Description: Header file for basic memory allocation/deallocation.
* Author: Ray Smith
* Created: Tue May 8 16:03:48 BST 1990
*
* (C) Copyright 1990, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef MEMRY_H
#define MEMRY_H
#include <stddef.h>
#include "host.h"
// allocate string
extern char *alloc_string(inT32 count);
// free a string.
extern void free_string(char *string);
// allocate memory
extern void *alloc_struct(inT32 count, const char *name = NULL);
// free a structure.
extern void free_struct(void *deadstruct, inT32, const char *name = NULL);
// get some memory
extern void *alloc_mem(inT32 count);
// get some memory initialized to 0.
extern void *alloc_big_zeros(inT32 count);
// free mem from alloc_mem
extern void free_mem(void *oldchunk);
// free mem from alloc_big_zeros
extern void free_big_mem(void *oldchunk);
#endif
-31
View File
@@ -1,31 +0,0 @@
/**********************************************************************
* File: ndminx.h (Formerly ndminmax.h)
* Description: Extended ascii chars
* Author: Phil Cheatle
* Created: Mon Mar 29 14:46:01 BST 1993
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef NDMINX_H
#define NDMINX_H
#ifndef MAX
#define MAX(x,y) (((x) >= (y))?(x):(y))
#endif
#ifndef MIN
#define MIN(x,y) (((x) <= (y))?(x):(y))
#endif
#endif
+184
View File
@@ -0,0 +1,184 @@
/**********************************************************************
* File: ocrclass.h
* Description: Class definitions and constants for the OCR API.
* Author: Hewlett-Packard Co
*
* (C) Copyright 1996, Hewlett-Packard Co.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
/**********************************************************************
* This file contains typedefs for all the structures used by
* the HP OCR interface.
* The code is designed to be used with either a C or C++ compiler.
* The structures are designed to allow them to be used with any
* structure alignment up to 8.
**********************************************************************/
#ifndef CCUTIL_OCRCLASS_H_
#define CCUTIL_OCRCLASS_H_
#ifndef __GNUC__
#ifdef _WIN32
#include "gettimeofday.h"
#endif
#else
#include <sys/time.h>
#endif
#include <ctime>
#include "host.h"
/*Maximum lengths of various strings*/
#define MAX_FONT_NAME 34 /*name of font */
#define MAX_OCR_NAME 32 /*name of engine */
#define MAX_OCR_VERSION 17 /*version code of engine */
/*pitch set definitions are identical to RTF*/
#define PITCH_DEF 0 /*default */
#define PITCH_FIXED 1 /*fixed pitch */
#define PITCH_VAR 2 /*variable pitch */
/**********************************************************************
* EANYCODE_CHAR
* Description of a single character. The character code is defined by
* the character set of the current font.
* Output text is sent as an array of these structures.
* Spaces and line endings in the output are represented in the
* structures of the surrounding characters. They are not directly
* represented as characters.
* The first character in a word has a positive value of blanks.
* Missing information should be set to the defaults in the comments.
* If word bounds are known, but not character bounds, then the top and
* bottom of each character should be those of the word. The left of the
* first and right of the last char in each word should be set. All other
* lefts and rights should be set to -1.
* If set, the values of right and bottom are left+width and top+height.
* Most of the members come directly from the parameters to ocr_append_char.
* The formatting member uses the enhancement parameter and combines the
* line direction stuff into the top 3 bits.
* The coding is 0=RL char, 1=LR char, 2=DR NL, 3=UL NL, 4=DR Para,
* 5=UL Para, 6=TB char, 7=BT char. API users do not need to know what
* the coding is, only that it is backwards compatible with the previous
* version.
**********************************************************************/
typedef struct { /*single character */
// It should be noted that the format for char_code for version 2.0 and beyond
// is UTF8 which means that ASCII characters will come out as one structure but
// other characters will be returned in two or more instances of this structure
// with a single byte of the UTF8 code in each, but each will have the same
// bounding box. Programs which want to handle languagues with different
// characters sets will need to handle extended characters appropriately, but
// *all* code needs to be prepared to receive UTF8 coded characters for
// characters such as bullet and fancy quotes.
uint16_t char_code; /*character itself */
int16_t left; /*of char (-1) */
int16_t right; /*of char (-1) */
int16_t top; /*of char (-1) */
int16_t bottom; /*of char (-1) */
int16_t font_index; /*what font (0) */
uint8_t confidence; /*0=perfect, 100=reject (0/100) */
uint8_t point_size; /*of char, 72=i inch, (10) */
int8_t blanks; /*no of spaces before this char (1) */
uint8_t formatting; /*char formatting (0) */
} EANYCODE_CHAR; /*single character */
/**********************************************************************
* ETEXT_DESC
* Description of the output of the OCR engine.
* This structure is used as both a progress monitor and the final
* output header, since it needs to be a valid progress monitor while
* the OCR engine is storing its output to shared memory.
* During progress, all the buffer info is -1.
* Progress starts at 0 and increases to 100 during OCR. No other constraint.
* Additionally the progress callback contains the bounding box of the word that
* is currently being processed.
* Every progress callback, the OCR engine must set ocr_alive to 1.
* The HP side will set ocr_alive to 0. Repeated failure to reset
* to 1 indicates that the OCR engine is dead.
* If the cancel function is not null then it is called with the number of
* user words found. If it returns true then operation is cancelled.
**********************************************************************/
class ETEXT_DESC;
typedef bool (*CANCEL_FUNC)(void* cancel_this, int words);
typedef bool (*PROGRESS_FUNC)(int progress, int left, int right, int top,
int bottom);
typedef bool (*PROGRESS_FUNC2)(ETEXT_DESC* ths, int left, int right, int top,
int bottom);
class ETEXT_DESC { // output header
public:
int16_t count; /// chars in this buffer(0)
int16_t progress; /// percent complete increasing (0-100)
/** Progress monitor covers word recognition and it does not cover layout
* analysis.
* See Ray comment in https://github.com/tesseract-ocr/tesseract/pull/27 */
int8_t more_to_come; /// true if not last
volatile int8_t ocr_alive; /// ocr sets to 1, HP 0
int8_t err_code; /// for errcode use
CANCEL_FUNC cancel; /// returns true to cancel
PROGRESS_FUNC progress_callback; /// called whenever progress increases
PROGRESS_FUNC2 progress_callback2;/// monitor-aware progress callback
void* cancel_this; /// this or other data for cancel
struct timeval end_time; /// Time to stop. Expected to be set only
/// by call to set_deadline_msecs().
EANYCODE_CHAR text[1]; /// character data
ETEXT_DESC()
: count(0),
progress(0),
more_to_come(0),
ocr_alive(0),
err_code(0),
cancel(nullptr),
progress_callback(nullptr),
progress_callback2(&default_progress_func),
cancel_this(nullptr) {
end_time.tv_sec = 0;
end_time.tv_usec = 0;
}
// Sets the end time to be deadline_msecs milliseconds from now.
void set_deadline_msecs(int32_t deadline_msecs) {
gettimeofday(&end_time, nullptr);
int32_t deadline_secs = deadline_msecs / 1000;
end_time.tv_sec += deadline_secs;
end_time.tv_usec += (deadline_msecs - deadline_secs * 1000) * 1000;
if (end_time.tv_usec > 1000000) {
end_time.tv_usec -= 1000000;
++end_time.tv_sec;
}
}
// Returns false if we've not passed the end_time, or have not set a deadline.
bool deadline_exceeded() const {
if (end_time.tv_sec == 0 && end_time.tv_usec == 0) return false;
struct timeval now;
gettimeofday(&now, nullptr);
return (now.tv_sec > end_time.tv_sec || (now.tv_sec == end_time.tv_sec &&
now.tv_usec > end_time.tv_usec));
}
private:
static bool default_progress_func(ETEXT_DESC* ths, int left, int right, int top,
int bottom)
{
if (ths->progress_callback) {
return (*(ths->progress_callback))(ths->progress, left, right, top, bottom);
}
return true;
}
};
#endif // CCUTIL_OCRCLASS_H_
+140
View File
@@ -0,0 +1,140 @@
///////////////////////////////////////////////////////////////////////
// File: osdetect.h
// Description: Orientation and script detection.
// Author: Samuel Charron
// Ranjith Unnikrishnan
//
// (C) Copyright 2008, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_OSDETECT_H_
#define TESSERACT_CCMAIN_OSDETECT_H_
#include "platform.h" // for TESS_API
class BLOBNBOX;
class BLOBNBOX_CLIST;
class BLOB_CHOICE_LIST;
class STRING;
class TO_BLOCK_LIST;
class UNICHARSET;
template <typename T> class GenericVector;
namespace tesseract {
class Tesseract;
}
// Max number of scripts in ICU + "NULL" + Japanese and Korean + Fraktur
const int kMaxNumberOfScripts = 116 + 1 + 2 + 1;
struct OSBestResult {
OSBestResult() : orientation_id(0), script_id(0), sconfidence(0.0),
oconfidence(0.0) {}
int orientation_id;
int script_id;
float sconfidence;
float oconfidence;
};
struct OSResults {
OSResults() : unicharset(nullptr) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < kMaxNumberOfScripts; ++j)
scripts_na[i][j] = 0;
orientations[i] = 0;
}
}
void update_best_orientation();
// Set the estimate of the orientation to the given id.
void set_best_orientation(int orientation_id);
// Update/Compute the best estimate of the script assuming the given
// orientation id.
void update_best_script(int orientation_id);
// Return the index of the script with the highest score for this orientation.
TESS_API int get_best_script(int orientation_id) const;
// Accumulate scores with given OSResults instance and update the best script.
void accumulate(const OSResults& osr);
// Print statistics.
void print_scores(void) const;
void print_scores(int orientation_id) const;
// Array holding scores for each orientation id [0,3].
// Orientation ids [0..3] map to [0, 270, 180, 90] degree orientations of the
// page respectively, where the values refer to the amount of clockwise
// rotation to be applied to the page for the text to be upright and readable.
float orientations[4];
// Script confidence scores for each of 4 possible orientations.
float scripts_na[4][kMaxNumberOfScripts];
UNICHARSET* unicharset;
OSBestResult best_result;
};
class OrientationDetector {
public:
OrientationDetector(const GenericVector<int>* allowed_scripts,
OSResults* results);
bool detect_blob(BLOB_CHOICE_LIST* scores);
int get_orientation();
private:
OSResults* osr_;
const GenericVector<int>* allowed_scripts_;
};
class ScriptDetector {
public:
ScriptDetector(const GenericVector<int>* allowed_scripts,
OSResults* osr, tesseract::Tesseract* tess);
void detect_blob(BLOB_CHOICE_LIST* scores);
bool must_stop(int orientation);
private:
OSResults* osr_;
static const char* korean_script_;
static const char* japanese_script_;
static const char* fraktur_script_;
int korean_id_;
int japanese_id_;
int katakana_id_;
int hiragana_id_;
int han_id_;
int hangul_id_;
int latin_id_;
int fraktur_id_;
tesseract::Tesseract* tess_;
const GenericVector<int>* allowed_scripts_;
};
int orientation_and_script_detection(STRING& filename,
OSResults*,
tesseract::Tesseract*);
int os_detect(TO_BLOCK_LIST* port_blocks,
OSResults* osr,
tesseract::Tesseract* tess);
int os_detect_blobs(const GenericVector<int>* allowed_scripts,
BLOBNBOX_CLIST* blob_list,
OSResults* osr,
tesseract::Tesseract* tess);
bool os_detect_blob(BLOBNBOX* bbox, OrientationDetector* o,
ScriptDetector* s, OSResults*,
tesseract::Tesseract* tess);
// Helper method to convert an orientation index to its value in degrees.
// The value represents the amount of clockwise rotation in degrees that must be
// applied for the text to be upright (readable).
TESS_API int OrientationIdToValue(const int& id);
#endif // TESSERACT_CCMAIN_OSDETECT_H_
+46 -9
View File
@@ -18,18 +18,19 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_PAGEITERATOR_H__
#define TESSERACT_CCMAIN_PAGEITERATOR_H__
#ifndef TESSERACT_CCMAIN_PAGEITERATOR_H_
#define TESSERACT_CCMAIN_PAGEITERATOR_H_
#include "publictypes.h"
#include "platform.h"
struct BlamerBundle;
class C_BLOB_IT;
class PBLOB_IT;
class PAGE_RES;
class PAGE_RES_IT;
class WERD;
struct Pix;
struct Pta;
namespace tesseract {
@@ -85,7 +86,7 @@ class TESS_API PageIterator {
// ============= Moving around within the page ============.
/**
* Moves the iterator to point to the start of the page to begin an
* Moves the iterator to point to the start of the page to begin an
* iteration.
*/
virtual void Begin();
@@ -178,6 +179,21 @@ class TESS_API PageIterator {
// If an image rectangle has been set in the API, then returned coordinates
// relate to the original (full) image, rather than the rectangle.
/**
* Controls what to include in a bounding box. Bounding boxes of all levels
* between RIL_WORD and RIL_BLOCK can include or exclude potential diacritics.
* Between layout analysis and recognition, it isn't known where all
* diacritics belong, so this control is used to include or exclude some
* diacritics that are above or below the main body of the word. In most cases
* where the placement is obvious, and after recognition, it doesn't make as
* much difference, as the diacritics will already be included in the word.
*/
void SetBoundingBoxComponents(bool include_upper_dots,
bool include_lower_dots) {
include_upper_dots_ = include_upper_dots;
include_lower_dots_ = include_lower_dots;
}
/**
* Returns the bounding rectangle of the current object at the given level.
* See comment on coordinate system above.
@@ -189,6 +205,8 @@ class TESS_API PageIterator {
*/
bool BoundingBox(PageIteratorLevel level,
int* left, int* top, int* right, int* bottom) const;
bool BoundingBox(PageIteratorLevel level, const int padding,
int* left, int* top, int* right, int* bottom) const;
/**
* Returns the bounding rectangle of the object in a coordinate system of the
* working image rectangle having its origin at (rect_left_, rect_top_) with
@@ -201,11 +219,20 @@ class TESS_API PageIterator {
bool Empty(PageIteratorLevel level) const;
/**
* Returns the type of the current block. See apitypes.h for
* Returns the type of the current block. See apitypes.h for
* PolyBlockType.
*/
PolyBlockType BlockType() const;
/**
* Returns the polygon outline of the current block. The returned Pta must
* be ptaDestroy-ed after use. Note that the returned Pta lists the vertices
* of the polygon, and the last edge is the line segment between the last
* point and the first point. nullptr will be returned if the iterator is
* at the end of the document or layout analysis was not used.
*/
Pta* BlockPolygon() const;
/**
* Returns a binary image of the current object at the given level.
* The position and size match the return from BoundingBoxInternal, and so
@@ -222,9 +249,10 @@ class TESS_API PageIterator {
* padding, so the top-left position of the returned image is returned
* in (left,top). These will most likely not match the coordinates
* returned by BoundingBox.
* If you do not supply an original image, you will get a binary one.
* Use pixDestroy to delete the image after use.
*/
Pix* GetImage(PageIteratorLevel level, int padding,
Pix* GetImage(PageIteratorLevel level, int padding, Pix* original_img,
int* left, int* top) const;
/**
@@ -282,6 +310,12 @@ class TESS_API PageIterator {
bool *is_crown,
int *first_line_indent) const;
// If the current WERD_RES (it_->word()) is not nullptr, sets the BlamerBundle
// of the current word to the given pointer (takes ownership of the pointer)
// and returns true.
// Can only be used when iterating on the word level.
bool SetWordBlamerBundle(BlamerBundle *blamer_bundle);
protected:
/**
* Sets up the internal data for iterating the blobs of a new word, then
@@ -300,7 +334,7 @@ class TESS_API PageIterator {
PAGE_RES_IT* it_;
/**
* The current input WERD being iterated. If there is an output from OCR,
* then word_ is NULL. Owned by the API
* then word_ is nullptr. Owned by the API
*/
WERD* word_;
/** The length of the current word_. */
@@ -308,11 +342,14 @@ class TESS_API PageIterator {
/** The current blob index within the word. */
int blob_index_;
/**
* Iterator to the blobs within the word. If NULL, then we are iterating
* Iterator to the blobs within the word. If nullptr, then we are iterating
* OCR results in the box_word.
* Owned by this ResultIterator.
*/
C_BLOB_IT* cblob_it_;
/** Control over what to include in bounding boxes. */
bool include_upper_dots_;
bool include_lower_dots_;
/** Parameters saved from the Thresholder. Needed to rebuild coordinates.*/
int scale_;
int scaled_yres_;
@@ -324,4 +361,4 @@ class TESS_API PageIterator {
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_PAGEITERATOR_H__
#endif // TESSERACT_CCMAIN_PAGEITERATOR_H_
-296
View File
@@ -1,296 +0,0 @@
/**********************************************************************
* File: params.h
* Description: Class definitions of the *_VAR classes for tunable constants.
* Author: Ray Smith
* Created: Fri Feb 22 11:26:25 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef PARAMS_H
#define PARAMS_H
#include <stdio.h>
#include "genericvector.h"
#include "strngs.h"
namespace tesseract {
class IntParam;
class BoolParam;
class StringParam;
class DoubleParam;
// Enum for constraints on what kind of params should be set by SetParam().
enum SetParamConstraint {
SET_PARAM_CONSTRAINT_NONE,
SET_PARAM_CONSTRAINT_DEBUG_ONLY,
SET_PARAM_CONSTRAINT_NON_DEBUG_ONLY,
SET_PARAM_CONSTRAINT_NON_INIT_ONLY,
};
struct ParamsVectors {
GenericVector<IntParam *> int_params;
GenericVector<BoolParam *> bool_params;
GenericVector<StringParam *> string_params;
GenericVector<DoubleParam *> double_params;
};
// Utility functions for working with Tesseract parameters.
class ParamUtils {
public:
// Reads a file of parameter definitions and set/modify the values therein.
// If the filename begins with a + or -, the BoolVariables will be
// ORed or ANDed with any current values.
// Blank lines and lines beginning # are ignored.
// Values may have any whitespace after the name and are the rest of line.
static bool ReadParamsFile(
const char *file, // filename to read
SetParamConstraint constraint,
ParamsVectors *member_params);
// Read parameters from the given file pointer (stop at end_offset).
static bool ReadParamsFromFp(FILE *fp, inT64 end_offset,
SetParamConstraint constraint,
ParamsVectors *member_params);
// Set a parameters to have the given value.
static bool SetParam(const char *name, const char* value,
SetParamConstraint constraint,
ParamsVectors *member_params);
// Returns the pointer to the parameter with the given name (of the
// appropriate type) if it was found in the vector obtained from
// GlobalParams() or in the given member_params.
template<class T>
static T *FindParam(const char *name,
const GenericVector<T *> &global_vec,
const GenericVector<T *> &member_vec) {
int i;
for (i = 0; i < global_vec.size(); ++i) {
if (strcmp(global_vec[i]->name_str(), name) == 0) return global_vec[i];
}
for (i = 0; i < member_vec.size(); ++i) {
if (strcmp(member_vec[i]->name_str(), name) == 0) return member_vec[i];
}
return NULL;
}
// Removes the given pointer to the param from the given vector.
template<class T>
static void RemoveParam(T *param_ptr, GenericVector<T *> *vec) {
for (int i = 0; i < vec->size(); ++i) {
if ((*vec)[i] == param_ptr) {
vec->remove(i);
return;
}
}
}
// Fetches the value of the named param as a STRING. Returns false if not
// found.
static bool GetParamAsString(const char *name,
const ParamsVectors* member_params,
STRING *value);
// Print parameters to the given file.
static void PrintParams(FILE *fp, const ParamsVectors *member_params);
};
// Definition of various parameter types.
class Param {
public:
~Param() {}
const char *name_str() const { return name_; }
const char *info_str() const { return info_; }
bool is_init() const { return init_; }
bool is_debug() const { return debug_; }
bool constraint_ok(SetParamConstraint constraint) const {
return (constraint == SET_PARAM_CONSTRAINT_NONE ||
(constraint == SET_PARAM_CONSTRAINT_DEBUG_ONLY &&
this->is_debug()) ||
(constraint == SET_PARAM_CONSTRAINT_NON_DEBUG_ONLY &&
!this->is_debug()) ||
(constraint == SET_PARAM_CONSTRAINT_NON_INIT_ONLY &&
!this->is_init()));
}
protected:
Param(const char *name, const char *comment, bool init) :
name_(name), info_(comment), init_(init) {
debug_ = (strstr(name, "debug") != NULL) || (strstr(name, "display"));
}
const char *name_; // name of this parameter
const char *info_; // for menus
bool init_; // needs to be set before init
bool debug_;
};
class IntParam : public Param {
public:
IntParam(inT32 value, const char *name, const char *comment, bool init,
ParamsVectors *vec) : Param(name, comment, init) {
value_ = value;
params_vec_ = &(vec->int_params);
vec->int_params.push_back(this);
}
~IntParam() { ParamUtils::RemoveParam<IntParam>(this, params_vec_); }
operator inT32() const { return value_; }
void set_value(inT32 value) { value_ = value; }
private:
inT32 value_;
// Pointer to the vector that contains this param (not owened by this class).
GenericVector<IntParam *> *params_vec_;
};
class BoolParam : public Param {
public:
BoolParam(bool value, const char *name, const char *comment, bool init,
ParamsVectors *vec) : Param(name, comment, init) {
value_ = value;
params_vec_ = &(vec->bool_params);
vec->bool_params.push_back(this);
}
~BoolParam() { ParamUtils::RemoveParam<BoolParam>(this, params_vec_); }
operator BOOL8() const { return value_; }
void set_value(BOOL8 value) { value_ = value; }
private:
BOOL8 value_;
// Pointer to the vector that contains this param (not owned by this class).
GenericVector<BoolParam *> *params_vec_;
};
class StringParam : public Param {
public:
StringParam(const char *value, const char *name,
const char *comment, bool init,
ParamsVectors *vec) : Param(name, comment, init) {
value_ = value;
params_vec_ = &(vec->string_params);
vec->string_params.push_back(this);
}
~StringParam() { ParamUtils::RemoveParam<StringParam>(this, params_vec_); }
operator STRING &() { return value_; }
const char *string() const { return value_.string(); }
bool empty() { return value_.length() <= 0; }
void set_value(const STRING &value) { value_ = value; }
private:
STRING value_;
// Pointer to the vector that contains this param (not owened by this class).
GenericVector<StringParam *> *params_vec_;
};
class DoubleParam : public Param {
public:
DoubleParam(double value, const char *name, const char *comment,
bool init, ParamsVectors *vec) : Param(name, comment, init) {
value_ = value;
params_vec_ = &(vec->double_params);
vec->double_params.push_back(this);
}
~DoubleParam() { ParamUtils::RemoveParam<DoubleParam>(this, params_vec_); }
operator double() const { return value_; }
void set_value(double value) { value_ = value; }
private:
double value_;
// Pointer to the vector that contains this param (not owned by this class).
GenericVector<DoubleParam *> *params_vec_;
};
} // namespace tesseract
// Global parameter lists.
//
// To avoid the problem of undetermined order of static initialization
// global_params are accessed through the GlobalParams function that
// initializes the static pointer to global_params only on the first
// first time GlobalParams() is called.
//
// TODO(daria): remove GlobalParams() when all global Tesseract
// parameters are converted to members.
tesseract::ParamsVectors *GlobalParams();
/*************************************************************************
* Note on defining parameters.
*
* The values of the parameters defined with *_INIT_* macros are guaranteed
* to be loaded from config files before Tesseract initialization is done
* (there is no such guarantee for parameters defined with the other macros).
*************************************************************************/
#define INT_VAR_H(name,val,comment)\
tesseract::IntParam name
#define BOOL_VAR_H(name,val,comment)\
tesseract::BoolParam name
#define STRING_VAR_H(name,val,comment)\
tesseract::StringParam name
#define double_VAR_H(name,val,comment)\
tesseract::DoubleParam name
#define INT_VAR(name,val,comment)\
tesseract::IntParam name(val,#name,comment,false,GlobalParams())
#define BOOL_VAR(name,val,comment)\
tesseract::BoolParam name(val,#name,comment,false,GlobalParams())
#define STRING_VAR(name,val,comment)\
tesseract::StringParam name(val,#name,comment,false,GlobalParams())
#define double_VAR(name,val,comment)\
tesseract::DoubleParam name(val,#name,comment,false,GlobalParams())
#define INT_INIT_VAR(name,val,comment)\
tesseract::IntParam name(val,#name,comment,true,GlobalParams())
#define BOOL_INIT_VAR(name,val,comment)\
tesseract::BoolParam name(val,#name,comment,true,GlobalParams())
#define STRING_INIT_VAR(name,val,comment)\
tesseract::StringParam name(val,#name,comment,true,GlobalParams())
#define double_INIT_VAR(name,val,comment)\
tesseract::DoubleParam name(val,#name,comment,true,GlobalParams())
#define INT_MEMBER(name, val, comment, vec)\
name(val, #name, comment, false, vec)
#define BOOL_MEMBER(name, val, comment, vec)\
name(val, #name, comment, false, vec)
#define STRING_MEMBER(name, val, comment, vec)\
name(val, #name, comment, false, vec)
#define double_MEMBER(name, val, comment, vec)\
name(val, #name, comment, false, vec)
#define INT_INIT_MEMBER(name, val, comment, vec)\
name(val, #name, comment, true, vec)
#define BOOL_INIT_MEMBER(name, val, comment, vec)\
name(val, #name, comment, true, vec)
#define STRING_INIT_MEMBER(name, val, comment, vec)\
name(val, #name, comment, true, vec)
#define double_INIT_MEMBER(name, val, comment, vec)\
name(val, #name, comment, true, vec)
#endif
+19 -12
View File
@@ -17,26 +17,27 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_PLATFORM_H__
#define TESSERACT_CCUTIL_PLATFORM_H__
#ifndef TESSERACT_CCUTIL_PLATFORM_H_
#define TESSERACT_CCUTIL_PLATFORM_H_
#define DLLSYM
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif /* NOMINMAX */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifdef __GNUC__
#define ultoa _ultoa
typedef struct _BLOB {
unsigned int cbSize;
char *pBlobData;
} BLOB, *LPBLOB;
#endif /* __GNUC__ */
#define SIGNED
#define snprintf _snprintf
#if (_MSC_VER <= 1400)
#define vsnprintf _vsnprintf
#endif /* _WIN32 */
#else
#define __UNIX__
#ifdef __cplusplus
#include <climits>
#else /* C compiler*/
#include <limits.h>
#endif /* __cplusplus */
#ifndef PATH_MAX
#define MAX_PATH 4096
#else
@@ -45,6 +46,12 @@ typedef struct _BLOB {
#define SIGNED signed
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(TESS_EXPORTS)
#define TESS_API __declspec(dllexport)
@@ -69,4 +76,4 @@ typedef struct _BLOB {
#endif
#endif
#endif // TESSERACT_CCUTIL_PLATFORM_H__
#endif // TESSERACT_CCUTIL_PLATFORM_H_
+57 -20
View File
@@ -17,8 +17,8 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H__
#define TESSERACT_CCSTRUCT_PUBLICTYPES_H__
#ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H_
#define TESSERACT_CCSTRUCT_PUBLICTYPES_H_
// This file contains types that are used both by the API and internally
// to Tesseract. In order to decouple the API from Tesseract and prevent cyclic
@@ -30,7 +30,19 @@
// API-level code should include apitypes.h in preference to this file.
/** Number of printers' points in an inch. The unit of the pointsize return. */
const int kPointsPerInch = 72;
constexpr int kPointsPerInch = 72;
/**
* Minimum believable resolution. Used as a default if there is no other
* information, as it is safer to under-estimate than over-estimate.
*/
constexpr int kMinCredibleResolution = 70;
/** Maximum believable resolution. */
constexpr int kMaxCredibleResolution = 2400;
/**
* Ratio between median blob size and likely resolution. Used to estimate
* resolution when none is provided. This is basically 1/usual text size in
* inches. */
constexpr int kResolutionEstimationFactor = 10;
/**
* Possible types for a POLY_BLOCK or ColPartition.
@@ -73,6 +85,10 @@ inline bool PTIsTextType(PolyBlockType type) {
type == PT_VERTICAL_TEXT || type == PT_CAPTION_TEXT ||
type == PT_INLINE_EQUATION;
}
// Returns true if PolyBlockType is of pullout(inter-column) type
inline bool PTIsPulloutType(PolyBlockType type) {
return type == PT_PULLOUT_IMAGE || type == PT_PULLOUT_TEXT;
}
/** String name for each block type. Keep in sync with PolyBlockType. */
extern const char* kPolyBlockNames[];
@@ -158,24 +174,42 @@ enum PageSegMode {
PSM_SINGLE_WORD, ///< Treat the image as a single word.
PSM_CIRCLE_WORD, ///< Treat the image as a single word in a circle.
PSM_SINGLE_CHAR, ///< Treat the image as a single character.
PSM_SPARSE_TEXT, ///< Find as much text as possible in no particular order.
PSM_SPARSE_TEXT_OSD, ///< Sparse text with orientation and script det.
PSM_RAW_LINE, ///< Treat the image as a single text line, bypassing
///< hacks that are Tesseract-specific.
PSM_COUNT ///< Number of enum entries.
};
/**
* Macros that act on a PageSegMode to determine whether components of
* Inline functions that act on a PageSegMode to determine whether components of
* layout analysis are enabled.
* *Depend critically on the order of elements of PageSegMode.*
* NOTE that arg is an int for compatibility with INT_PARAM.
*/
#define PSM_OSD_ENABLED(pageseg_mode) ((pageseg_mode) <= PSM_AUTO_OSD)
#define PSM_COL_FIND_ENABLED(pageseg_mode) \
((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_AUTO)
#define PSM_BLOCK_FIND_ENABLED(pageseg_mode) \
((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_COLUMN)
#define PSM_LINE_FIND_ENABLED(pageseg_mode) \
((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_BLOCK)
#define PSM_WORD_FIND_ENABLED(pageseg_mode) \
((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_LINE)
inline bool PSM_OSD_ENABLED(int pageseg_mode) {
return pageseg_mode <= PSM_AUTO_OSD || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
inline bool PSM_ORIENTATION_ENABLED(int pageseg_mode) {
return pageseg_mode <= PSM_AUTO || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
inline bool PSM_COL_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_AUTO;
}
inline bool PSM_SPARSE(int pageseg_mode) {
return pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
inline bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_COLUMN;
}
inline bool PSM_LINE_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_BLOCK;
}
inline bool PSM_WORD_FIND_ENABLED(int pageseg_mode) {
return (pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_LINE) ||
pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
/**
* enum of the elements of the page hierarchy, used in ResultIterator
@@ -191,7 +225,7 @@ enum PageIteratorLevel {
};
/**
* JUSTIFICATION_UNKNONW
* JUSTIFICATION_UNKNOWN
* The alignment is not clearly one of the other options. This could happen
* for example if there are only one or two lines of text or the text looks
* like source code or poetry.
@@ -213,7 +247,7 @@ enum PageIteratorLevel {
*
* JUSTIFICATION_RIGHT
* Each line, except possibly the first, is flush to the same right tab stop.
*/
*/
enum ParagraphJustification {
JUSTIFICATION_UNKNOWN,
JUSTIFICATION_LEFT,
@@ -232,18 +266,21 @@ enum ParagraphJustification {
* mention the connection to OcrEngineMode in the comments.
*/
enum OcrEngineMode {
OEM_TESSERACT_ONLY, // Run Tesseract only - fastest
OEM_CUBE_ONLY, // Run Cube only - better accuracy, but slower
OEM_TESSERACT_CUBE_COMBINED, // Run both and combine results - best accuracy
OEM_DEFAULT // Specify this mode when calling init_*(),
OEM_TESSERACT_ONLY, // Run Tesseract only - fastest; deprecated
OEM_LSTM_ONLY, // Run just the LSTM line recognizer.
OEM_TESSERACT_LSTM_COMBINED, // Run the LSTM recognizer, but allow fallback
// to Tesseract when things get difficult.
// deprecated
OEM_DEFAULT, // Specify this mode when calling init_*(),
// to indicate that any of the above modes
// should be automatically inferred from the
// variables in the language-specific config,
// command-line configs, or if not specified
// in any of the above should be set to the
// default OEM_TESSERACT_ONLY.
OEM_COUNT // Number of OEMs
};
} // namespace tesseract.
#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H__
#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H_
+262
View File
@@ -0,0 +1,262 @@
///////////////////////////////////////////////////////////////////////
// File: renderer.h
// Description: Rendering interface to inject into TessBaseAPI
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_RENDERER_H_
#define TESSERACT_API_RENDERER_H_
// To avoid collision with other typenames include the ABSOLUTE MINIMUM
// complexity of includes here. Use forward declarations wherever possible
// and hide includes of complex types in baseapi.cpp.
#include <string> // for std::string
#include "genericvector.h"
#include "platform.h"
namespace tesseract {
class TessBaseAPI;
/**
* Interface for rendering tesseract results into a document, such as text,
* HOCR or pdf. This class is abstract. Specific classes handle individual
* formats. This interface is then used to inject the renderer class into
* tesseract when processing images.
*
* For simplicity implementing this with tesesract version 3.01,
* the renderer contains document state that is cleared from document
* to document just as the TessBaseAPI is. This way the base API can just
* delegate its rendering functionality to injected renderers, and the
* renderers can manage the associated state needed for the specific formats
* in addition to the heuristics for producing it.
*/
class TESS_API TessResultRenderer {
public:
virtual ~TessResultRenderer();
// Takes ownership of pointer so must be new'd instance.
// Renderers aren't ordered, but appends the sequences of next parameter
// and existing next(). The renderers should be unique across both lists.
void insert(TessResultRenderer* next);
// Returns the next renderer or nullptr.
TessResultRenderer* next() { return next_; }
/**
* Starts a new document with the given title.
* This clears the contents of the output data.
* Title should use UTF-8 encoding.
*/
bool BeginDocument(const char* title);
/**
* Adds the recognized text from the source image to the current document.
* Invalid if BeginDocument not yet called.
*
* Note that this API is a bit weird but is designed to fit into the
* current TessBaseAPI implementation where the api has lots of state
* information that we might want to add in.
*/
bool AddImage(TessBaseAPI* api);
/**
* Finishes the document and finalizes the output data
* Invalid if BeginDocument not yet called.
*/
bool EndDocument();
const char* file_extension() const { return file_extension_; }
const char* title() const { return title_.c_str(); }
// Is everything fine? Otherwise something went wrong.
bool happy() { return happy_; }
/**
* Returns the index of the last image given to AddImage
* (i.e. images are incremented whether the image succeeded or not)
*
* This is always defined. It means either the number of the
* current image, the last image ended, or in the completed document
* depending on when in the document lifecycle you are looking at it.
* Will return -1 if a document was never started.
*/
int imagenum() const { return imagenum_; }
protected:
/**
* Called by concrete classes.
*
* outputbase is the name of the output file excluding
* extension. For example, "/path/to/chocolate-chip-cookie-recipe"
*
* extension indicates the file extension to be used for output
* files. For example "pdf" will produce a .pdf file, and "hocr"
* will produce .hocr files.
*/
TessResultRenderer(const char *outputbase,
const char* extension);
// Hook for specialized handling in BeginDocument()
virtual bool BeginDocumentHandler();
// This must be overridden to render the OCR'd results
virtual bool AddImageHandler(TessBaseAPI* api) = 0;
// Hook for specialized handling in EndDocument()
virtual bool EndDocumentHandler();
// Renderers can call this to append '\0' terminated strings into
// the output string returned by GetOutput.
// This method will grow the output buffer if needed.
void AppendString(const char* s);
// Renderers can call this to append binary byte sequences into
// the output string returned by GetOutput. Note that s is not necessarily
// '\0' terminated (and can contain '\0' within it).
// This method will grow the output buffer if needed.
void AppendData(const char* s, int len);
private:
const char* file_extension_; // standard extension for generated output
STRING title_; // title of document being renderered
int imagenum_; // index of last image added
FILE* fout_; // output file pointer
TessResultRenderer* next_; // Can link multiple renderers together
bool happy_; // I get grumpy when the disk fills up, etc.
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessTextRenderer : public TessResultRenderer {
public:
explicit TessTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
/**
* Renders tesseract output into an hocr text string
*/
class TESS_API TessHOcrRenderer : public TessResultRenderer {
public:
explicit TessHOcrRenderer(const char *outputbase, bool font_info);
explicit TessHOcrRenderer(const char *outputbase);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
private:
bool font_info_; // whether to print font information
};
/**
* Renders Tesseract output into a TSV string
*/
class TESS_API TessTsvRenderer : public TessResultRenderer {
public:
explicit TessTsvRenderer(const char* outputbase, bool font_info);
explicit TessTsvRenderer(const char* outputbase);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
private:
bool font_info_; // whether to print font information
};
/**
* Renders tesseract output into searchable PDF
*/
class TESS_API TessPDFRenderer : public TessResultRenderer {
public:
// datadir is the location of the TESSDATA. We need it because
// we load a custom PDF font from this location.
TessPDFRenderer(const char* outputbase, const char* datadir, bool textonly = false);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
private:
// We don't want to have every image in memory at once,
// so we store some metadata as we go along producing
// PDFs one page at a time. At the end, that metadata is
// used to make everything that isn't easily handled in a
// streaming fashion.
long int obj_; // counter for PDF objects
GenericVector<long int> offsets_; // offset of every PDF object in bytes
GenericVector<long int> pages_; // object number for every /Page object
std::string datadir_; // where to find the custom font
bool textonly_; // skip images if set
// Bookkeeping only. DIY = Do It Yourself.
void AppendPDFObjectDIY(size_t objectsize);
// Bookkeeping + emit data.
void AppendPDFObject(const char *data);
// Create the /Contents object for an entire page.
char* GetPDFTextObjects(TessBaseAPI* api, double width, double height);
// Turn an image into a PDF object. Only transcode if we have to.
static bool imageToPDFObj(Pix* pix, const char* filename, long int objnum,
char** pdf_object, long int* pdf_object_size, const int jpg_quality);
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessUnlvRenderer : public TessResultRenderer {
public:
explicit TessUnlvRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessBoxTextRenderer : public TessResultRenderer {
public:
explicit TessBoxTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
#ifndef DISABLED_LEGACY_ENGINE
/**
* Renders tesseract output into an osd text string
*/
class TESS_API TessOsdRenderer : public TessResultRenderer {
public:
explicit TessOsdRenderer(const char* outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
#endif // ndef DISABLED_LEGACY_ENGINE
} // namespace tesseract.
#endif // TESSERACT_API_RENDERER_H_
+32 -13
View File
@@ -19,15 +19,19 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_RESULT_ITERATOR_H__
#define TESSERACT_CCMAIN_RESULT_ITERATOR_H__
#ifndef TESSERACT_CCMAIN_RESULT_ITERATOR_H_
#define TESSERACT_CCMAIN_RESULT_ITERATOR_H_
#include "platform.h"
#include "ltrresultiterator.h"
#include "genericvector.h"
#include <set> // for std::pair
#include <vector> // for std::vector
#include "ltrresultiterator.h" // for LTRResultIterator
#include "platform.h" // for TESS_API, TESS_LOCAL
#include "publictypes.h" // for PageIteratorLevel
#include "unichar.h" // for StrongScriptDirection
template <typename T> class GenericVector;
template <typename T> class GenericVectorEqEq;
class BLOB_CHOICE_IT;
class WERD_RES;
class STRING;
namespace tesseract {
@@ -42,11 +46,11 @@ class TESS_API ResultIterator : public LTRResultIterator {
* ResultIterator is copy constructible!
* The default copy constructor works just fine for us.
*/
virtual ~ResultIterator() {}
virtual ~ResultIterator() = default;
// ============= Moving around within the page ============.
/**
* Moves the iterator to point to the start of the page to begin
/**
* Moves the iterator to point to the start of the page to begin
* an iteration.
*/
virtual void Begin();
@@ -81,6 +85,10 @@ class TESS_API ResultIterator : public LTRResultIterator {
virtual bool IsAtFinalElement(PageIteratorLevel level,
PageIteratorLevel element) const;
// ============= Functions that refer to words only ============.
// Returns the number of blanks before the current word.
int BlanksBeforeWord() const;
// ============= Accessing data ==============.
/**
@@ -89,6 +97,11 @@ class TESS_API ResultIterator : public LTRResultIterator {
*/
virtual char* GetUTF8Text(PageIteratorLevel level) const;
/**
* Returns the LSTM choices for every LSTM timestep for the current word.
*/
virtual std::vector<std::vector<std::pair<const char*, float>>>* GetBestLSTMSymbolChoices() const;
/**
* Return whether the current paragraph's dominant reading direction
* is left-to-right (as opposed to right-to-left).
@@ -158,7 +171,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
void CalculateTextlineOrder(bool paragraph_is_ltr,
const LTRResultIterator &resit,
GenericVectorEqEq<int> *indices) const;
/** Same as above, but the caller's ssd gets filled in if ssd != NULL. */
/** Same as above, but the caller's ssd gets filled in if ssd != nullptr. */
void CalculateTextlineOrder(bool paragraph_is_ltr,
const LTRResultIterator &resit,
GenericVector<StrongScriptDirection> *ssd,
@@ -180,7 +193,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
void MoveToLogicalStartOfTextline();
/**
* Precondition: current_paragraph_is_ltr_ and in_minor_direction_
* Precondition: current_paragraph_is_ltr_ and in_minor_direction_
* are set.
*/
void MoveToLogicalStartOfWord();
@@ -230,8 +243,14 @@ class TESS_API ResultIterator : public LTRResultIterator {
/** Is the currently pointed-at character in a minor-direction sequence? */
bool in_minor_direction_;
/**
* Should detected inter-word spaces be preserved, or "compressed" to a single
* space character (default behavior).
*/
bool preserve_interword_spaces_;
};
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H__
#endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H_
+130 -11
View File
@@ -20,17 +20,13 @@
#ifndef SERIALIS_H
#define SERIALIS_H
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "memry.h"
#include "errcode.h"
#include "fileerr.h"
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include "host.h"
// Switch endinan.
extern DLLSYM uinT64 reverse64(uinT64);
extern DLLSYM uinT32 reverse32(uinT32);
extern DLLSYM uinT16 reverse16(uinT16);
template <typename T> class GenericVector;
class STRING;
/***********************************************************************
QUOTE_IT MACRO DEFINITION
@@ -38,6 +34,129 @@ extern DLLSYM uinT16 reverse16(uinT16);
Replace <parm> with "<parm>". <parm> may be an arbitrary number of tokens
***********************************************************************/
#define QUOTE_IT( parm ) #parm
#define QUOTE_IT(parm) #parm
namespace tesseract {
// Return number of elements of an array.
template <typename T, size_t N>
constexpr size_t countof(T const (&)[N]) noexcept {
return N;
}
// Function to read a GenericVector<char> from a whole file.
// Returns false on failure.
typedef bool (*FileReader)(const STRING& filename, GenericVector<char>* data);
// Function to write a GenericVector<char> to a whole file.
// Returns false on failure.
typedef bool (*FileWriter)(const GenericVector<char>& data,
const STRING& filename);
// Deserialize data from file.
bool DeSerialize(FILE* fp, char* data, size_t n = 1);
bool DeSerialize(FILE* fp, float* data, size_t n = 1);
bool DeSerialize(FILE* fp, int8_t* data, size_t n = 1);
bool DeSerialize(FILE* fp, int16_t* data, size_t n = 1);
bool DeSerialize(FILE* fp, int32_t* data, size_t n = 1);
bool DeSerialize(FILE* fp, uint8_t* data, size_t n = 1);
bool DeSerialize(FILE* fp, uint16_t* data, size_t n = 1);
bool DeSerialize(FILE* fp, uint32_t* data, size_t n = 1);
// Serialize data to file.
bool Serialize(FILE* fp, const char* data, size_t n = 1);
bool Serialize(FILE* fp, const float* data, size_t n = 1);
bool Serialize(FILE* fp, const int8_t* data, size_t n = 1);
bool Serialize(FILE* fp, const int16_t* data, size_t n = 1);
bool Serialize(FILE* fp, const int32_t* data, size_t n = 1);
bool Serialize(FILE* fp, const uint8_t* data, size_t n = 1);
bool Serialize(FILE* fp, const uint16_t* data, size_t n = 1);
bool Serialize(FILE* fp, const uint32_t* data, size_t n = 1);
// Simple file class.
// Allows for portable file input from memory and from foreign file systems.
class TFile {
public:
TFile();
~TFile();
// All the Open methods load the whole file into memory for reading.
// Opens a file with a supplied reader, or nullptr to use the default.
// Note that mixed read/write is not supported.
bool Open(const STRING& filename, FileReader reader);
// From an existing memory buffer.
bool Open(const char* data, int size);
// From an open file and an end offset.
bool Open(FILE* fp, int64_t end_offset);
// Sets the value of the swap flag, so that FReadEndian does the right thing.
void set_swap(bool value) { swap_ = value; }
// Deserialize data.
bool DeSerialize(char* data, size_t count = 1);
bool DeSerialize(double* data, size_t count = 1);
bool DeSerialize(float* data, size_t count = 1);
bool DeSerialize(int8_t* data, size_t count = 1);
bool DeSerialize(int16_t* data, size_t count = 1);
bool DeSerialize(int32_t* data, size_t count = 1);
bool DeSerialize(int64_t* data, size_t count = 1);
bool DeSerialize(uint8_t* data, size_t count = 1);
bool DeSerialize(uint16_t* data, size_t count = 1);
bool DeSerialize(uint32_t* data, size_t count = 1);
bool DeSerialize(uint64_t* data, size_t count = 1);
// Serialize data.
bool Serialize(const char* data, size_t count = 1);
bool Serialize(const double* data, size_t count = 1);
bool Serialize(const float* data, size_t count = 1);
bool Serialize(const int8_t* data, size_t count = 1);
bool Serialize(const int16_t* data, size_t count = 1);
bool Serialize(const int32_t* data, size_t count = 1);
bool Serialize(const int64_t* data, size_t count = 1);
bool Serialize(const uint8_t* data, size_t count = 1);
bool Serialize(const uint16_t* data, size_t count = 1);
bool Serialize(const uint32_t* data, size_t count = 1);
bool Serialize(const uint64_t* data, size_t count = 1);
// Skip data.
bool Skip(size_t count);
// Reads a line like fgets. Returns nullptr on EOF, otherwise buffer.
// Reads at most buffer_size bytes, including '\0' terminator, even if
// the line is longer. Does nothing if buffer_size <= 0.
// To use fscanf use FGets and sscanf.
char* FGets(char* buffer, int buffer_size);
// Replicates fread, followed by a swap of the bytes if needed, returning the
// number of items read. If swap_ is true then the count items will each have
// size bytes reversed.
int FReadEndian(void* buffer, size_t size, int count);
// Replicates fread, returning the number of items read.
int FRead(void* buffer, size_t size, int count);
// Resets the TFile as if it has been Opened, but nothing read.
// Only allowed while reading!
void Rewind();
// Open for writing. Either supply a non-nullptr data with OpenWrite before
// calling FWrite, (no close required), or supply a nullptr data to OpenWrite
// and call CloseWrite to write to a file after the FWrites.
void OpenWrite(GenericVector<char>* data);
bool CloseWrite(const STRING& filename, FileWriter writer);
// Replicates fwrite, returning the number of items written.
// To use fprintf, use snprintf and FWrite.
int FWrite(const void* buffer, size_t size, int count);
private:
// The number of bytes used so far.
int offset_;
// The buffered data from the file.
GenericVector<char>* data_;
// True if the data_ pointer is owned by *this.
bool data_is_owned_;
// True if the TFile is open for writing.
bool is_writing_;
// True if bytes need to be swapped in FReadEndian.
bool swap_;
};
} // namespace tesseract.
#endif
+51 -31
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* File: strngs.h (Formerly strings.h)
* Description: STRING class definition.
* Author: Ray Smith
* Created: Fri Feb 15 09:15:01 GMT 1991
* Author: Ray Smith
* Created: Fri Feb 15 09:15:01 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,13 +17,18 @@
*
**********************************************************************/
#ifndef STRNGS_H
#define STRNGS_H
#ifndef STRNGS_H
#define STRNGS_H
#include <stdio.h>
#include <string.h>
#include "platform.h"
#include "memry.h"
#include <cassert> // for assert
#include <cstdint> // for uint32_t
#include <cstdio> // for FILE
#include <cstring> // for strncpy
#include "platform.h" // for TESS_API
namespace tesseract {
class TFile;
} // namespace tesseract.
// STRING_IS_PROTECTED means that string[index] = X is invalid
// because you have to go through strings interface to modify it.
@@ -43,38 +48,53 @@ class TESS_API STRING
STRING();
STRING(const STRING &string);
STRING(const char *string);
~STRING ();
STRING(const char *data, int length);
~STRING();
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
// Writes to the given file. Returns false in case of error.
bool Serialize(tesseract::TFile* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(tesseract::TFile* fp);
// As DeSerialize, but only seeks past the data - hence a static method.
static bool SkipDeSerialize(tesseract::TFile* fp);
BOOL8 contains(const char c) const;
inT32 length() const;
inT32 size() const { return length(); }
bool contains(const char c) const;
int32_t length() const;
int32_t size() const { return length(); }
// Workaround to avoid g++ -Wsign-compare warnings.
uint32_t unsigned_size() const {
const int32_t len = length();
assert(0 <= len);
return static_cast<uint32_t>(len);
}
const char *string() const;
const char *c_str() const;
inline char* strdup() const {
inT32 len = length() + 1;
int32_t len = length() + 1;
return strncpy(new char[len], GetCStr(), len);
}
#if STRING_IS_PROTECTED
const char &operator[] (inT32 index) const;
const char &operator[] (int32_t index) const;
// len is number of chars in s to insert starting at index in this string
void insert_range(inT32 index, const char*s, int len);
void erase_range(inT32 index, int len);
void insert_range(int32_t index, const char*s, int len);
void erase_range(int32_t index, int len);
#else
char &operator[] (inT32 index) const;
char &operator[] (int32_t index) const;
#endif
void split(const char c, GenericVector<STRING> *splited);
void truncate_at(inT32 index);
void truncate_at(int32_t index);
BOOL8 operator== (const STRING & string) const;
BOOL8 operator!= (const STRING & string) const;
BOOL8 operator!= (const char *string) const;
bool operator== (const STRING & string) const;
bool operator!= (const STRING & string) const;
bool operator!= (const char *string) const;
STRING & operator= (const char *string);
STRING & operator= (const STRING & string);
@@ -94,9 +114,11 @@ class TESS_API STRING
// be ambiguous, and ints usually need a string before or between them
// anyway.
void add_str_int(const char* str, int number);
// Appends the given string and double (as a %.8g) to this.
void add_str_double(const char* str, double number);
// ensure capcaity but keep pointer encapsulated
inline void ensure(inT32 min_capacity) { ensure_cstr(min_capacity); }
// ensure capacity but keep pointer encapsulated
inline void ensure(int32_t min_capacity) { ensure_cstr(min_capacity); }
private:
typedef struct STRING_HEADER {
@@ -106,9 +128,9 @@ class TESS_API STRING
// used_ is how much of the capacity is currently being used,
// including a '\0' terminator.
//
// If used_ is 0 then string is NULL (not even the '\0')
// If used_ is 0 then string is nullptr (not even the '\0')
// else if used_ > 0 then it is strlen() + 1 (because it includes '\0')
// else strlen is >= 0 (not NULL) but needs to be computed.
// else strlen is >= 0 (not nullptr) but needs to be computed.
// this condition is set when encapsulation is violated because
// an API returned a mutable string.
//
@@ -132,17 +154,15 @@ class TESS_API STRING
}
// returns the string data part of storage
inline char* GetCStr() {
return ((char *)data_) + sizeof(STRING_HEADER);
};
inline char* GetCStr() { return ((char*)data_) + sizeof(STRING_HEADER); }
inline const char* GetCStr() const {
return ((const char *)data_) + sizeof(STRING_HEADER);
};
}
inline bool InvariantOk() const {
#if STRING_IS_PROTECTED
return (GetHeader()->used_ == 0) ?
(string() == NULL) : (GetHeader()->used_ == (strlen(string()) + 1));
(string() == nullptr) : (GetHeader()->used_ == (strlen(string()) + 1));
#else
return true;
#endif
@@ -151,7 +171,7 @@ class TESS_API STRING
// Ensure string has requested capacity as optimization
// to avoid unnecessary reallocations.
// The return value is a cstr buffer with at least requested capacity
char* ensure_cstr(inT32 min_capacity);
char* ensure_cstr(int32_t min_capacity);
void FixHeader() const; // make used_ non-negative, even if const
@@ -0,0 +1,30 @@
///////////////////////////////////////////////////////////////////////
// File: version.h
// Description: Version information
//
// (C) Copyright 2018, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_VERSION_H_
#define TESSERACT_API_VERSION_H_
#define TESSERACT_MAJOR_VERSION 4
#define TESSERACT_MINOR_VERSION 0
#define TESSERACT_MICRO_VERSION 0
#define TESSERACT_VERSION \
(TESSERACT_MAJOR_VERSION << 16 | \
TESSERACT_MINOR_VERSION << 8 | \
TESSERACT_MICRO_VERSION)
#define TESSERACT_VERSION_STR "4.0.0"
#endif // TESSERACT_API_VERSION_H_
File diff suppressed because it is too large. Load diff
+43 -44
View File
@@ -17,10 +17,12 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_THRESHOLDER_H__
#define TESSERACT_CCMAIN_THRESHOLDER_H__
#ifndef TESSERACT_CCMAIN_THRESHOLDER_H_
#define TESSERACT_CCMAIN_THRESHOLDER_H_
#include "platform.h"
#include "publictypes.h"
class IMAGE;
struct Pix;
namespace tesseract {
@@ -31,7 +33,7 @@ namespace tesseract {
/// Each instance deals with a single image, but the design is intended to
/// be useful for multiple calls to SetRectangle and ThresholdTo* if
/// desired.
class ImageThresholder {
class TESS_API ImageThresholder {
public:
ImageThresholder();
virtual ~ImageThresholder();
@@ -42,10 +44,8 @@ class ImageThresholder {
/// Return true if no image has been set.
bool IsEmpty() const;
/// SetImage makes a copy of only the metadata, not the underlying
/// image buffer. It promises to treat the source as read-only in either case,
/// but in return assumes that the Pix or image buffer remain valid
/// throughout the life of the ImageThresholder.
/// SetImage makes a copy of all the image data, so it may be deleted
/// immediately after this call.
/// Greyscale of 8 and color of 24 or 32 bits per pixel may be given.
/// Palette color images will not work properly and must be converted to
/// 24 bit.
@@ -68,12 +68,12 @@ class ImageThresholder {
/// Return true if the source image is color.
bool IsColor() const {
return image_bytespp_ >= 3;
return pix_channels_ >= 3;
}
/// Returns true if the source image is binary.
bool IsBinary() const {
return image_bytespp_ == 0;
return pix_channels_ == 0;
}
int GetScaleFactor() const {
@@ -107,20 +107,27 @@ class ImageThresholder {
return scale_ * estimated_res_;
}
/// Pix vs raw, which to use?
/// Implementations should provide the ability to source and target Pix
/// where possible. A future version of Tesseract may choose to use Pix
/// as its internal representation and discard IMAGE altogether.
/// Because of that, an implementation that sources and targets Pix may end up
/// with less copies than an implementation that does not.
/// NOTE: Opposite to SetImage for raw images, SetImage for Pix clones its
/// input, so the source pix may be pixDestroyed immediately after.
/// Pix vs raw, which to use? Pix is the preferred input for efficiency,
/// since raw buffers are copied.
/// SetImage for Pix clones its input, so the source pix may be pixDestroyed
/// immediately after, but may not go away until after the Thresholder has
/// finished with it.
void SetImage(const Pix* pix);
/// Threshold the source image as efficiently as possible to the output Pix.
/// Creates a Pix and sets pix to point to the resulting pointer.
/// Caller must use pixDestroy to free the created Pix.
virtual void ThresholdToPix(Pix** pix);
/// Returns false on error.
virtual bool ThresholdToPix(PageSegMode pageseg_mode, Pix** pix);
// Gets a pix that contains an 8 bit threshold value at each pixel. The
// returned pix may be an integer reduction of the binary image such that
// the scale factor may be inferred from the ratio of the sizes, even down
// to the extreme of a 1x1 pixel thresholds image.
// Ideally the 8 bit threshold should be the exact threshold used to generate
// the binary image in ThresholdToPix, but this is not a hard constraint.
// Returns nullptr if the input is binary. PixDestroy after use.
virtual Pix* GetPixRectThresholds();
/// Get a clone/copy of the source image rectangle.
/// The returned Pix must be pixDestroyed.
@@ -129,12 +136,11 @@ class ImageThresholder {
/// so there is no raw equivalent.
Pix* GetPixRect();
/// Get a clone/copy of the source image rectangle, reduced to greyscale.
/// The returned Pix must be pixDestroyed.
/// This function will be used in the future by the page layout analysis, and
/// the layout analysis that uses it will only be available with Leptonica,
/// so there is no raw equivalent.
Pix* GetPixRectGrey();
// Get a clone/copy of the source image rectangle, reduced to greyscale,
// and at the same resolution as the output binary.
// The returned Pix must be pixDestroyed.
// Provided to the classifier to extract features from the greyscale image.
virtual Pix* GetPixRectGrey();
protected:
// ----------------------------------------------------------------------
@@ -149,33 +155,26 @@ class ImageThresholder {
rect_width_ == image_width_ && rect_height_ == image_height_;
}
/// Otsu threshold the rectangle, taking everything except the image buffer
/// pointer from the class, to the output Pix.
void OtsuThresholdRectToPix(const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
Pix** pix) const;
// Otsu thresholds the rectangle, taking the rectangle from *this.
void OtsuThresholdRectToPix(Pix* src_pix, Pix** out_pix) const;
/// Threshold the rectangle, taking everything except the image buffer pointer
/// from the class, using thresholds/hi_values to the output IMAGE.
void ThresholdRectToPix(const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
/// Threshold the rectangle, taking everything except the src_pix
/// from the class, using thresholds/hi_values to the output pix.
/// NOTE that num_channels is the size of the thresholds and hi_values
// arrays and also the bytes per pixel in src_pix.
void ThresholdRectToPix(Pix* src_pix, int num_channels,
const int* thresholds, const int* hi_values,
Pix** pix) const;
/// Copy the raw image rectangle, taking all data from the class, to the Pix.
void RawRectToPix(Pix** pix) const;
protected:
/// Clone or other copy of the source Pix.
/// The pix will always be PixDestroy()ed on destruction of the class.
Pix* pix_;
/// Exactly one of pix_ and image_data_ is not NULL.
const unsigned char* image_data_; //< Raw source image.
int image_width_; //< Width of source image/pix.
int image_height_; //< Height of source image/pix.
int image_bytespp_; //< Bytes per pixel of source image/pix.
int image_bytespl_; //< Bytes per line of source image/pix.
int image_width_; //< Width of source pix_.
int image_height_; //< Height of source pix_.
int pix_channels_; //< Number of 8-bit channels in pix_.
int pix_wpl_; //< Words per line of pix_.
// Limits of image rectangle to be processed.
int scale_; //< Scale factor from original image.
int yres_; //< y pixels/inch in source image.
@@ -188,4 +187,4 @@ class ImageThresholder {
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_THRESHOLDER_H__
#endif // TESSERACT_CCMAIN_THRESHOLDER_H_
+89 -7
View File
@@ -17,18 +17,22 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_UNICHAR_H__
#define TESSERACT_CCUTIL_UNICHAR_H__
#ifndef TESSERACT_CCUTIL_UNICHAR_H_
#define TESSERACT_CCUTIL_UNICHAR_H_
#include <memory.h>
#include <string.h>
#include <cstring>
#include <string>
#include <vector>
#include "platform.h"
// Maximum number of characters that can be stored in a UNICHAR. Must be
// at least 4. Must not exceed 31 without changing the coding of length.
#define UNICHAR_LEN 30
// TODO(rays) Move these to the tesseract namespace.
// A UNICHAR_ID is the unique id of a unichar.
typedef int UNICHAR_ID;
using UNICHAR_ID = int;
// A variable to indicate an invalid or uninitialized unichar id.
static const int INVALID_UNICHAR_ID = -1;
@@ -43,9 +47,13 @@ enum StrongScriptDirection {
// and right-to-left characters.
};
namespace tesseract {
using char32 = signed int;
// The UNICHAR class holds a single classification result. This may be
// a single Unicode character (stored as between 1 and 4 utf8 bytes) or
// multple Unicode characters representing the NFKC expansion of a ligature
// multiple Unicode characters representing the NFKC expansion of a ligature
// such as fi, ffl etc. These are also stored as utf8.
class UNICHAR {
public:
@@ -72,7 +80,7 @@ class UNICHAR {
return len >=0 && len < UNICHAR_LEN ? len : UNICHAR_LEN;
}
// Get a UTF8 string, but NOT NULL terminated.
// Get a UTF8 string, but NOT nullptr terminated.
const char* utf8() const {
return chars;
}
@@ -83,6 +91,78 @@ class UNICHAR {
// Get the number of bytes in the first character of the given utf8 string.
static int utf8_step(const char* utf8_str);
// A class to simplify iterating over and accessing elements of a UTF8
// string. Note that unlike the UNICHAR class, const_iterator does NOT COPY or
// take ownership of the underlying byte array. It also does not permit
// modification of the array (as the name suggests).
//
// Example:
// for (UNICHAR::const_iterator it = UNICHAR::begin(str, str_len);
// it != UNICHAR::end(str, len);
// ++it) {
// tprintf("UCS-4 symbol code = %d\n", *it);
// char buf[5];
// int char_len = it.get_utf8(buf); buf[char_len] = '\0';
// tprintf("Char = %s\n", buf);
// }
class const_iterator {
using CI = const_iterator ;
public:
// Step to the next UTF8 character.
// If the current position is at an illegal UTF8 character, then print an
// error message and step by one byte. If the current position is at a nullptr
// value, don't step past it.
const_iterator& operator++();
// Return the UCS-4 value at the current position.
// If the current position is at an illegal UTF8 value, return a single
// space character.
int operator*() const;
// Store the UTF-8 encoding of the current codepoint into buf, which must be
// at least 4 bytes long. Return the number of bytes written.
// If the current position is at an illegal UTF8 value, writes a single
// space character and returns 1.
// Note that this method does not null-terminate the buffer.
int get_utf8(char* buf) const;
// Returns the number of bytes of the current codepoint. Returns 1 if the
// current position is at an illegal UTF8 value.
int utf8_len() const;
// Returns true if the UTF-8 encoding at the current position is legal.
bool is_legal() const;
// Return the pointer into the string at the current position.
const char* utf8_data() const { return it_; }
// Iterator equality operators.
friend bool operator==(const CI& lhs, const CI& rhs) {
return lhs.it_ == rhs.it_;
}
friend bool operator!=(const CI& lhs, const CI& rhs) {
return !(lhs == rhs);
}
private:
friend class UNICHAR;
explicit const_iterator(const char* it) : it_(it) {}
const char* it_; // Pointer into the string.
};
// Create a start/end iterator pointing to a string. Note that these methods
// are static and do NOT create a copy or take ownership of the underlying
// array.
static const_iterator begin(const char* utf8_str, const int byte_length);
static const_iterator end(const char* utf8_str, const int byte_length);
// Converts a utf-8 string to a vector of unicodes.
// Returns an empty vector if the input contains invalid UTF-8.
static std::vector<char32> UTF8ToUTF32(const char* utf8_str);
// Converts a vector of unicodes to a utf8 string.
// Returns an empty string if the input contains an invalid unicode.
static std::string UTF32ToUTF8(const std::vector<char32>& str32);
private:
// A UTF-8 representation of 1 or more Unicode characters.
// The last element (chars[UNICHAR_LEN - 1]) is a length if
@@ -90,4 +170,6 @@ class UNICHAR {
char chars[UNICHAR_LEN];
};
#endif // TESSERACT_CCUTIL_UNICHAR_H__
} // namespace tesseract
#endif // TESSERACT_CCUTIL_UNICHAR_H_
-82
View File
@@ -1,82 +0,0 @@
///////////////////////////////////////////////////////////////////////
// File: unicharmap.h
// Description: Unicode character/ligature to integer id class.
// Author: Thomas Kielbus
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_UNICHARMAP_H__
#define TESSERACT_CCUTIL_UNICHARMAP_H__
#include "unichar.h"
// A UNICHARMAP stores unique unichars. Each of them is associated with one
// UNICHAR_ID.
class UNICHARMAP {
public:
// Create an empty UNICHARMAP
UNICHARMAP();
~UNICHARMAP();
// Insert the given unichar represention in the UNICHARMAP and associate it
// with the given id. The length of the representation MUST be non-zero.
void insert(const char* const unichar_repr, UNICHAR_ID id);
// Return the id associated with the given unichar representation,
// this representation MUST exist within the UNICHARMAP.
// The length of the representation MUST be non-zero.
UNICHAR_ID unichar_to_id(const char* const unichar_repr) const;
// Return the id associated with the given unichar representation,
// this representation MUST exist within the UNICHARMAP. The first
// length characters (maximum) from unichar_repr are used. The length
// MUST be non-zero.
UNICHAR_ID unichar_to_id(const char* const unichar_repr, int length) const;
// Return true if the given unichar representation is already present in the
// UNICHARMAP. The length of the representation MUST be non-zero.
bool contains(const char* const unichar_repr) const;
// Return true if the given unichar representation is already present in the
// UNICHARMAP. The first length characters (maximum) from unichar_repr are
// used. The length MUST be non-zero.
bool contains(const char* const unichar_repr, int length) const;
// Return the minimum number of characters that must be used from this string
// to obtain a match in the UNICHARMAP.
int minmatch(const char* const unichar_repr) const;
// Clear the UNICHARMAP. All previous data is lost.
void clear();
private:
// The UNICHARMAP is represented as a tree whose nodes are of type
// UNICHARMAP_NODE.
struct UNICHARMAP_NODE {
UNICHARMAP_NODE();
~UNICHARMAP_NODE();
UNICHARMAP_NODE* children;
UNICHAR_ID id;
};
UNICHARMAP_NODE* nodes;
};
#endif // TESSERACT_CCUTIL_UNICHARMAP_H__
-884
View File
@@ -1,884 +0,0 @@
///////////////////////////////////////////////////////////////////////
// File: unicharset.h
// Description: Unicode character/ligature set class.
// Author: Thomas Kielbus
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_UNICHARSET_H__
#define TESSERACT_CCUTIL_UNICHARSET_H__
#include "errcode.h"
#include "helpers.h"
#include "strngs.h"
#include "tesscallback.h"
#include "unichar.h"
#include "unicharmap.h"
class CHAR_FRAGMENT {
public:
// Minimum number of characters used for fragment representation.
static const int kMinLen = 6;
// Maximum number of characters used for fragment representation.
static const int kMaxLen = 3 + UNICHAR_LEN + 2;
// Maximum number of fragments per character.
static const int kMaxChunks = 5;
// Setters and Getters.
inline void set_all(const char *unichar, int pos, int total, bool natural) {
set_unichar(unichar);
set_pos(pos);
set_total(total);
set_natural(natural);
}
inline void set_unichar(const char *uch) {
strncpy(this->unichar, uch, UNICHAR_LEN);
this->unichar[UNICHAR_LEN] = '\0';
}
inline void set_pos(int p) { this->pos = p; }
inline void set_total(int t) { this->total = t; }
inline const char* get_unichar() const { return this->unichar; }
inline int get_pos() const { return this->pos; }
inline int get_total() const { return this->total; }
// Returns the string that represents a fragment
// with the given unichar, pos and total.
static STRING to_string(const char *unichar, int pos, int total,
bool natural);
// Returns the string that represents this fragment.
STRING to_string() const {
return to_string(unichar, pos, total, natural);
}
// Checks whether a fragment has the same unichar,
// position and total as the given inputs.
inline bool equals(const char *other_unichar,
int other_pos, int other_total) const {
return (strcmp(this->unichar, other_unichar) == 0 &&
this->pos == other_pos && this->total == other_total);
}
inline bool equals(const CHAR_FRAGMENT *other) const {
return this->equals(other->get_unichar(),
other->get_pos(),
other->get_total());
}
// Checks whether a given fragment is a continuation of this fragment.
// Assumes that the given fragment pointer is not NULL.
inline bool is_continuation_of(const CHAR_FRAGMENT *fragment) const {
return (strcmp(this->unichar, fragment->get_unichar()) == 0 &&
this->total == fragment->get_total() &&
this->pos == fragment->get_pos() + 1);
}
// Returns true if this fragment is a beginning fragment.
inline bool is_beginning() const { return this->pos == 0; }
// Returns true if this fragment is an ending fragment.
inline bool is_ending() const { return this->pos == this->total-1; }
// Returns true if the fragment was a separate component to begin with,
// ie did not need chopping to be isolated, but may have been separated
// out from a multi-outline blob.
inline bool is_natural() const { return natural; }
void set_natural(bool value) { natural = value; }
// Parses the string to see whether it represents a character fragment
// (rather than a regular character). If so, allocates memory for a new
// CHAR_FRAGMENT instance and fills it in with the corresponding fragment
// information. Fragments are of the form:
// |m|1|2, meaning chunk 1 of 2 of character m, or
// |:|1n2, meaning chunk 1 of 2 of character :, and no chopping was needed
// to divide the parts, as they were already separate connected components.
//
// If parsing succeeded returns the pointer to the allocated CHAR_FRAGMENT
// instance, otherwise (if the string does not represent a fragment or it
// looks like it does, but parsing it as a fragment fails) returns NULL.
//
// Note: The caller is responsible for deallocating memory
// associated with the returned pointer.
static CHAR_FRAGMENT *parse_from_string(const char *str);
private:
char unichar[UNICHAR_LEN + 1];
// True if the fragment was a separate component to begin with,
// ie did not need chopping to be isolated, but may have been separated
// out from a multi-outline blob.
bool natural;
inT16 pos; // fragment position in the character
inT16 total; // total number of fragments in the character
};
// The UNICHARSET class is an utility class for Tesseract that holds the
// set of characters that are used by the engine. Each character is identified
// by a unique number, from 0 to (size - 1).
class UNICHARSET {
public:
// Custom list of characters and their ligature forms (UTF8)
// These map to unicode values in the private use area (PUC) and are supported
// by only few font families (eg. Wyld, Adobe Caslon Pro).
static const char* kCustomLigatures[][2];
// ICU 2.0 UCharDirection enum (from third_party/icu/include/unicode/uchar.h)
enum Direction {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_CHAR_DIRECTION_COUNT
};
// Create an empty UNICHARSET
UNICHARSET();
~UNICHARSET();
// Return the UNICHAR_ID of a given unichar representation within the
// UNICHARSET.
const UNICHAR_ID unichar_to_id(const char* const unichar_repr) const;
// Return the UNICHAR_ID of a given unichar representation within the
// UNICHARSET. Only the first length characters from unichar_repr are used.
const UNICHAR_ID unichar_to_id(const char* const unichar_repr,
int length) const;
// Return the minimum number of bytes that matches a legal UNICHAR_ID,
// while leaving a legal UNICHAR_ID afterwards. In other words, if there
// is both a short and a long match to the string, return the length that
// ensures there is a legal match after it.
int step(const char* str) const;
// Return whether the given UTF-8 string is encodable with this UNICHARSET.
// If not encodable, write the first byte offset which cannot be converted
// into the second (return) argument.
bool encodable_string(const char *str, int *first_bad_position) const;
// Return the unichar representation corresponding to the given UNICHAR_ID
// within the UNICHARSET.
const char* const id_to_unichar(UNICHAR_ID id) const;
// Return the UTF8 representation corresponding to the given UNICHAR_ID after
// resolving any private encodings internal to Tesseract. This method is
// preferrable to id_to_unichar for outputting text that will be visible to
// external applications.
const char* const id_to_unichar_ext(UNICHAR_ID id) const;
// Return a STRING that reformats the utf8 str into the str followed
// by its hex unicodes.
static STRING debug_utf8_str(const char* str);
// Return a STRING containing debug information on the unichar, including
// the id_to_unichar, its hex unicodes and the properties.
STRING debug_str(UNICHAR_ID id) const;
STRING debug_str(const char * unichar_repr) const {
return debug_str(unichar_to_id(unichar_repr));
}
// Add a unichar representation to the set.
void unichar_insert(const char* const unichar_repr);
// Return true if the given unichar id exists within the set.
// Relies on the fact that unichar ids are contiguous in the unicharset.
bool contains_unichar_id(UNICHAR_ID unichar_id) const {
return unichar_id != INVALID_UNICHAR_ID && unichar_id < size_used &&
unichar_id >= 0;
}
// Return true if the given unichar representation exists within the set.
bool contains_unichar(const char* const unichar_repr) const;
bool contains_unichar(const char* const unichar_repr, int length) const;
// Return true if the given unichar representation corresponds to the given
// UNICHAR_ID within the set.
bool eq(UNICHAR_ID unichar_id, const char* const unichar_repr) const;
// Delete CHAR_FRAGMENTs stored in properties of unichars array.
void delete_pointers_in_unichars() {
for (int i = 0; i < size_used; ++i) {
if (unichars[i].properties.fragment != NULL) {
delete unichars[i].properties.fragment;
unichars[i].properties.fragment = NULL;
}
}
}
// Clear the UNICHARSET (all the previous data is lost).
void clear() {
if (script_table != NULL) {
for (int i = 0; i < script_table_size_used; ++i)
delete[] script_table[i];
delete[] script_table;
script_table = NULL;
script_table_size_used = 0;
}
if (unichars != NULL) {
delete_pointers_in_unichars();
delete[] unichars;
unichars = NULL;
}
script_table_size_reserved = 0;
size_reserved = 0;
size_used = 0;
ids.clear();
top_bottom_set_ = false;
script_has_upper_lower_ = false;
script_has_xheight_ = false;
null_sid_ = 0;
common_sid_ = 0;
latin_sid_ = 0;
cyrillic_sid_ = 0;
greek_sid_ = 0;
han_sid_ = 0;
hiragana_sid_ = 0;
katakana_sid_ = 0;
}
// Return the size of the set (the number of different UNICHAR it holds).
int size() const {
return size_used;
}
// Reserve enough memory space for the given number of UNICHARS
void reserve(int unichars_number);
// Opens the file indicated by filename and saves unicharset to that file.
// Returns true if the operation is successful.
bool save_to_file(const char * const filename) const {
FILE* file = fopen(filename, "w+b");
if (file == NULL) return false;
bool result = save_to_file(file);
fclose(file);
return result;
}
// Saves the content of the UNICHARSET to the given file.
// Returns true if the operation is successful.
bool save_to_file(FILE *file) const;
// Load a unicharset from a unicharset file that has been loaded into
// the given memory buffer.
// Returns true if the operation is successful.
bool load_from_inmemory_file(const char* const memory, int mem_size,
bool skip_fragments);
// Returns true if the operation is successful.
bool load_from_inmemory_file(const char* const memory, int mem_size) {
return load_from_inmemory_file(memory, mem_size, false);
}
// Opens the file indicated by filename and loads the UNICHARSET
// from the given file. The previous data is lost.
// Returns true if the operation is successful.
bool load_from_file(const char* const filename, bool skip_fragments) {
FILE* file = fopen(filename, "rb");
if (file == NULL) return false;
bool result = load_from_file(file, skip_fragments);
fclose(file);
return result;
}
// returns true if the operation is successful.
bool load_from_file(const char* const filename) {
return load_from_file(filename, false);
}
// Loads the UNICHARSET from the given file. The previous data is lost.
// Returns true if the operation is successful.
bool load_from_file(FILE *file, bool skip_fragments);
bool load_from_file(FILE *file) { return load_from_file(file, false); }
// Sets up internal data after loading the file, based on the char
// properties. Called from load_from_file, but also needs to be run
// during set_unicharset_properties.
void post_load_setup();
// Returns true if right_to_left scripts are significant in the unicharset,
// but without being so sensitive that "universal" unicharsets containing
// characters from many scripts, like orientation and script detection,
// look like they are right_to_left.
bool major_right_to_left() const;
// Set a whitelist and/or blacklist of characters to recognize.
// An empty or NULL whitelist enables everything (minus any blacklist).
// An empty or NULL blacklist disables nothing.
// The blacklist overrides the whitelist.
// Each list is a string of utf8 character strings. Boundaries between
// unicharset units are worked out automatically, and characters not in
// the unicharset are silently ignored.
void set_black_and_whitelist(const char* blacklist, const char* whitelist);
// Set the isalpha property of the given unichar to the given value.
void set_isalpha(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.isalpha = value;
}
// Set the islower property of the given unichar to the given value.
void set_islower(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.islower = value;
}
// Set the isupper property of the given unichar to the given value.
void set_isupper(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.isupper = value;
}
// Set the isdigit property of the given unichar to the given value.
void set_isdigit(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.isdigit = value;
}
// Set the ispunctuation property of the given unichar to the given value.
void set_ispunctuation(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.ispunctuation = value;
}
// Set the isngram property of the given unichar to the given value.
void set_isngram(UNICHAR_ID unichar_id, bool value) {
unichars[unichar_id].properties.isngram = value;
}
// Set the script name of the given unichar to the given value.
// Value is copied and thus can be a temporary;
void set_script(UNICHAR_ID unichar_id, const char* value) {
unichars[unichar_id].properties.script_id = add_script(value);
}
// Set other_case unichar id in the properties for the given unichar id.
void set_other_case(UNICHAR_ID unichar_id, UNICHAR_ID other_case) {
unichars[unichar_id].properties.other_case = other_case;
}
// Set the direction property of the given unichar to the given value.
void set_direction(UNICHAR_ID unichar_id, UNICHARSET::Direction value) {
unichars[unichar_id].properties.direction = value;
}
// Set mirror unichar id in the properties for the given unichar id.
void set_mirror(UNICHAR_ID unichar_id, UNICHAR_ID mirror) {
unichars[unichar_id].properties.mirror = mirror;
}
// Record normalized version of unichar with the given unichar_id.
void set_normed(UNICHAR_ID unichar_id, const char* normed) {
unichars[unichar_id].properties.normed = normed;
}
// Return the isalpha property of the given unichar.
bool get_isalpha(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.isalpha;
}
// Return the islower property of the given unichar.
bool get_islower(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.islower;
}
// Return the isupper property of the given unichar.
bool get_isupper(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.isupper;
}
// Return the isdigit property of the given unichar.
bool get_isdigit(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.isdigit;
}
// Return the ispunctuation property of the given unichar.
bool get_ispunctuation(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.ispunctuation;
}
// Return the isngram property of the given unichar.
bool get_isngram(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return false;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.isngram;
}
// Returns whether the unichar id represents a unicode value in the private
// use area.
bool get_isprivate(UNICHAR_ID unichar_id) const;
// Returns true if the ids have useful min/max top/bottom values.
bool top_bottom_useful() const {
return top_bottom_set_;
}
// Sets all ranges to empty, so they can be expanded to set the values.
void set_ranges_empty();
// Sets all the properties for this unicharset given a src_unicharset with
// everything set. The unicharsets don't have to be the same, and graphemes
// are correctly accounted for.
void SetPropertiesFromOther(const UNICHARSET& src);
// Expands the tops and bottoms and widths for this unicharset given a
// src_unicharset with ranges in it. The unicharsets don't have to be the
// same, and graphemes are correctly accounted for.
void ExpandRangesFromOther(const UNICHARSET& src);
// For each id in src, if it does not occur in this, add it, as in
// SetPropertiesFromOther, otherwise expand the ranges, as in
// ExpandRangesFromOther.
void AppendOtherUnicharset(const UNICHARSET& src);
// Returns the min and max bottom and top of the given unichar in
// baseline-normalized coordinates, ie, where the baseline is
// kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight
// (See normalis.h for the definitions).
void get_top_bottom(UNICHAR_ID unichar_id,
int* min_bottom, int* max_bottom,
int* min_top, int* max_top) const {
if (INVALID_UNICHAR_ID == unichar_id) {
*min_bottom = *min_top = 0;
*max_bottom = *max_top = 256; // kBlnCellHeight
return;
}
ASSERT_HOST(contains_unichar_id(unichar_id));
*min_bottom = unichars[unichar_id].properties.min_bottom;
*max_bottom = unichars[unichar_id].properties.max_bottom;
*min_top = unichars[unichar_id].properties.min_top;
*max_top = unichars[unichar_id].properties.max_top;
}
void set_top_bottom(UNICHAR_ID unichar_id,
int min_bottom, int max_bottom,
int min_top, int max_top) {
unichars[unichar_id].properties.min_bottom =
static_cast<uinT8>(ClipToRange(min_bottom, 0, MAX_UINT8));
unichars[unichar_id].properties.max_bottom =
static_cast<uinT8>(ClipToRange(max_bottom, 0, MAX_UINT8));
unichars[unichar_id].properties.min_top =
static_cast<uinT8>(ClipToRange(min_top, 0, MAX_UINT8));
unichars[unichar_id].properties.max_top =
static_cast<uinT8>(ClipToRange(max_top, 0, MAX_UINT8));
}
// Returns the width range of the given unichar in baseline-normalized
// coordinates, ie, where the baseline is kBlnBaselineOffset and the
// meanline is kBlnBaselineOffset + kBlnXHeight.
// (See normalis.h for the definitions).
void get_width_range(UNICHAR_ID unichar_id,
int* min_width, int* max_width) const {
if (INVALID_UNICHAR_ID == unichar_id) {
*min_width = 0;
*max_width = 256; // kBlnCellHeight;
return;
}
ASSERT_HOST(contains_unichar_id(unichar_id));
*min_width = unichars[unichar_id].properties.min_width;
*max_width = unichars[unichar_id].properties.max_width;
}
void set_width_range(UNICHAR_ID unichar_id, int min_width, int max_width) {
unichars[unichar_id].properties.min_width =
static_cast<inT16>(ClipToRange(min_width, 0, MAX_INT16));
unichars[unichar_id].properties.max_width =
static_cast<inT16>(ClipToRange(max_width, 0, MAX_INT16));
}
// Returns the range of the x-bearing of the given unichar in
// baseline-normalized coordinates, ie, where the baseline is
// kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight.
// (See normalis.h for the definitions).
void get_bearing_range(UNICHAR_ID unichar_id,
int* min_bearing, int* max_bearing) const {
if (INVALID_UNICHAR_ID == unichar_id) {
*min_bearing = *max_bearing = 0;
return;
}
ASSERT_HOST(contains_unichar_id(unichar_id));
*min_bearing = unichars[unichar_id].properties.min_bearing;
*max_bearing = unichars[unichar_id].properties.max_bearing;
}
void set_bearing_range(UNICHAR_ID unichar_id,
int min_bearing, int max_bearing) {
unichars[unichar_id].properties.min_bearing =
static_cast<inT16>(ClipToRange(min_bearing, 0, MAX_INT16));
unichars[unichar_id].properties.max_bearing =
static_cast<inT16>(ClipToRange(max_bearing, 0, MAX_INT16));
}
// Returns the range of the x-advance of the given unichar in
// baseline-normalized coordinates, ie, where the baseline is
// kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight.
// (See normalis.h for the definitions).
void get_advance_range(UNICHAR_ID unichar_id,
int* min_advance, int* max_advance) const {
if (INVALID_UNICHAR_ID == unichar_id) {
*min_advance = *max_advance = 0;
return;
}
ASSERT_HOST(contains_unichar_id(unichar_id));
*min_advance = unichars[unichar_id].properties.min_advance;
*max_advance = unichars[unichar_id].properties.max_advance;
}
void set_advance_range(UNICHAR_ID unichar_id,
int min_advance, int max_advance) {
unichars[unichar_id].properties.min_advance =
static_cast<inT16>(ClipToRange(min_advance, 0, MAX_INT16));
unichars[unichar_id].properties.max_advance =
static_cast<inT16>(ClipToRange(max_advance, 0, MAX_INT16));
}
// Return the script name of the given unichar.
// The returned pointer will always be the same for the same script, it's
// managed by unicharset and thus MUST NOT be deleted
int get_script(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return null_sid_;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.script_id;
}
// Return the character properties, eg. alpha/upper/lower/digit/punct,
// as a bit field of unsigned int.
unsigned int get_properties(UNICHAR_ID unichar_id) const;
// Return the character property as a single char. If a character has
// multiple attributes, the main property is defined by the following order:
// upper_case : 'A'
// lower_case : 'a'
// alpha : 'x'
// digit : '0'
// punctuation: 'p'
char get_chartype(UNICHAR_ID unichar_id) const;
// Get other_case unichar id in the properties for the given unichar id.
UNICHAR_ID get_other_case(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.other_case;
}
// Returns the direction property of the given unichar.
Direction get_direction(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return UNICHARSET::U_OTHER_NEUTRAL;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.direction;
}
// Get mirror unichar id in the properties for the given unichar id.
UNICHAR_ID get_mirror(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.mirror;
}
// Returns UNICHAR_ID of the corresponding lower-case unichar.
UNICHAR_ID to_lower(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID;
ASSERT_HOST(contains_unichar_id(unichar_id));
if (unichars[unichar_id].properties.islower) return unichar_id;
return unichars[unichar_id].properties.other_case;
}
// Returns UNICHAR_ID of the corresponding upper-case unichar.
UNICHAR_ID to_upper(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID;
ASSERT_HOST(contains_unichar_id(unichar_id));
if (unichars[unichar_id].properties.isupper) return unichar_id;
return unichars[unichar_id].properties.other_case;
}
// Return a pointer to the CHAR_FRAGMENT class if the given
// unichar id represents a character fragment.
const CHAR_FRAGMENT *get_fragment(UNICHAR_ID unichar_id) const {
if (INVALID_UNICHAR_ID == unichar_id) return NULL;
ASSERT_HOST(contains_unichar_id(unichar_id));
return unichars[unichar_id].properties.fragment;
}
// Return the isalpha property of the given unichar representation.
bool get_isalpha(const char* const unichar_repr) const {
return get_isalpha(unichar_to_id(unichar_repr));
}
// Return the islower property of the given unichar representation.
bool get_islower(const char* const unichar_repr) const {
return get_islower(unichar_to_id(unichar_repr));
}
// Return the isupper property of the given unichar representation.
bool get_isupper(const char* const unichar_repr) const {
return get_isupper(unichar_to_id(unichar_repr));
}
// Return the isdigit property of the given unichar representation.
bool get_isdigit(const char* const unichar_repr) const {
return get_isdigit(unichar_to_id(unichar_repr));
}
// Return the ispunctuation property of the given unichar representation.
bool get_ispunctuation(const char* const unichar_repr) const {
return get_ispunctuation(unichar_to_id(unichar_repr));
}
// Return the character properties, eg. alpha/upper/lower/digit/punct,
// of the given unichar representation
unsigned int get_properties(const char* const unichar_repr) const {
return get_properties(unichar_to_id(unichar_repr));
}
char get_chartype(const char* const unichar_repr) const {
return get_chartype(unichar_to_id(unichar_repr));
}
// Return the script name of the given unichar representation.
// The returned pointer will always be the same for the same script, it's
// managed by unicharset and thus MUST NOT be deleted
int get_script(const char* const unichar_repr) const {
return get_script(unichar_to_id(unichar_repr));
}
// Return a pointer to the CHAR_FRAGMENT class struct if the given
// unichar representation represents a character fragment.
const CHAR_FRAGMENT *get_fragment(const char* const unichar_repr) const {
if (unichar_repr == NULL || unichar_repr[0] == '\0' ||
!ids.contains(unichar_repr)) {
return NULL;
}
return get_fragment(unichar_to_id(unichar_repr));
}
// Return the isalpha property of the given unichar representation.
// Only the first length characters from unichar_repr are used.
bool get_isalpha(const char* const unichar_repr,
int length) const {
return get_isalpha(unichar_to_id(unichar_repr, length));
}
// Return the islower property of the given unichar representation.
// Only the first length characters from unichar_repr are used.
bool get_islower(const char* const unichar_repr,
int length) const {
return get_islower(unichar_to_id(unichar_repr, length));
}
// Return the isupper property of the given unichar representation.
// Only the first length characters from unichar_repr are used.
bool get_isupper(const char* const unichar_repr,
int length) const {
return get_isupper(unichar_to_id(unichar_repr, length));
}
// Return the isdigit property of the given unichar representation.
// Only the first length characters from unichar_repr are used.
bool get_isdigit(const char* const unichar_repr,
int length) const {
return get_isdigit(unichar_to_id(unichar_repr, length));
}
// Return the ispunctuation property of the given unichar representation.
// Only the first length characters from unichar_repr are used.
bool get_ispunctuation(const char* const unichar_repr,
int length) const {
return get_ispunctuation(unichar_to_id(unichar_repr, length));
}
// Returns normalized version of unichar with the given unichar_id.
const char *get_normed_unichar(UNICHAR_ID unichar_id) const {
return unichars[unichar_id].properties.normed.string();
}
// Return the script name of the given unichar representation.
// Only the first length characters from unichar_repr are used.
// The returned pointer will always be the same for the same script, it's
// managed by unicharset and thus MUST NOT be deleted
int get_script(const char* const unichar_repr,
int length) const {
return get_script(unichar_to_id(unichar_repr, length));
}
// Return the (current) number of scripts in the script table
int get_script_table_size() const {
return script_table_size_used;
}
// Return the script string from its id
const char* get_script_from_script_id(int id) const {
if (id >= script_table_size_used || id < 0)
return null_script;
return script_table[id];
}
// Returns the id from the name of the script, or 0 if script is not found.
// Note that this is an expensive operation since it involves iteratively
// comparing strings in the script table. To avoid dependency on STL, we
// won't use a hash. Instead, the calling function can use this to lookup
// and save the ID for relevant scripts for fast comparisons later.
int get_script_id_from_name(const char* script_name) const;
// Return true if the given script is the null script
bool is_null_script(const char* script) const {
return script == null_script;
}
// Uniquify the given script. For two scripts a and b, if strcmp(a, b) == 0,
// then the returned pointer will be the same.
// The script parameter is copied and thus can be a temporary.
int add_script(const char* script);
// Return the enabled property of the given unichar.
bool get_enabled(UNICHAR_ID unichar_id) const {
return unichars[unichar_id].properties.enabled;
}
int null_sid() const { return null_sid_; }
int common_sid() const { return common_sid_; }
int latin_sid() const { return latin_sid_; }
int cyrillic_sid() const { return cyrillic_sid_; }
int greek_sid() const { return greek_sid_; }
int han_sid() const { return han_sid_; }
int hiragana_sid() const { return hiragana_sid_; }
int katakana_sid() const { return katakana_sid_; }
int default_sid() const { return default_sid_; }
// Returns true if the unicharset has the concept of upper/lower case.
bool script_has_upper_lower() const {
return script_has_upper_lower_;
}
// Returns true if the unicharset has the concept of x-height.
// script_has_xheight can be true even if script_has_upper_lower is not,
// when the script has a sufficiently predominant top line with ascenders,
// such as Devanagari and Thai.
bool script_has_xheight() const {
return script_has_xheight_;
}
private:
struct UNICHAR_PROPERTIES {
UNICHAR_PROPERTIES();
// Initializes all properties to sensible default values.
void Init();
// Sets all ranges wide open. Initialization default in case there are
// no useful values available.
void SetRangesOpen();
// Sets all ranges to empty. Used before expanding with font-based data.
void SetRangesEmpty();
// Returns true if any of the top/bottom/width/bearing/advance ranges is
// emtpy.
bool AnyRangeEmpty() const;
// Expands the ranges with the ranges from the src properties.
void ExpandRangesFrom(const UNICHAR_PROPERTIES& src);
// Copies the properties from src into this.
void CopyFrom(const UNICHAR_PROPERTIES& src);
bool isalpha;
bool islower;
bool isupper;
bool isdigit;
bool ispunctuation;
bool isngram;
bool enabled;
// Possible limits of the top and bottom of the bounding box in
// baseline-normalized coordinates, ie, where the baseline is
// kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight
// (See normalis.h for the definitions).
uinT8 min_bottom;
uinT8 max_bottom;
uinT8 min_top;
uinT8 max_top;
// Limits on the widths of bounding box, also in baseline-normalized coords.
inT16 min_width;
inT16 max_width;
// Limits on the x-bearing and advance, also in baseline-normalized coords.
inT16 min_bearing;
inT16 max_bearing;
inT16 min_advance;
inT16 max_advance;
int script_id;
UNICHAR_ID other_case; // id of the corresponding upper/lower case unichar
Direction direction; // direction of this unichar
// Mirror property is useful for reverse DAWG lookup for words in
// right-to-left languages (e.g. "(word)" would be in
// '[open paren]' 'w' 'o' 'r' 'd' '[close paren]' in a UTF8 string.
// However, what we want in our DAWG is
// '[open paren]', 'd', 'r', 'o', 'w', '[close paren]' not
// '[close paren]', 'd', 'r', 'o', 'w', '[open paren]'.
UNICHAR_ID mirror;
STRING normed; // normalized version of this unichar
// Contains meta information about the fragment if a unichar represents
// a fragment of a character, otherwise should be set to NULL.
// It is assumed that character fragments are added to the unicharset
// after the corresponding 'base' characters.
CHAR_FRAGMENT *fragment;
};
struct UNICHAR_SLOT {
char representation[UNICHAR_LEN + 1];
UNICHAR_PROPERTIES properties;
};
// Gets the properties for a grapheme string, combining properties for
// multiple characters in a meaningful way where possible.
// Returns false if no valid match was found in the unicharset.
// NOTE that script_id, mirror, and other_case refer to this unicharset on
// return and will need redirecting if the target unicharset is different.
bool GetStrProperties(const char* utf8_str,
UNICHAR_PROPERTIES* props) const;
// Load ourselves from a "file" where our only interface to the file is
// an implementation of fgets(). This is the parsing primitive accessed by
// the public routines load_from_file() and load_from_inmemory_file().
bool load_via_fgets(TessResultCallback2<char *, char *, int> *fgets_cb,
bool skip_fragments);
UNICHAR_SLOT* unichars;
UNICHARMAP ids;
int size_used;
int size_reserved;
char** script_table;
int script_table_size_used;
int script_table_size_reserved;
const char* null_script;
// True if the unichars have their tops/bottoms set.
bool top_bottom_set_;
// True if the unicharset has significant upper/lower case chars.
bool script_has_upper_lower_;
// True if the unicharset has a significant mean-line with significant
// ascenders above that.
bool script_has_xheight_;
// A few convenient script name-to-id mapping without using hash.
// These are initialized when unicharset file is loaded. Anything
// missing from this list can be looked up using get_script_id_from_name.
int null_sid_;
int common_sid_;
int latin_sid_;
int cyrillic_sid_;
int greek_sid_;
int han_sid_;
int hiragana_sid_;
int katakana_sid_;
// The most frequently occurring script in the charset.
int default_sid_;
};
#endif // TESSERACT_CCUTIL_UNICHARSET_H__