Update Tesseract to version 5.0.

This commit is contained in:
Damiano Galassi committed 2021-12-07 12:05:31 +01:00
1 parent f9492c57bc
commit 8cffa8c9bb
32 files changed
+1119 -12894

No files matched your search

+209 -321
View File
@@ -19,76 +19,53 @@
#ifndef TESSERACT_API_BASEAPI_H_
#define TESSERACT_API_BASEAPI_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 "tess_version.h"
#include "apitypes.h"
#ifdef HAVE_CONFIG_H
# include "config_auto.h" // DISABLED_LEGACY_ENGINE
#endif
#include "export.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"
template <typename T> class GenericVector;
class PAGE_RES;
class PAGE_RES_IT;
class ParagraphModel;
struct BlamerBundle;
class BLOCK_LIST;
class DENORM;
class MATRIX;
class ROW;
class STRING;
class WERD;
#include <tesseract/version.h>
#include <cstdio>
#include <vector> // for std::vector
struct Pix;
struct Box;
struct Pixa;
struct Boxa;
class ETEXT_DESC;
struct OSResults;
class TBOX;
class UNICHARSET;
class WERD_CHOICE_LIST;
struct INT_FEATURE_STRUCT;
typedef INT_FEATURE_STRUCT *INT_FEATURE;
struct TBLOB;
namespace tesseract {
class PAGE_RES;
class ParagraphModel;
class BLOCK_LIST;
class ETEXT_DESC;
struct OSResults;
class UNICHARSET;
class Dawg;
class Dict;
class EquationDetect;
class PageIterator;
class ImageThresholder;
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 WERD_CHOICE_LIST &best_choices,
const UNICHARSET &unicharset,
BlamerBundle *blamer_bundle);
typedef TessCallback4<const UNICHARSET &, int, PageIterator *, Pix *>
TruthCallback;
// Function to read a std::vector<char> from a whole file.
// Returns false on failure.
using FileReader = bool (*)(const char *filename, std::vector<char> *data);
using DictFunc = int (Dict::*)(void *, const UNICHARSET &, UNICHAR_ID,
bool) const;
using ProbabilityInContextFunc = double (Dict::*)(const char *, const char *,
int, const char *, int);
/**
* Base class for all tesseract APIs.
@@ -99,14 +76,17 @@ typedef TessCallback4<const UNICHARSET &, int, PageIterator *, Pix *>
* include any other Tesseract headers.
*/
class TESS_API TessBaseAPI {
public:
public:
TessBaseAPI();
virtual ~TessBaseAPI();
// Copy constructor and assignment operator are currently unsupported.
TessBaseAPI(TessBaseAPI const &) = delete;
TessBaseAPI &operator=(TessBaseAPI const &) = delete;
/**
* Returns the version identifier as a static string. Do not delete.
*/
static const char* Version();
static const char *Version();
/**
* If compiled with OpenCL AND an available OpenCL
@@ -117,17 +97,11 @@ class TESS_API TessBaseAPI {
*/
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);
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
@@ -135,15 +109,15 @@ class TESS_API TessBaseAPI {
* we need the original image. Finally, resolution metadata
* is stored in the PDF so we need that as well.
*/
const char* GetInputName();
const char *GetInputName();
// Takes ownership of the input pix.
void SetInputImage(Pix *pix);
Pix* GetInputImage();
Pix *GetInputImage();
int GetSourceYResolution();
const char* GetDatapath();
const char *GetDatapath();
/** Set the name of the bonus output files. Needed only for debugging. */
void SetOutputName(const char* name);
void SetOutputName(const char *name);
/**
* Set the value of an internal "parameter."
@@ -158,8 +132,8 @@ class TESS_API TessBaseAPI {
* Note: Must be called after Init(). Only works for non-init variables
* (init variables should be passed to Init()).
*/
bool SetVariable(const char* name, const char* value);
bool SetDebugVariable(const char* name, const char* value);
bool SetVariable(const char *name, const char *value);
bool SetDebugVariable(const char *name, const char *value);
/**
* Returns true if the parameter was found among Tesseract parameters.
@@ -175,6 +149,15 @@ class TESS_API TessBaseAPI {
*/
const char *GetStringVariable(const char *name) const;
#ifndef DISABLED_LEGACY_ENGINE
/**
* Print Tesseract fonts table to the given file.
*/
void PrintFontsTable(FILE *fp) const;
#endif
/**
* Print Tesseract parameters to the given file.
*/
@@ -183,7 +166,7 @@ class TESS_API TessBaseAPI {
/**
* Get value of named variable as a string, if it exists.
*/
bool GetVariableAsString(const char *name, STRING *val);
bool GetVariableAsString(const char *name, std::string *val) const;
/**
* Instances are now mostly thread-safe and totally independent,
@@ -196,10 +179,9 @@ class TESS_API TessBaseAPI {
* NOTE that the only members that may be called before Init are those
* listed above here in the class definition.
*
* 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 nullptr will default to eng.
* It is entirely safe (and eventually will be efficient too) to call
* The datapath must be the name of the tessdata directory.
* 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.
* The language may be a string of the form [~]<lang>[+[~]<lang>]* indicating
@@ -223,23 +205,24 @@ class TESS_API TessBaseAPI {
* If set_only_non_debug_params is true, only params that do not contain
* "debug" in the name will be set.
*/
int Init(const char* datapath, const char* language, OcrEngineMode mode,
int Init(const char *datapath, const char *language, OcrEngineMode mode,
char **configs, int configs_size,
const GenericVector<STRING> *vars_vec,
const GenericVector<STRING> *vars_values,
const std::vector<std::string> *vars_vec,
const std::vector<std::string> *vars_values,
bool set_only_non_debug_params);
int Init(const char* datapath, const char* language, OcrEngineMode oem) {
int Init(const char *datapath, const char *language, OcrEngineMode oem) {
return Init(datapath, language, oem, nullptr, 0, nullptr, nullptr, false);
}
int Init(const char* datapath, const char* language) {
return Init(datapath, language, OEM_DEFAULT, nullptr, 0, nullptr, nullptr, false);
int Init(const char *datapath, const char *language) {
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,
int Init(const char *data, int data_size, const char *language,
OcrEngineMode mode, char **configs, int configs_size,
const std::vector<std::string> *vars_vec,
const std::vector<std::string> *vars_values,
bool set_only_non_debug_params, FileReader reader);
/**
@@ -250,27 +233,19 @@ class TESS_API TessBaseAPI {
* loaded use GetLoadedLanguagesAsVector.
* The returned string should NOT be deleted.
*/
const char* GetInitLanguagesAsString() const;
const char *GetInitLanguagesAsString() const;
/**
* Returns the loaded languages in the vector of STRINGs.
* Returns the loaded languages in the vector of std::string.
* Includes all languages loaded by the last Init, including those loaded
* as dependencies of other loaded languages.
*/
void GetLoadedLanguagesAsVector(GenericVector<STRING>* langs) const;
void GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const;
/**
* Returns the available languages in the sorted vector of STRINGs.
* Returns the available languages in the sorted vector of std::string.
*/
void GetAvailableLanguagesAsVector(GenericVector<STRING>* langs) const;
/**
* Init only the lang model component of Tesseract. The only functions
* that work after this init are SetVariable and IsValidWord.
* WARNING: temporary! This function will be removed from here and placed
* in a separate API at some future time.
*/
int InitLangMod(const char* datapath, const char* language);
void GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const;
/**
* Init only for page layout analysis. Use only for calls to SetImage and
@@ -284,9 +259,9 @@ class TESS_API TessBaseAPI {
* and also accepts a relative or absolute path name.
* Note: only non-init params will be set (init params are set by Init()).
*/
void ReadConfigFile(const char* filename);
void ReadConfigFile(const char *filename);
/** Same as above, but only set debug params from the given config file. */
void ReadDebugConfigFile(const char* filename);
void ReadDebugConfigFile(const char *filename);
/**
* Set the current page segmentation mode. Defaults to PSM_SINGLE_BLOCK.
@@ -315,9 +290,9 @@ class TESS_API TessBaseAPI {
* For advanced uses, use SetImage, (optionally) SetRectangle, Recognize,
* and one or more of the Get*Text functions below.
*/
char* TesseractRect(const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
int left, int top, int width, int height);
char *TesseractRect(const unsigned char *imagedata, int bytes_per_pixel,
int bytes_per_line, int left, int top, int width,
int height);
/**
* Call between pages or documents etc to free up memory and forget
@@ -331,7 +306,7 @@ class TESS_API TessBaseAPI {
* get hold of the thresholded image, get the text in different formats,
* get bounding boxes, confidences etc.
*/
/* @{ */
/* @{ */
/**
* Provide an image for Tesseract to recognize. Format is as
@@ -340,7 +315,7 @@ class TESS_API TessBaseAPI {
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*/
void SetImage(const unsigned char* imagedata, int width, int height,
void SetImage(const unsigned char *imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line);
/**
@@ -351,7 +326,7 @@ class TESS_API TessBaseAPI {
* Use Pix where possible. Tesseract uses Pix as its internal representation
* and it is therefore more efficient to provide a Pix directly.
*/
void SetImage(Pix* pix);
void SetImage(Pix *pix);
/**
* Set the resolution of the source image in pixels per inch so font size
@@ -366,32 +341,19 @@ class TESS_API TessBaseAPI {
*/
void SetRectangle(int left, int top, int width, int height);
/**
* In extreme cases only, usually with a subclass of Thresholder, it
* is possible to provide a different Thresholder. The Thresholder may
* be preloaded with an image, settings etc, or they may be set after.
* Note that Tesseract takes ownership of the Thresholder and will
* delete it when it it is replaced or the API is destructed.
*/
void SetThresholder(ImageThresholder* thresholder) {
delete thresholder_;
thresholder_ = thresholder;
ClearResults();
}
/**
* Get a copy of the internal thresholded image from Tesseract.
* Caller takes ownership of the Pix and must pixDestroy it.
* May be called any time after SetImage, or after TesseractRect.
*/
Pix* GetThresholdedImage();
Pix *GetThresholdedImage();
/**
* Get the result of page layout analysis as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* GetRegions(Pixa** pixa);
Boxa *GetRegions(Pixa **pixa);
/**
* Get the textlines as a leptonica-style
@@ -399,17 +361,17 @@ class TESS_API TessBaseAPI {
* Can be called before or after Recognize.
* 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.
* 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(const bool raw_image, const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
Boxa *GetTextlines(bool raw_image, 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) {
Helper method to extract from the thresholded image. (most common usage)
*/
Boxa *GetTextlines(Pixa **pixa, int **blockids) {
return GetTextlines(false, 0, pixa, blockids, nullptr);
}
@@ -418,17 +380,17 @@ class TESS_API TessBaseAPI {
* pair, in reading order. Enables downstream handling of non-rectangular
* regions.
* Can be called before or after Recognize.
* 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 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);
Boxa *GetStrips(Pixa **pixa, int **blockids);
/**
* Get the words as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* GetWords(Pixa** pixa);
Boxa *GetWords(Pixa **pixa);
/**
* Gets the individual connected (text) components (created
@@ -438,7 +400,7 @@ class TESS_API TessBaseAPI {
* Note: the caller is responsible for calling boxaDestroy()
* on the returned Boxa array and pixaDestroy() on cc array.
*/
Boxa* GetConnectedComponents(Pixa** cc);
Boxa *GetConnectedComponents(Pixa **cc);
/**
* Get the given level kind of components (block, textline, word etc.) as a
@@ -446,22 +408,20 @@ class TESS_API TessBaseAPI {
* Can be called before or after Recognize.
* 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.
* 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(const PageIteratorLevel level,
const bool text_only, const bool raw_image,
const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
Boxa *GetComponentImages(PageIteratorLevel level, bool text_only,
bool raw_image, 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);
Boxa *GetComponentImages(const PageIteratorLevel level, const bool text_only,
Pixa **pixa, int **blockids) {
return GetComponentImages(level, text_only, false, 0, pixa, blockids,
nullptr);
}
/**
@@ -487,8 +447,8 @@ class TESS_API TessBaseAPI {
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
PageIterator* AnalyseLayout();
PageIterator* AnalyseLayout(bool merge_similar_words);
PageIterator *AnalyseLayout();
PageIterator *AnalyseLayout(bool merge_similar_words);
/**
* Recognize the image from SetAndThresholdImage, generating Tesseract
@@ -496,18 +456,13 @@ class TESS_API TessBaseAPI {
* Optional. The Get*Text functions below will call Recognize if needed.
* After Recognize, the output is kept internally until the next SetImage.
*/
int Recognize(ETEXT_DESC* monitor);
int Recognize(ETEXT_DESC *monitor);
/**
* Methods to retrieve information after SetAndThresholdImage(),
* 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
/**
* Turns images into symbolic text.
*
@@ -530,11 +485,11 @@ class TESS_API TessBaseAPI {
*
* Returns true if successful, false on error.
*/
bool ProcessPages(const char* filename, const char* retry_config,
int timeout_millisec, TessResultRenderer* renderer);
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);
bool ProcessPagesInternal(const char *filename, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer);
/**
* Turn a single image into symbolic text.
@@ -543,11 +498,11 @@ class TESS_API TessBaseAPI {
* metadata used by side-effect processes, such as reading a box
* file or formatting as hOCR.
*
* See ProcessPages for desciptions of other parameters.
* See ProcessPages for descriptions of other parameters.
*/
bool ProcessPage(Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer);
bool ProcessPage(Pix *pix, int page_index, const char *filename,
const char *retry_config, int timeout_millisec,
TessResultRenderer *renderer);
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
@@ -557,7 +512,7 @@ class TESS_API TessBaseAPI {
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
ResultIterator* GetIterator();
ResultIterator *GetIterator();
/**
* Get a mutable iterator to the results of LayoutAnalysis and/or Recognize.
@@ -567,13 +522,13 @@ class TESS_API TessBaseAPI {
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
MutableIterator* GetMutableIterator();
MutableIterator *GetMutableIterator();
/**
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
*/
char* GetUTF8Text();
char *GetUTF8Text();
/**
* Make a HTML-formatted string with hOCR markup from the internal
@@ -584,7 +539,7 @@ class TESS_API TessBaseAPI {
* receive progress callbacks
* Returned string must be freed with the delete [] operator.
*/
char* GetHOCRText(ETEXT_DESC* monitor, int page_number);
char *GetHOCRText(ETEXT_DESC *monitor, int page_number);
/**
* Make a HTML-formatted string with hOCR markup from the internal
@@ -592,14 +547,34 @@ class TESS_API TessBaseAPI {
* 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);
char *GetHOCRText(int page_number);
/**
* Make an XML-formatted string with Alto markup from the internal
* data structures.
*/
char *GetAltoText(ETEXT_DESC *monitor, int page_number);
/**
* Make an XML-formatted string with Alto markup from the internal
* data structures.
*/
char *GetAltoText(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);
char *GetTSVText(int page_number);
/**
* Make a box file for LSTM training from the internal data structures.
* 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 *GetLSTMBoxText(int page_number);
/**
* The recognized text is returned as a char* which is coded in the same
@@ -608,14 +583,22 @@ class TESS_API TessBaseAPI {
* 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);
char *GetBoxText(int page_number);
/**
* The recognized text is returned as a char* which is coded in the same
* format as a WordStr box file used in training.
* 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 *GetWordStrBoxText(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.
* Returned string must be freed with the delete [] operator.
*/
char* GetUNLVText();
char *GetUNLVText();
/**
* Detect the orientation of the input image and apparent script (alphabet).
@@ -626,15 +609,15 @@ class TESS_API TessBaseAPI {
* 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);
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);
char *GetOsdText(int page_number);
/** Returns the (average) confidence value between 0 and 100. */
int MeanTextConf();
@@ -644,7 +627,7 @@ class TESS_API TessBaseAPI {
* The number of confidences should correspond to the number of space-
* delimited words in GetUTF8Text.
*/
int* AllWordConfidences();
int *AllWordConfidences();
#ifndef DISABLED_LEGACY_ENGINE
/**
@@ -657,8 +640,8 @@ class TESS_API TessBaseAPI {
* The currently set PageSegMode is preserved.
* Returns false if adaption was not possible for some reason.
*/
bool AdaptToWordStr(PageSegMode mode, const char* wordstr);
#endif // ndef DISABLED_LEGACY_ENGINE
bool AdaptToWordStr(PageSegMode mode, const char *wordstr);
#endif // ndef DISABLED_LEGACY_ENGINE
/**
* Free up recognition results and any stored image data, without actually
@@ -691,12 +674,11 @@ class TESS_API TessBaseAPI {
* @warning temporary! This function will be removed from here and placed
* in a separate API at some future time.
*/
int IsValidWord(const char *word);
int IsValidWord(const char *word) const;
// Returns true if utf8_character is defined in the UniCharset.
bool IsValidCharacter(const char *utf8_character);
bool IsValidCharacter(const char *utf8_character) const;
bool GetTextDirection(int* out_offset, float* out_slope);
bool GetTextDirection(int *out_offset, float *out_slope);
/** Sets Dict::letter_is_okay_ function to point to the given function. */
void SetDictFunc(DictFunc f);
@@ -710,69 +692,17 @@ class TESS_API TessBaseAPI {
* Estimates the Orientation And Script of the image.
* @return true if the image was processed successfully.
*/
bool DetectOS(OSResults*);
bool DetectOS(OSResults *);
/**
* 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();
/**
* 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);
/** Returns a ROW object created from the input row specification. */
static ROW *MakeTessOCRRow(float baseline, float xheight,
float descender, float ascender);
/** Returns a TBLOB corresponding to the entire input image. */
static TBLOB *MakeTBLOB(Pix *pix);
/**
* This method baseline normalizes a TBLOB in-place. The input row is used
* 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);
/** 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
void GetBlockTextOrientations(int **block_orientation,
bool **vertical_writing);
/** This method returns the string form of the specified unichar. */
const char* GetUnichar(int unichar_id);
const char *GetUnichar(int unichar_id) const;
/** Return the pointer to the i-th dawg loaded into tesseract_ object. */
const Dawg *GetDawg(int i) const;
@@ -780,31 +710,33 @@ class TESS_API TessBaseAPI {
/** Return the number of dawgs loaded into tesseract_ object. */
int NumDawgs() const;
Tesseract* tesseract() const { return tesseract_; }
Tesseract *tesseract() const {
return tesseract_;
}
OcrEngineMode oem() const { return last_oem_requested_; }
void InitTruthCallback(TruthCallback *cb) { truth_cb_ = cb; }
OcrEngineMode oem() const {
return last_oem_requested_;
}
void set_min_orientation_margin(double margin);
/* @} */
/* @} */
protected:
/** Common code for setting the image. Returns true if Init has been called. */
TESS_LOCAL bool InternalSetImage();
protected:
/** Common code for setting the image. Returns true if Init has been called.
*/
bool InternalSetImage();
/**
* 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 bool Threshold(Pix** pix);
virtual bool Threshold(Pix **pix);
/**
* Find lines from the image making the BLOCK_LIST.
* @return 0 on success.
*/
TESS_LOCAL int FindLines();
int FindLines();
/** Delete the pageres and block list ready for a new page. */
void ClearResults();
@@ -814,7 +746,7 @@ class TESS_API TessBaseAPI {
* to ignore all BiDi smarts at that point.
* delete once you're done with it.
*/
TESS_LOCAL LTRResultIterator* GetLTRIterator();
LTRResultIterator *GetLTRIterator();
/**
* Return the length of the output text string, as UTF8, assuming
@@ -822,66 +754,30 @@ class TESS_API TessBaseAPI {
* and assuming a single character reject marker for each rejected character.
* Also return the number of recognized blobs in blob_count.
*/
TESS_LOCAL int TextLength(int* blob_count);
int TextLength(int *blob_count) const;
//// paragraphs.cpp ////////////////////////////////////////////////////
TESS_LOCAL void DetectParagraphs(bool after_text_recognition);
void DetectParagraphs(bool after_text_recognition);
#ifndef DISABLED_LEGACY_ENGINE
const PAGE_RES *GetPageRes() const {
return page_res_;
}
/** @defgroup ocropusAddOns ocropus add-ons */
/* @{ */
/**
* Adapt to recognize the current image as the given character.
* The image must be preloaded and be just an image of a single character.
*/
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr,
int length,
float baseline,
float xheight,
float descender,
float ascender);
/** 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);
/**
* Extract the OCR results, costs (penalty points for uncertainty),
* and the bounding boxes of the characters.
*/
TESS_LOCAL static int TesseractExtractResult(char** text,
int** lengths,
float** costs,
int** x0,
int** y0,
int** x1,
int** y1,
PAGE_RES* 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.
PAGE_RES* page_res_; ///< The page-level data.
STRING* input_file_; ///< Name used by training code.
STRING* output_file_; ///< Name used by debug code.
STRING* datapath_; ///< Current location of tessdata.
STRING* language_; ///< Last initialized language.
OcrEngineMode last_oem_requested_; ///< Last ocr language mode requested.
bool recognition_done_; ///< page_res_ contains recognition data.
TruthCallback *truth_cb_; /// fxn for setting truth_* in WERD_RES
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.
std::vector<ParagraphModel *> *paragraph_models_;
BLOCK_LIST *block_list_; ///< The page layout.
PAGE_RES *page_res_; ///< The page-level data.
std::string input_file_; ///< Name used by training code.
std::string output_file_; ///< Name used by debug code.
std::string datapath_; ///< Current location of tessdata.
std::string language_; ///< Last initialized language.
OcrEngineMode last_oem_requested_; ///< Last ocr language mode requested.
bool recognition_done_; ///< page_res_ contains recognition data.
/**
* @defgroup ThresholderParams Thresholder Parameters
@@ -896,31 +792,23 @@ class TESS_API TessBaseAPI {
int image_height_;
/* @} */
private:
private:
// A list of image filenames gets special consideration
bool ProcessPagesFileList(FILE *fp,
STRING *buf,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer,
bool ProcessPagesFileList(FILE *fp, std::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,
bool ProcessPagesMultipageTiff(const unsigned char *data, size_t size,
const char *filename, const char *retry_config,
int timeout_millisec,
TessResultRenderer* renderer,
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.
}; // class TessBaseAPI.
/** Escape a char string - remove &<>"' with HTML codes. */
STRING HOcrEscape(const char* text);
} // namespace tesseract.
std::string HOcrEscape(const char *text);
#endif // TESSERACT_API_BASEAPI_H_
} // namespace tesseract
#endif // TESSERACT_API_BASEAPI_H_
+341 -312
View File
@@ -18,47 +18,31 @@
#ifndef API_CAPI_H_
#define API_CAPI_H_
#if defined(TESSERACT_API_BASEAPI_H_) && !defined(TESS_CAPI_INCLUDE_BASEAPI)
# define TESS_CAPI_INCLUDE_BASEAPI
#include "export.h"
#ifdef __cplusplus
# include <tesseract/baseapi.h>
# include <tesseract/ocrclass.h>
# include <tesseract/pageiterator.h>
# include <tesseract/renderer.h>
# include <tesseract/resultiterator.h>
#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
#include <stdbool.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef TESS_CALL
# if defined(WIN32)
# define TESS_CALL __cdecl
# else
# define TESS_CALL
# endif
#endif
#ifndef BOOL
# define BOOL int
# define TRUE 1
# define FALSE 0
# define BOOL int
# define TRUE 1
# define FALSE 0
#endif
#ifdef TESS_CAPI_INCLUDE_BASEAPI
#ifdef __cplusplus
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;
@@ -66,48 +50,95 @@ 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::Orientation TessOrientation;
typedef tesseract::ParagraphJustification TessParagraphJustification;
typedef tesseract::WritingDirection TessWritingDirection;
typedef tesseract::TextlineOrder TessTextlineOrder;
typedef PolyBlockType TessPolyBlockType;
typedef tesseract::PolyBlockType TessPolyBlockType;
typedef tesseract::ETEXT_DESC ETEXT_DESC;
#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 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_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_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 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_SPARSE_TEXT,
PSM_SPARSE_TEXT_OSD,
PSM_RAW_LINE,
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_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;
#endif
typedef bool (*TessCancelFunc)(void* cancel_this, int words);
typedef bool (*TessProgressFunc)(ETEXT_DESC* ths, int left, int right, int top,
typedef bool (*TessCancelFunc)(void *cancel_this, int words);
typedef bool (*TessProgressFunc)(ETEXT_DESC *ths, int left, int right, int top,
int bottom);
struct Pix;
@@ -116,336 +147,334 @@ struct Pixa;
/* General free functions */
TESS_API const char*
TESS_CALL TessVersion();
TESS_API void TESS_CALL TessDeleteText(char* text);
TESS_API void TESS_CALL TessDeleteTextArray(char** arr);
TESS_API void TESS_CALL TessDeleteIntArray(int* arr);
TESS_API const char *TessVersion();
TESS_API void TessDeleteText(const char *text);
TESS_API void TessDeleteTextArray(char **arr);
TESS_API void TessDeleteIntArray(const int *arr);
/* 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 TessResultRenderer *TessTextRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessHOcrRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessHOcrRendererCreate2(const char *outputbase,
BOOL font_info);
TESS_API TessResultRenderer *TessAltoRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessTsvRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessPDFRendererCreate(const char *outputbase,
const char *datadir,
BOOL textonly);
TESS_API TessResultRenderer *TessUnlvRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessBoxTextRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessLSTMBoxRendererCreate(const char *outputbase);
TESS_API TessResultRenderer *TessWordStrBoxRendererCreate(
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 void TessDeleteResultRenderer(TessResultRenderer *renderer);
TESS_API void TessResultRendererInsert(TessResultRenderer *renderer,
TessResultRenderer *next);
TESS_API TessResultRenderer *TessResultRendererNext(
TessResultRenderer *renderer);
TESS_API BOOL TessResultRendererBeginDocument(TessResultRenderer *renderer,
const char *title);
TESS_API BOOL TessResultRendererAddImage(TessResultRenderer *renderer,
TessBaseAPI *api);
TESS_API BOOL 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);
TESS_API const char *TessResultRendererExtention(TessResultRenderer *renderer);
TESS_API const char *TessResultRendererTitle(TessResultRenderer *renderer);
TESS_API int TessResultRendererImageNum(TessResultRenderer *renderer);
/* Base API */
TESS_API TessBaseAPI*
TESS_CALL TessBaseAPICreate();
TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle);
TESS_API TessBaseAPI *TessBaseAPICreate();
TESS_API void TessBaseAPIDelete(TessBaseAPI *handle);
TESS_API size_t TESS_CALL TessBaseAPIGetOpenCLDevice(TessBaseAPI* handle, void **device);
TESS_API size_t 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 TessBaseAPISetInputName(TessBaseAPI *handle, const char *name);
TESS_API const char *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 void TessBaseAPISetInputImage(TessBaseAPI *handle, struct Pix *pix);
TESS_API struct Pix *TessBaseAPIGetInputImage(TessBaseAPI *handle);
TESS_API int TESS_CALL TessBaseAPIGetSourceYResolution(TessBaseAPI* handle);
TESS_API const char* TESS_CALL TessBaseAPIGetDatapath(TessBaseAPI* handle);
TESS_API int TessBaseAPIGetSourceYResolution(TessBaseAPI *handle);
TESS_API const char *TessBaseAPIGetDatapath(TessBaseAPI *handle);
TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name);
TESS_API void 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 TessBaseAPISetVariable(TessBaseAPI *handle, const char *name,
const char *value);
TESS_API BOOL 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 TessBaseAPIGetDoubleVariable(const TessBaseAPI* handle, const char* name, double* value);
TESS_API const char*
TESS_CALL TessBaseAPIGetStringVariable(const TessBaseAPI* handle, const char* name);
TESS_API BOOL TessBaseAPIGetIntVariable(const TessBaseAPI *handle,
const char *name, int *value);
TESS_API BOOL TessBaseAPIGetBoolVariable(const TessBaseAPI *handle,
const char *name, BOOL *value);
TESS_API BOOL TessBaseAPIGetDoubleVariable(const TessBaseAPI *handle,
const char *name, double *value);
TESS_API const char *TessBaseAPIGetStringVariable(const TessBaseAPI *handle,
const char *name);
TESS_API void TESS_CALL TessBaseAPIPrintVariables(const TessBaseAPI* handle, FILE* fp);
TESS_API BOOL TESS_CALL TessBaseAPIPrintVariablesToFile(const TessBaseAPI* handle, const char* filename);
TESS_API void TessBaseAPIPrintVariables(const TessBaseAPI *handle, FILE *fp);
TESS_API BOOL TessBaseAPIPrintVariablesToFile(const TessBaseAPI *handle,
const char *filename);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API int TessBaseAPIInit1(TessBaseAPI *handle, const char *datapath,
const char *language, TessOcrEngineMode oem,
char **configs, int configs_size);
TESS_API int TessBaseAPIInit2(TessBaseAPI *handle, const char *datapath,
const char *language, TessOcrEngineMode oem);
TESS_API int TessBaseAPIInit3(TessBaseAPI *handle, const char *datapath,
const char *language);
TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val);
TESS_API int 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 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);
TESS_API const char *TessBaseAPIGetInitLanguagesAsString(
const TessBaseAPI *handle);
TESS_API char **TessBaseAPIGetLoadedLanguagesAsVector(
const TessBaseAPI *handle);
TESS_API char **TessBaseAPIGetAvailableLanguagesAsVector(
const TessBaseAPI *handle);
#endif // def TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TessBaseAPIInitForAnalysePage(TessBaseAPI *handle);
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 void TessBaseAPIReadConfigFile(TessBaseAPI *handle,
const char *filename);
TESS_API void TessBaseAPIReadDebugConfigFile(TessBaseAPI *handle,
const char *filename);
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 void TessBaseAPISetPageSegMode(TessBaseAPI *handle,
TessPageSegMode mode);
TESS_API TessPageSegMode TessBaseAPIGetPageSegMode(const TessBaseAPI *handle);
TESS_API const char*
TESS_CALL TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI* handle);
TESS_API char**
TESS_CALL TessBaseAPIGetLoadedLanguagesAsVector(const TessBaseAPI* handle);
TESS_API char**
TESS_CALL TessBaseAPIGetAvailableLanguagesAsVector(const TessBaseAPI* handle);
TESS_API char *TessBaseAPIRect(TessBaseAPI *handle,
const unsigned char *imagedata,
int bytes_per_pixel, int bytes_per_line,
int left, int top, int width, int height);
TESS_API int TESS_CALL TessBaseAPIInitLangMod(TessBaseAPI* handle, const char* datapath, const char* language);
TESS_API void TESS_CALL TessBaseAPIInitForAnalysePage(TessBaseAPI* handle);
TESS_API void TessBaseAPIClearAdaptiveClassifier(TessBaseAPI *handle);
TESS_API void TESS_CALL TessBaseAPIReadConfigFile(TessBaseAPI* handle, const char* filename);
TESS_API void TESS_CALL TessBaseAPIReadDebugConfigFile(TessBaseAPI* handle, const char* filename);
TESS_API void TessBaseAPISetImage(TessBaseAPI *handle,
const unsigned char *imagedata, int width,
int height, int bytes_per_pixel,
int bytes_per_line);
TESS_API void TessBaseAPISetImage2(TessBaseAPI *handle, struct Pix *pix);
TESS_API void TESS_CALL TessBaseAPISetPageSegMode(TessBaseAPI* handle, TessPageSegMode mode);
TESS_API TessPageSegMode
TESS_CALL TessBaseAPIGetPageSegMode(const TessBaseAPI* handle);
TESS_API void TessBaseAPISetSourceResolution(TessBaseAPI *handle, int ppi);
TESS_API char* TESS_CALL TessBaseAPIRect(TessBaseAPI* handle, const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
int left, int top, int width, int height);
TESS_API void TessBaseAPISetRectangle(TessBaseAPI *handle, int left, int top,
int width, int height);
TESS_API void TESS_CALL TessBaseAPIClearAdaptiveClassifier(TessBaseAPI* handle);
TESS_API struct Pix *TessBaseAPIGetThresholdedImage(TessBaseAPI *handle);
TESS_API struct Boxa *TessBaseAPIGetRegions(TessBaseAPI *handle,
struct Pixa **pixa);
TESS_API struct Boxa *TessBaseAPIGetTextlines(TessBaseAPI *handle,
struct Pixa **pixa,
int **blockids);
TESS_API struct Boxa *TessBaseAPIGetTextlines1(TessBaseAPI *handle,
BOOL raw_image, int raw_padding,
struct Pixa **pixa,
int **blockids, int **paraids);
TESS_API struct Boxa *TessBaseAPIGetStrips(TessBaseAPI *handle,
struct Pixa **pixa, int **blockids);
TESS_API struct Boxa *TessBaseAPIGetWords(TessBaseAPI *handle,
struct Pixa **pixa);
TESS_API struct Boxa *TessBaseAPIGetConnectedComponents(TessBaseAPI *handle,
struct Pixa **cc);
TESS_API struct Boxa *TessBaseAPIGetComponentImages(TessBaseAPI *handle,
TessPageIteratorLevel level,
BOOL text_only,
struct Pixa **pixa,
int **blockids);
TESS_API struct Boxa *TessBaseAPIGetComponentImages1(
TessBaseAPI *handle, TessPageIteratorLevel level, BOOL text_only,
BOOL raw_image, int raw_padding, struct Pixa **pixa, int **blockids,
int **paraids);
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, struct Pix* pix);
TESS_API int TessBaseAPIGetThresholdedImageScaleFactor(
const TessBaseAPI *handle);
TESS_API void TESS_CALL TessBaseAPISetSourceResolution(TessBaseAPI* handle, int ppi);
TESS_API TessPageIterator *TessBaseAPIAnalyseLayout(TessBaseAPI *handle);
TESS_API void TESS_CALL TessBaseAPISetRectangle(TessBaseAPI* handle, int left, int top, int width, int height);
TESS_API int TessBaseAPIRecognize(TessBaseAPI *handle, ETEXT_DESC *monitor);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API void TESS_CALL TessBaseAPISetThresholder(TessBaseAPI* handle, TessImageThresholder* thresholder);
#endif
TESS_API BOOL TessBaseAPIProcessPages(TessBaseAPI *handle, const char *filename,
const char *retry_config,
int timeout_millisec,
TessResultRenderer *renderer);
TESS_API BOOL TessBaseAPIProcessPage(TessBaseAPI *handle, struct Pix *pix,
int page_index, const char *filename,
const char *retry_config,
int timeout_millisec,
TessResultRenderer *renderer);
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 TessResultIterator *TessBaseAPIGetIterator(TessBaseAPI *handle);
TESS_API TessMutableIterator *TessBaseAPIGetMutableIterator(
TessBaseAPI *handle);
TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle);
TESS_API char *TessBaseAPIGetUTF8Text(TessBaseAPI *handle);
TESS_API char *TessBaseAPIGetHOCRText(TessBaseAPI *handle, int page_number);
TESS_API TessPageIterator*
TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle);
TESS_API char *TessBaseAPIGetAltoText(TessBaseAPI *handle, int page_number);
TESS_API char *TessBaseAPIGetTsvText(TessBaseAPI *handle, int page_number);
TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor);
TESS_API char *TessBaseAPIGetBoxText(TessBaseAPI *handle, int page_number);
TESS_API char *TessBaseAPIGetLSTMBoxText(TessBaseAPI *handle, int page_number);
TESS_API char *TessBaseAPIGetWordStrBoxText(TessBaseAPI *handle,
int page_number);
TESS_API char *TessBaseAPIGetUNLVText(TessBaseAPI *handle);
TESS_API int TessBaseAPIMeanTextConf(TessBaseAPI *handle);
TESS_API int *TessBaseAPIAllWordConfidences(TessBaseAPI *handle);
#ifndef DISABLED_LEGACY_ENGINE
TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor);
#endif
TESS_API BOOL TessBaseAPIAdaptToWordStr(TessBaseAPI *handle,
TessPageSegMode mode,
const char *wordstr);
#endif // #ifndef DISABLED_LEGACY_ENGINE
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 void TessBaseAPIClear(TessBaseAPI *handle);
TESS_API void TessBaseAPIEnd(TessBaseAPI *handle);
TESS_API TessResultIterator*
TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle);
TESS_API TessMutableIterator*
TESS_CALL TessBaseAPIGetMutableIterator(TessBaseAPI* handle);
TESS_API int TessBaseAPIIsValidWord(TessBaseAPI *handle, const char *word);
TESS_API BOOL TessBaseAPIGetTextDirection(TessBaseAPI *handle, int *out_offset,
float *out_slope);
TESS_API char* TESS_CALL TessBaseAPIGetUTF8Text(TessBaseAPI* handle);
TESS_API char* TESS_CALL TessBaseAPIGetHOCRText(TessBaseAPI* handle, int page_number);
TESS_API const char *TessBaseAPIGetUnichar(TessBaseAPI *handle, int unichar_id);
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);
TESS_API void TessBaseAPIClearPersistentCache(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);
// Call TessDeleteText(*best_script_name) to free memory allocated by this
// function
TESS_API BOOL TessBaseAPIDetectOrientationScript(TessBaseAPI *handle,
int *orient_deg,
float *orient_conf,
const char **script_name,
float *script_conf);
#endif // #ifndef DISABLED_LEGACY_ENGINE
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);
TESS_API void TessBaseAPISetMinOrientationMargin(TessBaseAPI *handle,
double margin);
TESS_API int TessBaseAPINumDawgs(const TessBaseAPI *handle);
#ifdef TESS_CAPI_INCLUDE_BASEAPI
TESS_API TessOcrEngineMode TessBaseAPIOem(const TessBaseAPI *handle);
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);
// 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);
#endif // def TESS_CAPI_INCLUDE_BASEAPI
TESS_API const char*
TESS_CALL TessBaseAPIGetUnichar(TessBaseAPI* handle, int unichar_id);
TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin);
#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);
TESS_API TessOcrEngineMode
TESS_CALL TessBaseAPIOem(const TessBaseAPI* handle);
TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback* cb);
TESS_API void TESS_CALL TessBaseGetBlockTextOrientations(TessBaseAPI* handle, int** block_orientation, bool** vertical_writing);
#endif
TESS_API void TessBaseGetBlockTextOrientations(TessBaseAPI *handle,
int **block_orientation,
bool **vertical_writing);
/* Page iterator */
TESS_API void TESS_CALL TessPageIteratorDelete(TessPageIterator* handle);
TESS_API void TessPageIteratorDelete(TessPageIterator *handle);
TESS_API TessPageIterator*
TESS_CALL TessPageIteratorCopy(const TessPageIterator* handle);
TESS_API TessPageIterator *TessPageIteratorCopy(const TessPageIterator *handle);
TESS_API void TESS_CALL TessPageIteratorBegin(TessPageIterator* handle);
TESS_API void TessPageIteratorBegin(TessPageIterator *handle);
TESS_API BOOL TESS_CALL TessPageIteratorNext(TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API BOOL TessPageIteratorNext(TessPageIterator *handle,
TessPageIteratorLevel level);
TESS_API BOOL TESS_CALL TessPageIteratorIsAtBeginningOf(const TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API BOOL TessPageIteratorIsAtBeginningOf(const TessPageIterator *handle,
TessPageIteratorLevel level);
TESS_API BOOL TESS_CALL TessPageIteratorIsAtFinalElement(const TessPageIterator* handle, TessPageIteratorLevel level,
TessPageIteratorLevel element);
TESS_API BOOL 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 BOOL TessPageIteratorBoundingBox(const TessPageIterator *handle,
TessPageIteratorLevel level,
int *left, int *top, int *right,
int *bottom);
TESS_API TessPolyBlockType
TESS_CALL TessPageIteratorBlockType(const TessPageIterator* handle);
TessPageIteratorBlockType(const TessPageIterator *handle);
TESS_API struct Pix*
TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level);
TESS_API struct Pix *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 struct Pix *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 BOOL 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 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);
TESS_API void TessPageIteratorParagraphInfo(
TessPageIterator *handle, TessParagraphJustification *justification,
BOOL *is_list_item, BOOL *is_crown, int *first_line_indent);
/* Result iterator */
TESS_API void TESS_CALL TessResultIteratorDelete(TessResultIterator* handle);
TESS_API TessResultIterator*
TESS_CALL TessResultIteratorCopy(const TessResultIterator* handle);
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 void TessResultIteratorDelete(TessResultIterator *handle);
TESS_API TessResultIterator *TessResultIteratorCopy(
const TessResultIterator *handle);
TESS_API TessPageIterator *TessResultIteratorGetPageIterator(
TessResultIterator *handle);
TESS_API const TessPageIterator *TessResultIteratorGetPageIteratorConst(
const TessResultIterator *handle);
TESS_API TessChoiceIterator *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,
BOOL* is_smallcaps, int* pointsize, int* font_id);
TESS_API BOOL TessResultIteratorNext(TessResultIterator *handle,
TessPageIteratorLevel level);
TESS_API char *TessResultIteratorGetUTF8Text(const TessResultIterator *handle,
TessPageIteratorLevel level);
TESS_API float TessResultIteratorConfidence(const TessResultIterator *handle,
TessPageIteratorLevel level);
TESS_API const char *TessResultIteratorWordRecognitionLanguage(
const TessResultIterator *handle);
TESS_API const char *TessResultIteratorWordFontAttributes(
const TessResultIterator *handle, BOOL *is_bold, BOOL *is_italic,
BOOL *is_underlined, BOOL *is_monospace, BOOL *is_serif, BOOL *is_smallcaps,
int *pointsize, int *font_id);
TESS_API BOOL TESS_CALL TessResultIteratorWordIsFromDictionary(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorWordIsNumeric(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSuperscript(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSubscript(const TessResultIterator* handle);
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsDropcap(const TessResultIterator* handle);
TESS_API BOOL
TessResultIteratorWordIsFromDictionary(const TessResultIterator *handle);
TESS_API BOOL TessResultIteratorWordIsNumeric(const TessResultIterator *handle);
TESS_API BOOL
TessResultIteratorSymbolIsSuperscript(const TessResultIterator *handle);
TESS_API BOOL
TessResultIteratorSymbolIsSubscript(const TessResultIterator *handle);
TESS_API BOOL
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);
TESS_API void TessChoiceIteratorDelete(TessChoiceIterator *handle);
TESS_API BOOL TessChoiceIteratorNext(TessChoiceIterator *handle);
TESS_API const char *TessChoiceIteratorGetUTF8Text(
const TessChoiceIterator *handle);
TESS_API float 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
TESS_API ETEXT_DESC *TessMonitorCreate();
TESS_API void TessMonitorDelete(ETEXT_DESC *monitor);
TESS_API void TessMonitorSetCancelFunc(ETEXT_DESC *monitor,
TessCancelFunc cancelFunc);
TESS_API void TessMonitorSetCancelThis(ETEXT_DESC *monitor, void *cancelThis);
TESS_API void *TessMonitorGetCancelThis(ETEXT_DESC *monitor);
TESS_API void TessMonitorSetProgressFunc(ETEXT_DESC *monitor,
TessProgressFunc progressFunc);
TESS_API int TessMonitorGetProgress(ETEXT_DESC *monitor);
TESS_API void TessMonitorSetDeadlineMSecs(ETEXT_DESC *monitor, int deadline);
#ifdef __cplusplus
}
#endif
#endif // API_CAPI_H_
#endif // API_CAPI_H_
@@ -1,10 +1,8 @@
///////////////////////////////////////////////////////////////////////
// File: apitypes.h
// Description: Types used in both the API and internally
// Author: Ray Smith
// Created: Wed Mar 03 09:22:53 PST 2010
// File: export.h
// Description: Place holder
//
// (C) Copyright 2010, Google Inc.
// (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
@@ -17,17 +15,25 @@
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_APITYPES_H_
#define TESSERACT_API_APITYPES_H_
#ifndef TESSERACT_PLATFORM_H_
#define TESSERACT_PLATFORM_H_
#include "publictypes.h"
#ifndef TESS_API
# if defined(_WIN32) || defined(__CYGWIN__)
# if defined(TESS_EXPORTS)
# define TESS_API __declspec(dllexport)
# elif defined(TESS_IMPORTS)
# define TESS_API __declspec(dllimport)
# else
# define TESS_API
# endif
# else
# if defined(TESS_EXPORTS) || defined(TESS_IMPORTS)
# define TESS_API __attribute__((visibility("default")))
# else
# define TESS_API
# endif
# endif
#endif
// The types used by the API and Page/ResultIterator can be found in:
// ccstruct/publictypes.h
// ccmain/resultiterator.h
// ccmain/pageiterator.h
// API interfaces and API users should be sure to include this file, rather
// 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_PLATFORM_H_
File diff suppressed because it is too large. Load diff
-205
View File
@@ -1,205 +0,0 @@
/* -*-C-*-
********************************************************************************
*
* File: helpers.h
* Description: General utility functions
* Author: Daria Antonova
* Created: Wed Apr 8 14:37:00 2009
* Language: C++
* Package: N/A
* Status: Reusable Software Component
*
* (c) Copyright 2009, 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_HELPERS_H_
#define TESSERACT_CCUTIL_HELPERS_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 = static_cast<int>(strlen(str)) - 1;
while (last_index >= 0 &&
(str[last_index] == '\n' || str[last_index] == '\r')) {
str[last_index--] = '\0';
}
}
// Advance the current pointer of the file if it points to a newline character.
inline void SkipNewline(FILE *file) {
if (fgetc(file) != '\n') fseek(file, -1, SEEK_CUR);
}
// 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.
inline int RoundUp(int n, int block_size) {
return block_size * ((n + block_size - 1) / block_size);
}
// Clip a numeric value to the interval [lower_bound, upper_bound].
template<typename T>
inline T ClipToRange(const T& x, const T& lower_bound, const T& upper_bound) {
if (x < lower_bound)
return lower_bound;
if (x > upper_bound)
return upper_bound;
return x;
}
// Extend the range [lower_bound, upper_bound] to include x.
template<typename T1, typename T2>
inline void UpdateRange(const T1& x, T2* lower_bound, T2* upper_bound) {
if (x < *lower_bound)
*lower_bound = x;
if (x > *upper_bound)
*upper_bound = x;
}
// Decrease lower_bound to be <= x_lo AND increase upper_bound to be >= x_hi.
template<typename T1, typename T2>
inline void UpdateRange(const T1& x_lo, const T1& x_hi,
T2* lower_bound, T2* upper_bound) {
if (x_lo < *lower_bound)
*lower_bound = x_lo;
if (x_hi > *upper_bound)
*upper_bound = x_hi;
}
// Intersect the range [*lower2, *upper2] with the range [lower1, upper1],
// putting the result back in [*lower2, *upper2].
// If non-intersecting ranges are given, we end up with *lower2 > *upper2.
template<typename T>
inline void IntersectRange(const T& lower1, const T& upper1,
T* lower2, T* upper2) {
if (lower1 > *lower2)
*lower2 = lower1;
if (upper1 < *upper2)
*upper2 = upper1;
}
// Proper modulo arithmetic operator. Returns a mod b that works for -ve a.
// For any integer a and positive b, returns r : 0<=r<b and a=n*b + r for
// some integer n.
inline int Modulo(int a, int b) {
return (a % b + b) % b;
}
// Integer division operator with rounding that works for negative input.
// Returns a divided by b, rounded to the nearest integer, without double
// counting at 0. With simple rounding 1/3 = 0, 0/3 = 0 -1/3 = 0, -2/3 = 0,
// -3/3 = 0 and -4/3 = -1.
// I want 1/3 = 0, 0/3 = 0, -1/3 = 0, -2/3 = -1, -3/3 = -1 and -4/3 = -1.
inline int DivRounded(int a, int b) {
if (b < 0) return -DivRounded(a, -b);
return a >= 0 ? (a + b / 2) / b : (a - b / 2) / b;
}
// Return a double cast to int with rounding.
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) {
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];
cptr[i] = cptr[num_bytes - 1 - i];
cptr[num_bytes - 1 - i] = tmp;
}
}
// Reverse the order of bytes in a 16 bit quantity for big/little-endian switch.
inline void Reverse16(void *ptr) {
ReverseN(ptr, 2);
}
// Reverse the order of bytes in a 32 bit quantity for big/little-endian switch.
inline void Reverse32(void *ptr) {
ReverseN(ptr, 4);
}
// Reverse the order of bytes in a 64 bit quantity for big/little-endian switch.
inline void Reverse64(void* ptr) {
ReverseN(ptr, 8);
}
#endif // TESSERACT_CCUTIL_HELPERS_H_
-65
View File
@@ -1,65 +0,0 @@
/******************************************************************************
** Filename: host.h
** Purpose: This is the system independent typedefs and defines
** Author: MN, JG, MD
**
** (c) Copyright Hewlett-Packard Company, 1988-1996.
** 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_HOST_H_
#define TESSERACT_CCUTIL_HOST_H_
#include <limits>
#include "platform.h"
/* _WIN32 */
#ifdef _WIN32
#include <windows.h>
#undef min
#undef max
#endif
#include <cinttypes> // PRId32, ...
#include <cstdint> // int32_t, ...
// definitions of portable data types (numbers and characters)
using BOOL8 = unsigned char;
#if defined(_WIN32)
/* MinGW defines the standard PRI... macros, but MSVS doesn't. */
#if !defined(PRId32)
#define PRId32 "d"
#endif
#if !defined(PRId64)
#define PRId64 "I64d"
#endif
#endif /* _WIN32 */
// Defines
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#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 // TESSERACT_CCUTIL_HOST_H_
+54 -41
View File
@@ -3,7 +3,6 @@
// Description: Iterator for tesseract results in strict left-to-right
// order that avoids using tesseract internal data structures.
// Author: Ray Smith
// Created: Fri Feb 26 11:01:06 PST 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,17 +20,17 @@
#ifndef TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
#define TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
#include "pageiterator.h" // for PageIterator
#include "platform.h" // for TESS_API
#include "publictypes.h" // for PageIteratorLevel
#include "unichar.h" // for StrongScriptDirection
#include "export.h" // for TESS_API
#include "pageiterator.h" // for PageIterator
#include "publictypes.h" // for PageIteratorLevel
#include "unichar.h" // for StrongScriptDirection
namespace tesseract {
class BLOB_CHOICE_IT;
class PAGE_RES;
class WERD_RES;
namespace tesseract {
class Tesseract;
// Class to iterate over tesseract results, providing access to all levels
@@ -41,13 +40,14 @@ class Tesseract;
// therefore can only be used while the TessBaseAPI class still exists and
// has not been subjected to a call of Init, SetImage, Recognize, Clear, End
// DetectOS, or anything else that changes the internal PAGE_RES.
// See apitypes.h for the definition of PageIteratorLevel.
// See tesseract/publictypes.h for the definition of PageIteratorLevel.
// See also base class PageIterator, which contains the bulk of the interface.
// LTRResultIterator adds text-specific methods for access to OCR output.
class TESS_API LTRResultIterator : public PageIterator {
friend class ChoiceIterator;
public:
public:
// page_res and tesseract come directly from the BaseAPI.
// The rectangle parameters are copied indirectly from the Thresholder,
// via the BaseAPI. They represent the coordinates of some rectangle in an
@@ -60,12 +60,11 @@ class TESS_API LTRResultIterator : public PageIterator {
// The scaled_yres indicates the effective resolution of the binary image
// that tesseract has been given by the Thresholder.
// After the constructor, Begin has already been called.
LTRResultIterator(PAGE_RES* page_res, Tesseract* tesseract,
int scale, int scaled_yres,
int rect_left, int rect_top,
LTRResultIterator(PAGE_RES *page_res, Tesseract *tesseract, int scale,
int scaled_yres, int rect_left, int rect_top,
int rect_width, int rect_height);
virtual ~LTRResultIterator();
~LTRResultIterator() override;
// LTRResultIterators may be copied! This makes it possible to iterate over
// all the objects at a lower level, while maintaining an iterator to
@@ -82,7 +81,7 @@ class TESS_API LTRResultIterator : public PageIterator {
// Returns the null terminated UTF-8 encoded text string for the current
// object at the given level. Use delete [] to free after use.
char* GetUTF8Text(PageIteratorLevel level) const;
char *GetUTF8Text(PageIteratorLevel level) const;
// Set the string inserted at the end of each text line. "\n" by default.
void SetLineSeparator(const char *new_line);
@@ -94,10 +93,6 @@ 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
@@ -108,18 +103,14 @@ class TESS_API LTRResultIterator : public PageIterator {
// the iterator itself, ie rendered invalid by various members of
// TessBaseAPI, including Init, SetImage, End or deleting the TessBaseAPI.
// Pointsize is returned in printers points (1/72 inch.)
const char* WordFontAttributes(bool* is_bold,
bool* is_italic,
bool* is_underlined,
bool* is_monospace,
bool* is_serif,
bool* is_smallcaps,
int* pointsize,
int* font_id) const;
const char *WordFontAttributes(bool *is_bold, bool *is_italic,
bool *is_underlined, bool *is_monospace,
bool *is_serif, bool *is_smallcaps,
int *pointsize, int *font_id) const;
// Return the name of the language used to recognize this word.
// On error, nullptr. Do not delete this pointer.
const char* WordRecognitionLanguage() const;
const char *WordRecognitionLanguage() const;
// Return the overall directionality of this word.
StrongScriptDirection WordDirection() const;
@@ -157,11 +148,11 @@ class TESS_API LTRResultIterator : public PageIterator {
// Returns a null terminated UTF-8 encoded truth string for the current word.
// Use delete [] to free after use.
char* WordTruthUTF8Text() const;
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;
char *WordNormedUTF8Text() const;
// Returns a pointer to serialized choice lattice.
// Fills lattice_size with the number of bytes in lattice data.
@@ -182,18 +173,18 @@ class TESS_API LTRResultIterator : public PageIterator {
// this will return the attributes of the first symbol in that word.
bool SymbolIsDropcap() const;
protected:
protected:
const char *line_separator_;
const char *paragraph_separator_;
};
// Class to iterate over the classifier choices for a single RIL_SYMBOL.
class ChoiceIterator {
public:
class TESS_API ChoiceIterator {
public:
// Construction is from a LTRResultIterator that points to the symbol of
// interest. The ChoiceIterator allows a one-shot iteration over the
// choices for this symbol and after that is is useless.
explicit ChoiceIterator(const LTRResultIterator& result_it);
explicit ChoiceIterator(const LTRResultIterator &result_it);
~ChoiceIterator();
// Moves to the next choice for the symbol and returns false if there
@@ -206,19 +197,41 @@ class ChoiceIterator {
// choice.
// NOTE: Unlike LTRResultIterator::GetUTF8Text, the return points to an
// internal structure and should NOT be delete[]ed to free after use.
const char* GetUTF8Text() const;
const char *GetUTF8Text() const;
// Returns the confidence of the current choice.
// The number should be interpreted as a percent probability. (0.0f-100.0f)
// Returns the confidence of the current choice depending on the used language
// data. If only LSTM traineddata is used the value range is 0.0f - 1.0f. All
// choices for one symbol should roughly add up to 1.0f.
// If only traineddata of the legacy engine is used, the number should be
// interpreted as a percent probability. (0.0f-100.0f) In this case
// probabilities won't add up to 100. Each one stands on its own.
float Confidence() const;
private:
// Returns a vector containing all timesteps, which belong to the currently
// selected symbol. A timestep is a vector containing pairs of symbols and
// floating point numbers. The number states the probability for the
// corresponding symbol.
std::vector<std::vector<std::pair<const char *, float>>> *Timesteps() const;
private:
// clears the remaining spaces out of the results and adapt the probabilities
void filterSpaces();
// Pointer to the WERD_RES object owned by the API.
WERD_RES* word_res_;
WERD_RES *word_res_;
// Iterator over the blob choices.
BLOB_CHOICE_IT* choice_it_;
BLOB_CHOICE_IT *choice_it_;
std::vector<std::pair<const char *, float>> *LSTM_choices_ = nullptr;
std::vector<std::pair<const char *, float>>::iterator LSTM_choice_it_;
const int *tstep_index_;
// regulates the rating granularity
double rating_coefficient_;
// leading blanks
int blanks_before_word_;
// true when there is lstm engine related trained data
bool oemLSTM_;
};
} // namespace tesseract.
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
#endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H_
+67 -94
View File
@@ -1,7 +1,7 @@
/**********************************************************************
* File: ocrclass.h
* Description: Class definitions and constants for the OCR API.
* Author: Hewlett-Packard Co
* Author: Hewlett-Packard Co
*
* (C) Copyright 1996, Hewlett-Packard Co.
** Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,33 +19,17 @@
/**********************************************************************
* 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 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"
#include <chrono>
#include <ctime>
/*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 */
namespace tesseract {
/**********************************************************************
* EANYCODE_CHAR
@@ -71,26 +55,26 @@
* 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 */
struct EANYCODE_CHAR { /*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) */
};
/**********************************************************************
* ETEXT_DESC
@@ -110,75 +94,64 @@ typedef struct { /*single character */
**********************************************************************/
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);
using CANCEL_FUNC = bool (*)(void *, int);
using PROGRESS_FUNC = bool (*)(int, int, int, int, int);
using PROGRESS_FUNC2 = bool (*)(ETEXT_DESC *, int, int, int, int);
class ETEXT_DESC { // output header
public:
int16_t count; /// chars in this buffer(0)
int16_t progress; /// percent complete increasing (0-100)
class ETEXT_DESC { // output header
public:
int16_t count{0}; /// chars in this buffer(0)
int16_t progress{0}; /// 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
* analysis.
* See Ray comment in https://github.com/tesseract-ocr/tesseract/pull/27 */
int8_t more_to_come{0}; /// true if not last
volatile int8_t ocr_alive{0}; /// ocr sets to 1, HP 0
int8_t err_code{0}; /// for errcode use
CANCEL_FUNC cancel{nullptr}; /// returns true to cancel
PROGRESS_FUNC progress_callback{
nullptr}; /// called whenever progress increases
PROGRESS_FUNC2 progress_callback2; /// monitor-aware progress callback
void *cancel_this{nullptr}; /// this or other data for cancel
std::chrono::steady_clock::time_point 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;
ETEXT_DESC() : progress_callback2(&default_progress_func) {
end_time = std::chrono::time_point<std::chrono::steady_clock,
std::chrono::milliseconds>();
}
// 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;
if (deadline_msecs > 0) {
end_time = std::chrono::steady_clock::now() +
std::chrono::milliseconds(deadline_msecs);
}
}
// 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));
if (end_time.time_since_epoch() ==
std::chrono::steady_clock::duration::zero()) {
return false;
}
auto now = std::chrono::steady_clock::now();
return (now > end_time);
}
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);
static bool default_progress_func(ETEXT_DESC *ths, int left, int right,
int top, int bottom) {
if (ths->progress_callback != nullptr) {
return (*(ths->progress_callback))(ths->progress, left, right, top,
bottom);
}
return true;
}
};
#endif // CCUTIL_OCRCLASS_H_
} // namespace tesseract
#endif // CCUTIL_OCRCLASS_H_
+45 -44
View File
@@ -20,26 +20,26 @@
#ifndef TESSERACT_CCMAIN_OSDETECT_H_
#define TESSERACT_CCMAIN_OSDETECT_H_
#include "platform.h" // for TESS_API
#include "export.h" // for TESS_API
#include <vector> // for std::vector
namespace tesseract {
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) {}
OSBestResult()
: orientation_id(0), script_id(0), sconfidence(0.0), oconfidence(0.0) {}
int orientation_id;
int script_id;
float sconfidence;
@@ -49,8 +49,9 @@ struct OSBestResult {
struct OSResults {
OSResults() : unicharset(nullptr) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < kMaxNumberOfScripts; ++j)
for (int j = 0; j < kMaxNumberOfScripts; ++j) {
scripts_na[i][j] = 0;
}
orientations[i] = 0;
}
}
@@ -63,7 +64,7 @@ struct OSResults {
// 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);
void accumulate(const OSResults &osr);
// Print statistics.
void print_scores(void) const;
@@ -77,32 +78,34 @@ struct OSResults {
// Script confidence scores for each of 4 possible orientations.
float scripts_na[4][kMaxNumberOfScripts];
UNICHARSET* unicharset;
UNICHARSET *unicharset;
OSBestResult best_result;
};
class OrientationDetector {
public:
OrientationDetector(const GenericVector<int>* allowed_scripts,
OSResults* results);
bool detect_blob(BLOB_CHOICE_LIST* scores);
public:
OrientationDetector(const std::vector<int> *allowed_scripts,
OSResults *results);
bool detect_blob(BLOB_CHOICE_LIST *scores);
int get_orientation();
private:
OSResults* osr_;
const GenericVector<int>* allowed_scripts_;
private:
OSResults *osr_;
const std::vector<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_;
public:
ScriptDetector(const std::vector<int> *allowed_scripts, OSResults *osr,
tesseract::Tesseract *tess);
void detect_blob(BLOB_CHOICE_LIST *scores);
bool must_stop(int orientation) const;
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_;
@@ -111,30 +114,28 @@ class ScriptDetector {
int hangul_id_;
int latin_id_;
int fraktur_id_;
tesseract::Tesseract* tess_;
const GenericVector<int>* allowed_scripts_;
tesseract::Tesseract *tess_;
const std::vector<int> *allowed_scripts_;
};
int orientation_and_script_detection(STRING& filename,
OSResults*,
tesseract::Tesseract*);
int orientation_and_script_detection(const char *filename, OSResults *,
tesseract::Tesseract *);
int os_detect(TO_BLOCK_LIST* port_blocks,
OSResults* osr,
tesseract::Tesseract* tess);
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);
int os_detect_blobs(const std::vector<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);
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);
TESS_API int OrientationIdToValue(const int &id);
#endif // TESSERACT_CCMAIN_OSDETECT_H_
} // namespace tesseract
#endif // TESSERACT_CCMAIN_OSDETECT_H_
+42 -40
View File
@@ -3,7 +3,6 @@
// Description: Iterator for tesseract page structure that avoids using
// tesseract internal data structures.
// Author: Ray Smith
// Created: Fri Feb 26 11:01:06 PST 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,18 +20,19 @@
#ifndef TESSERACT_CCMAIN_PAGEITERATOR_H_
#define TESSERACT_CCMAIN_PAGEITERATOR_H_
#include "export.h"
#include "publictypes.h"
#include "platform.h"
struct Pix;
struct Pta;
namespace tesseract {
struct BlamerBundle;
class C_BLOB_IT;
class PAGE_RES;
class PAGE_RES_IT;
class WERD;
struct Pix;
struct Pta;
namespace tesseract {
class Tesseract;
@@ -44,13 +44,13 @@ class Tesseract;
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
* See apitypes.h for the definition of PageIteratorLevel.
* See tesseract/publictypes.h for the definition of PageIteratorLevel.
* See also ResultIterator, derived from PageIterator, which adds in the
* ability to access OCR output with text-specific methods.
*/
class TESS_API PageIterator {
public:
public:
/**
* page_res and tesseract come directly from the BaseAPI.
* The rectangle parameters are copied indirectly from the Thresholder,
@@ -65,10 +65,9 @@ class TESS_API PageIterator {
* that tesseract has been given by the Thresholder.
* After the constructor, Begin has already been called.
*/
PageIterator(PAGE_RES* page_res, Tesseract* tesseract,
int scale, int scaled_yres,
int rect_left, int rect_top,
int rect_width, int rect_height);
PageIterator(PAGE_RES *page_res, Tesseract *tesseract, int scale,
int scaled_yres, int rect_left, int rect_top, int rect_width,
int rect_height);
virtual ~PageIterator();
/**
@@ -77,11 +76,11 @@ class TESS_API PageIterator {
* objects at a higher level. These constructors DO NOT CALL Begin, so
* iterations will continue from the location of src.
*/
PageIterator(const PageIterator& src);
const PageIterator& operator=(const PageIterator& src);
PageIterator(const PageIterator &src);
const PageIterator &operator=(const PageIterator &src);
/** Are we positioned at the same location as other? */
bool PositionedAtSameWord(const PAGE_RES_IT* other) const;
bool PositionedAtSameWord(const PAGE_RES_IT *other) const;
// ============= Moving around within the page ============.
@@ -203,24 +202,24 @@ class TESS_API PageIterator {
* from a grey image. The padding argument to GetImage can be used to expand
* the image to include more foreground pixels. See GetImage below.
*/
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;
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right,
int *bottom) const;
bool BoundingBox(PageIteratorLevel level, 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
* respect to the original image and is scaled by a factor scale_.
*/
bool BoundingBoxInternal(PageIteratorLevel level,
int* left, int* top, int* right, int* bottom) const;
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top,
int *right, int *bottom) const;
/** Returns whether there is no object of a given level. */
bool Empty(PageIteratorLevel level) const;
/**
* Returns the type of the current block. See apitypes.h for
* PolyBlockType.
* Returns the type of the current block.
* See tesseract/publictypes.h for PolyBlockType.
*/
PolyBlockType BlockType() const;
@@ -231,7 +230,7 @@ class TESS_API PageIterator {
* 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;
Pta *BlockPolygon() const;
/**
* Returns a binary image of the current object at the given level.
@@ -239,7 +238,7 @@ class TESS_API PageIterator {
* this could be upscaled with respect to the original input image.
* Use pixDestroy to delete the image after use.
*/
Pix* GetBinaryImage(PageIteratorLevel level) const;
Pix *GetBinaryImage(PageIteratorLevel level) const;
/**
* Returns an image of the current object at the given level in greyscale
@@ -252,8 +251,8 @@ class TESS_API PageIterator {
* 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* original_img,
int* left, int* top) const;
Pix *GetImage(PageIteratorLevel level, int padding, Pix *original_img,
int *left, int *top) const;
/**
* Returns the baseline of the current object at the given level.
@@ -261,8 +260,12 @@ class TESS_API PageIterator {
* WARNING: with vertical text, baselines may be vertical!
* Returns false if there is no baseline at the current position.
*/
bool Baseline(PageIteratorLevel level,
int* x1, int* y1, int* x2, int* y2) const;
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2,
int *y2) const;
// Returns the attributes of the current row.
void RowAttributes(float *row_height, float *descenders,
float *ascenders) const;
/**
* Returns orientation for the block the iterator points to.
@@ -306,8 +309,7 @@ class TESS_API PageIterator {
* of text.
*/
void ParagraphInfo(tesseract::ParagraphJustification *justification,
bool *is_list_item,
bool *is_crown,
bool *is_list_item, bool *is_crown,
int *first_line_indent) const;
// If the current WERD_RES (it_->word()) is not nullptr, sets the BlamerBundle
@@ -316,27 +318,27 @@ class TESS_API PageIterator {
// Can only be used when iterating on the word level.
bool SetWordBlamerBundle(BlamerBundle *blamer_bundle);
protected:
protected:
/**
* Sets up the internal data for iterating the blobs of a new word, then
* moves the iterator to the given offset.
*/
TESS_LOCAL void BeginWord(int offset);
void BeginWord(int offset);
/** Pointer to the page_res owned by the API. */
PAGE_RES* page_res_;
PAGE_RES *page_res_;
/** Pointer to the Tesseract object owned by the API. */
Tesseract* tesseract_;
Tesseract *tesseract_;
/**
* The iterator to the page_res_. Owned by this ResultIterator.
* A pointer just to avoid dragging in Tesseract includes.
*/
PAGE_RES_IT* it_;
PAGE_RES_IT *it_;
/**
* The current input WERD being iterated. If there is an output from OCR,
* then word_ is nullptr. Owned by the API
*/
WERD* word_;
WERD *word_;
/** The length of the current word_. */
int word_length_;
/** The current blob index within the word. */
@@ -346,7 +348,7 @@ class TESS_API PageIterator {
* OCR results in the box_word.
* Owned by this ResultIterator.
*/
C_BLOB_IT* cblob_it_;
C_BLOB_IT *cblob_it_;
/** Control over what to include in bounding boxes. */
bool include_upper_dots_;
bool include_lower_dots_;
@@ -359,6 +361,6 @@ class TESS_API PageIterator {
int rect_height_;
};
} // namespace tesseract.
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_PAGEITERATOR_H_
#endif // TESSERACT_CCMAIN_PAGEITERATOR_H_
-79
View File
@@ -1,79 +0,0 @@
///////////////////////////////////////////////////////////////////////
// File: platform.h
// Description: Place holder
// Author:
// Created:
//
// (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_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
#endif /* __GNUC__ */
#define SIGNED
#else
#ifdef __cplusplus
#include <climits>
#else /* C compiler*/
#include <limits.h>
#endif /* __cplusplus */
#ifndef PATH_MAX
#define MAX_PATH 4096
#else
#define MAX_PATH PATH_MAX
#endif
#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)
#elif defined(TESS_IMPORTS)
#define TESS_API __declspec(dllimport)
#else
#define TESS_API
#endif
#define TESS_LOCAL
#else
#if __GNUC__ >= 4
#if defined(TESS_EXPORTS) || defined(TESS_IMPORTS)
#define TESS_API __attribute__ ((visibility ("default")))
#define TESS_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define TESS_API
#define TESS_LOCAL
#endif
#else
#define TESS_API
#define TESS_LOCAL
#endif
#endif
#endif // TESSERACT_CCUTIL_PLATFORM_H_
+65 -68
View File
@@ -2,7 +2,6 @@
// File: publictypes.h
// Description: Types used in both the API and internally
// Author: Ray Smith
// Created: Wed Mar 03 09:22:53 PST 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,6 +19,8 @@
#ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H_
#define TESSERACT_CCSTRUCT_PUBLICTYPES_H_
namespace tesseract {
// 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
// dependencies, THIS FILE SHOULD NOT DEPEND ON ANY OTHER PART OF TESSERACT.
@@ -27,7 +28,6 @@
// but not for the low-level tesseract code to include top-level API code.
// This file should not use other Tesseract types, as that would drag
// their includes into the API-level.
// 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. */
constexpr int kPointsPerInch = 72;
@@ -47,25 +47,25 @@ constexpr int kResolutionEstimationFactor = 10;
/**
* Possible types for a POLY_BLOCK or ColPartition.
* Must be kept in sync with kPBColors in polyblk.cpp and PTIs*Type functions
* below, as well as kPolyBlockNames in publictypes.cpp.
* below, as well as kPolyBlockNames in layout_test.cc.
* Used extensively by ColPartition, and POLY_BLOCK.
*/
*/
enum PolyBlockType {
PT_UNKNOWN, // Type is not yet known. Keep as the first element.
PT_FLOWING_TEXT, // Text that lives inside a column.
PT_HEADING_TEXT, // Text that spans more than one column.
PT_PULLOUT_TEXT, // Text that is in a cross-column pull-out region.
PT_EQUATION, // Partition belonging to an equation region.
PT_INLINE_EQUATION, // Partition has inline equation.
PT_TABLE, // Partition belonging to a table region.
PT_VERTICAL_TEXT, // Text-line runs vertically.
PT_CAPTION_TEXT, // Text that belongs to an image.
PT_FLOWING_IMAGE, // Image that lives inside a column.
PT_HEADING_IMAGE, // Image that spans more than one column.
PT_PULLOUT_IMAGE, // Image that is in a cross-column pull-out region.
PT_HORZ_LINE, // Horizontal Line.
PT_VERT_LINE, // Vertical Line.
PT_NOISE, // Lies outside of any column.
PT_UNKNOWN, // Type is not yet known. Keep as the first element.
PT_FLOWING_TEXT, // Text that lives inside a column.
PT_HEADING_TEXT, // Text that spans more than one column.
PT_PULLOUT_TEXT, // Text that is in a cross-column pull-out region.
PT_EQUATION, // Partition belonging to an equation region.
PT_INLINE_EQUATION, // Partition has inline equation.
PT_TABLE, // Partition belonging to a table region.
PT_VERTICAL_TEXT, // Text-line runs vertically.
PT_CAPTION_TEXT, // Text that belongs to an image.
PT_FLOWING_IMAGE, // Image that lives inside a column.
PT_HEADING_IMAGE, // Image that spans more than one column.
PT_PULLOUT_IMAGE, // Image that is in a cross-column pull-out region.
PT_HORZ_LINE, // Horizontal Line.
PT_VERT_LINE, // Vertical Line.
PT_NOISE, // Lies outside of any column.
PT_COUNT
};
@@ -90,10 +90,6 @@ 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[];
namespace tesseract {
/**
* +------------------+ Orientation Example:
* | 1 Aaaa Aaaa Aaaa | ====================
@@ -131,7 +127,7 @@ enum Orientation {
*
* For English text, the writing direction is left-to-right. For the
* Chinese text in the above example, the writing direction is top-to-bottom.
*/
*/
enum WritingDirection {
WRITING_DIRECTION_LEFT_TO_RIGHT = 0,
WRITING_DIRECTION_RIGHT_TO_LEFT = 1,
@@ -148,7 +144,7 @@ enum WritingDirection {
*
* Note that only some combinations make sense. For example,
* WRITING_DIRECTION_LEFT_TO_RIGHT implies TEXTLINE_ORDER_TOP_TO_BOTTOM
*/
*/
enum TextlineOrder {
TEXTLINE_ORDER_LEFT_TO_RIGHT = 0,
TEXTLINE_ORDER_RIGHT_TO_LEFT = 1,
@@ -159,27 +155,28 @@ enum TextlineOrder {
* Possible modes for page layout analysis. These *must* be kept in order
* of decreasing amount of layout analysis to be done, except for OSD_ONLY,
* so that the inequality test macros below work.
*/
*/
enum PageSegMode {
PSM_OSD_ONLY, ///< Orientation and script detection only.
PSM_AUTO_OSD, ///< Automatic page segmentation with orientation and
///< script detection. (OSD)
PSM_AUTO_ONLY, ///< Automatic page segmentation, but no OSD, or OCR.
PSM_AUTO, ///< Fully automatic page segmentation, but no OSD.
PSM_SINGLE_COLUMN, ///< Assume a single column of text of variable sizes.
PSM_SINGLE_BLOCK_VERT_TEXT, ///< Assume a single uniform block of vertically
///< aligned text.
PSM_SINGLE_BLOCK, ///< Assume a single uniform block of text. (Default.)
PSM_SINGLE_LINE, ///< Treat the image as a single text line.
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_OSD_ONLY = 0, ///< Orientation and script detection only.
PSM_AUTO_OSD = 1, ///< Automatic page segmentation with orientation and
///< script detection. (OSD)
PSM_AUTO_ONLY = 2, ///< Automatic page segmentation, but no OSD, or OCR.
PSM_AUTO = 3, ///< Fully automatic page segmentation, but no OSD.
PSM_SINGLE_COLUMN = 4, ///< Assume a single column of text of variable sizes.
PSM_SINGLE_BLOCK_VERT_TEXT = 5, ///< Assume a single uniform block of
///< vertically aligned text.
PSM_SINGLE_BLOCK = 6, ///< Assume a single uniform block of text. (Default.)
PSM_SINGLE_LINE = 7, ///< Treat the image as a single text line.
PSM_SINGLE_WORD = 8, ///< Treat the image as a single word.
PSM_CIRCLE_WORD = 9, ///< Treat the image as a single word in a circle.
PSM_SINGLE_CHAR = 10, ///< Treat the image as a single character.
PSM_SPARSE_TEXT =
11, ///< Find as much text as possible in no particular order.
PSM_SPARSE_TEXT_OSD = 12, ///< Sparse text with orientation and script det.
PSM_RAW_LINE = 13, ///< Treat the image as a single text line, bypassing
///< hacks that are Tesseract-specific.
PSM_COUNT ///< Number of enum entries.
PSM_COUNT ///< Number of enum entries.
};
/**
@@ -187,7 +184,7 @@ enum PageSegMode {
* layout analysis are enabled.
* *Depend critically on the order of elements of PageSegMode.*
* NOTE that arg is an int for compatibility with INT_PARAM.
*/
*/
inline bool PSM_OSD_ENABLED(int pageseg_mode) {
return pageseg_mode <= PSM_AUTO_OSD || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
@@ -208,20 +205,20 @@ inline bool PSM_LINE_FIND_ENABLED(int pageseg_mode) {
}
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;
pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
/**
* enum of the elements of the page hierarchy, used in ResultIterator
* to provide functions that operate on each level without having to
* have 5x as many functions.
*/
*/
enum PageIteratorLevel {
RIL_BLOCK, // Block of text/image/separator line.
RIL_PARA, // Paragraph within a block.
RIL_TEXTLINE, // Line within a paragraph.
RIL_WORD, // Word within a textline.
RIL_SYMBOL // Symbol/character within a word.
RIL_BLOCK, // Block of text/image/separator line.
RIL_PARA, // Paragraph within a block.
RIL_TEXTLINE, // Line within a paragraph.
RIL_WORD, // Word within a textline.
RIL_SYMBOL // Symbol/character within a word.
};
/**
@@ -264,23 +261,23 @@ enum ParagraphJustification {
* appropriate changes to all the enums mirroring it (e.g. OCREngine in
* cityblock/workflow/detection/detection_storage.proto). Such enums will
* mention the connection to OcrEngineMode in the comments.
*/
*/
enum OcrEngineMode {
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
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.
} // namespace tesseract.
#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H_
#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H_
+179 -129
View File
@@ -18,12 +18,15 @@
#ifndef TESSERACT_API_RENDERER_H_
#define TESSERACT_API_RENDERER_H_
#include "export.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"
#include <string> // for std::string
#include <vector> // for std::vector
struct Pix;
namespace tesseract {
@@ -35,7 +38,7 @@ class TessBaseAPI;
* 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,
* For simplicity implementing this with tesseract 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
@@ -43,203 +46,250 @@ class TessBaseAPI;
* in addition to the heuristics for producing it.
*/
class TESS_API TessResultRenderer {
public:
virtual ~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);
// 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_; }
// 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);
/**
* 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);
/**
* 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();
/**
* 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(); }
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_; }
// Is everything fine? Otherwise something went wrong.
bool happy() const {
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_; }
/**
* 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);
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();
// 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;
// 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();
// 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 '\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);
// 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.
private:
TessResultRenderer *next_; // Can link multiple renderers together
FILE *fout_; // output file pointer
const char *file_extension_; // standard extension for generated output
std::string title_; // title of document being rendered
int imagenum_; // index of last image added
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:
public:
explicit TessTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
/**
* Renders tesseract output into an hocr text string
*/
class TESS_API TessHOcrRenderer : public TessResultRenderer {
public:
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();
protected:
bool BeginDocumentHandler() override;
bool AddImageHandler(TessBaseAPI *api) override;
bool EndDocumentHandler() override;
private:
bool font_info_; // whether to print font information
private:
bool font_info_; // whether to print font information
};
/**
* Renders tesseract output into an alto text string
*/
class TESS_API TessAltoRenderer : public TessResultRenderer {
public:
explicit TessAltoRenderer(const char *outputbase);
protected:
bool BeginDocumentHandler() override;
bool AddImageHandler(TessBaseAPI *api) override;
bool EndDocumentHandler() override;
private:
bool begin_document;
};
/**
* 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);
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();
protected:
bool BeginDocumentHandler() override;
bool AddImageHandler(TessBaseAPI *api) override;
bool EndDocumentHandler() override;
private:
bool font_info_; // whether to print font information
private:
bool font_info_; // whether to print font information
};
/**
* Renders tesseract output into searchable PDF
*/
class TESS_API TessPDFRenderer : public TessResultRenderer {
public:
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);
TessPDFRenderer(const char *outputbase, const char *datadir,
bool textonly = false);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
protected:
bool BeginDocumentHandler() override;
bool AddImageHandler(TessBaseAPI *api) override;
bool EndDocumentHandler() override;
private:
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
long int obj_; // counter for PDF objects
std::vector<long int> offsets_; // offset of every PDF object in bytes
std::vector<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);
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);
static bool imageToPDFObj(Pix *pix, const char *filename, long int objnum,
char **pdf_object, long int *pdf_object_size,
int jpg_quality);
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessUnlvRenderer : public TessResultRenderer {
public:
public:
explicit TessUnlvRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
/**
* Renders tesseract output into a plain UTF-8 text string for LSTMBox
*/
class TESS_API TessLSTMBoxRenderer : public TessResultRenderer {
public:
explicit TessLSTMBoxRenderer(const char *outputbase);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessBoxTextRenderer : public TessResultRenderer {
public:
public:
explicit TessBoxTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
/**
* Renders tesseract output into a plain UTF-8 text string in WordStr format
*/
class TESS_API TessWordStrBoxRenderer : public TessResultRenderer {
public:
explicit TessWordStrBoxRenderer(const char *outputbase);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
#ifndef DISABLED_LEGACY_ENGINE
@@ -248,15 +298,15 @@ class TESS_API TessBoxTextRenderer : public TessResultRenderer {
* Renders tesseract output into an osd text string
*/
class TESS_API TessOsdRenderer : public TessResultRenderer {
public:
explicit TessOsdRenderer(const char* outputbase);
public:
explicit TessOsdRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
protected:
bool AddImageHandler(TessBaseAPI *api) override;
};
#endif // ndef DISABLED_LEGACY_ENGINE
} // namespace tesseract.
} // namespace tesseract.
#endif // TESSERACT_API_RENDERER_H_
#endif // TESSERACT_API_RENDERER_H_
+37 -41
View File
@@ -4,7 +4,6 @@
// iterating in proper reading order over Bi Directional
// (e.g. mixed Hebrew and English) text.
// Author: David Eger
// Created: Fri May 27 13:58:06 PST 2011
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,38 +21,32 @@
#ifndef TESSERACT_CCMAIN_RESULT_ITERATOR_H_
#define TESSERACT_CCMAIN_RESULT_ITERATOR_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
#include "export.h" // for TESS_API, TESS_LOCAL
#include "ltrresultiterator.h" // for LTRResultIterator
#include "publictypes.h" // for PageIteratorLevel
#include "unichar.h" // for StrongScriptDirection
template <typename T> class GenericVector;
template <typename T> class GenericVectorEqEq;
class STRING;
#include <set> // for std::pair
#include <vector> // for std::vector
namespace tesseract {
class Tesseract;
class TESS_API ResultIterator : public LTRResultIterator {
public:
public:
static ResultIterator *StartOfParagraph(const LTRResultIterator &resit);
/**
* ResultIterator is copy constructible!
* The default copy constructor works just fine for us.
*/
virtual ~ResultIterator() = default;
~ResultIterator() override = default;
// ============= Moving around within the page ============.
/**
* Moves the iterator to point to the start of the page to begin
* an iteration.
*/
virtual void Begin();
void Begin() override;
/**
* Moves to the start of the next object at the given level in the
@@ -67,7 +60,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
* This function iterates words in right-to-left scripts correctly, if
* the appropriate language has been loaded into Tesseract.
*/
virtual bool Next(PageIteratorLevel level);
bool Next(PageIteratorLevel level) override;
/**
* IsAtBeginningOf() returns whether we're at the logical beginning of the
@@ -75,15 +68,15 @@ class TESS_API ResultIterator : public LTRResultIterator {
* order). Otherwise, this acts the same as PageIterator::IsAtBeginningOf().
* For a full description, see pageiterator.h
*/
virtual bool IsAtBeginningOf(PageIteratorLevel level) const;
bool IsAtBeginningOf(PageIteratorLevel level) const override;
/**
* Implement PageIterator's IsAtFinalElement correctly in a BiDi context.
* For instance, IsAtFinalElement(RIL_PARA, RIL_WORD) returns whether we
* point at the last word in a paragraph. See PageIterator for full comment.
*/
virtual bool IsAtFinalElement(PageIteratorLevel level,
PageIteratorLevel element) const;
*/
bool IsAtFinalElement(PageIteratorLevel level,
PageIteratorLevel element) const override;
// ============= Functions that refer to words only ============.
// Returns the number of blanks before the current word.
@@ -94,18 +87,21 @@ class TESS_API ResultIterator : public LTRResultIterator {
/**
* Returns the null terminated UTF-8 encoded text string for the current
* object at the given level. Use delete [] to free after use.
*/
virtual char* GetUTF8Text(PageIteratorLevel level) const;
*/
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;
*/
virtual std::vector<std::vector<std::vector<std::pair<const char *, float>>>>
*GetRawLSTMTimesteps() const;
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).
*/
*/
bool ParagraphIsLtr() const;
// ============= Exposed only for testing =============.
@@ -134,23 +130,23 @@ class TESS_API ResultIterator : public LTRResultIterator {
*/
static void CalculateTextlineOrder(
bool paragraph_is_ltr,
const GenericVector<StrongScriptDirection> &word_dirs,
GenericVectorEqEq<int> *reading_order);
const std::vector<StrongScriptDirection> &word_dirs,
std::vector<int> *reading_order);
static const int kMinorRunStart;
static const int kMinorRunEnd;
static const int kComplexWord;
protected:
protected:
/**
* We presume the data associated with the given iterator will outlive us.
* NB: This is private because it does something that is non-obvious:
* it resets to the beginning of the paragraph instead of staying wherever
* resit might have pointed.
*/
TESS_LOCAL explicit ResultIterator(const LTRResultIterator &resit);
explicit ResultIterator(const LTRResultIterator &resit);
private:
private:
/**
* Calculates the current paragraph's dominant writing direction.
* Typically, members should use current_paragraph_ltr_ instead.
@@ -170,12 +166,12 @@ class TESS_API ResultIterator : public LTRResultIterator {
*/
void CalculateTextlineOrder(bool paragraph_is_ltr,
const LTRResultIterator &resit,
GenericVectorEqEq<int> *indices) const;
std::vector<int> *indices) const;
/** 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,
GenericVectorEqEq<int> *indices) const;
std::vector<StrongScriptDirection> *ssd,
std::vector<int> *indices) const;
/**
* What is the index of the current word in a strict left-to-right reading
@@ -187,7 +183,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
* Given an iterator pointing at a word, returns the logical reading order
* of blob indices for the word.
*/
void CalculateBlobOrder(GenericVector<int> *blob_indices) const;
void CalculateBlobOrder(std::vector<int> *blob_indices) const;
/** Precondition: current_paragraph_is_ltr_ is set. */
void MoveToLogicalStartOfTextline();
@@ -208,10 +204,10 @@ class TESS_API ResultIterator : public LTRResultIterator {
* Append any extra marks that should be appended to this word when printed.
* Mostly, these are Unicode BiDi control characters.
*/
void AppendSuffixMarks(STRING *text) const;
void AppendSuffixMarks(std::string *text) const;
/** Appends the current word in reading order to the given buffer.*/
void AppendUTF8WordText(STRING *text) const;
void AppendUTF8WordText(std::string *text) const;
/**
* Appends the text of the current text line, *assuming this iterator is
@@ -220,7 +216,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
* Each textline is terminated in a single newline character.
* If the textline ends a paragraph, it gets a second terminal newline.
*/
void IterateAndAppendUTF8TextlineText(STRING *text);
void IterateAndAppendUTF8TextlineText(std::string *text);
/**
* Appends the text of the current paragraph in reading order
@@ -228,7 +224,7 @@ class TESS_API ResultIterator : public LTRResultIterator {
* Each textline is terminated in a single newline character, and the
* paragraph gets an extra newline at the end.
*/
void AppendUTF8ParagraphText(STRING *text) const;
void AppendUTF8ParagraphText(std::string *text) const;
/** Returns whether the bidi_debug flag is set to at least min_level. */
bool BidiDebug(int min_level) const;
@@ -251,6 +247,6 @@ class TESS_API ResultIterator : public LTRResultIterator {
bool preserve_interword_spaces_;
};
} // namespace tesseract.
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H_
#endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H_
-162
View File
@@ -1,162 +0,0 @@
/**********************************************************************
* File: serialis.h (Formerly serialmac.h)
* Description: Inline routines and macros for serialisation functions
* Author: Phil Cheatle
* Created: Tue Oct 08 08:33:12 BST 1991
*
* (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 SERIALIS_H
#define SERIALIS_H
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include "host.h"
template <typename T> class GenericVector;
class STRING;
/***********************************************************************
QUOTE_IT MACRO DEFINITION
===========================
Replace <parm> with "<parm>". <parm> may be an arbitrary number of tokens
***********************************************************************/
#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
-181
View File
@@ -1,181 +0,0 @@
/**********************************************************************
* File: strngs.h (Formerly strings.h)
* Description: STRING class definition.
* 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");
** 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 STRNGS_H
#define STRNGS_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.
// This allows the string to ensure internal integrity and maintain
// its own string length. Unfortunately this is not possible because
// STRINGS are used as direct-manipulation data buffers for things
// like length arrays and many places cast away the const on string()
// to mutate the string. Turning this off means that internally we
// cannot assume we know the strlen.
#define STRING_IS_PROTECTED 0
template <typename T> class GenericVector;
class TESS_API STRING
{
public:
STRING();
STRING(const STRING &string);
STRING(const char *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);
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_t len = length() + 1;
return strncpy(new char[len], GetCStr(), len);
}
#if STRING_IS_PROTECTED
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_t index, const char*s, int len);
void erase_range(int32_t index, int len);
#else
char &operator[] (int32_t index) const;
#endif
void split(const char c, GenericVector<STRING> *splited);
void truncate_at(int32_t index);
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);
STRING operator+ (const STRING & string) const;
STRING operator+ (const char ch) const;
STRING & operator+= (const char *string);
STRING & operator+= (const STRING & string);
STRING & operator+= (const char ch);
// Assignment for strings which are not null-terminated.
void assign(const char *cstr, int len);
// Appends the given string and int (as a %d) to this.
// += cannot be used for ints as there as a char += operator that would
// 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 capacity but keep pointer encapsulated
inline void ensure(int32_t min_capacity) { ensure_cstr(min_capacity); }
private:
typedef struct STRING_HEADER {
// How much space was allocated in the string buffer for char data.
int capacity_;
// used_ is how much of the capacity is currently being used,
// including a '\0' terminator.
//
// 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 nullptr) but needs to be computed.
// this condition is set when encapsulation is violated because
// an API returned a mutable string.
//
// capacity_ - used_ = excess capacity that the string can grow
// without reallocating
mutable int used_;
} STRING_HEADER;
// To preserve the behavior of the old serialization, we only have space
// for one pointer in this structure. So we are embedding a data structure
// at the start of the storage that will hold additional state variables,
// then storing the actual string contents immediately after.
STRING_HEADER* data_;
// returns the header part of the storage
inline STRING_HEADER* GetHeader() {
return data_;
}
inline const STRING_HEADER* GetHeader() const {
return data_;
}
// returns the string data part of storage
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() == nullptr) : (GetHeader()->used_ == (strlen(string()) + 1));
#else
return true;
#endif
}
// 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_t min_capacity);
void FixHeader() const; // make used_ non-negative, even if const
char* AllocData(int used, int capacity);
void DiscardData();
};
#endif
File diff suppressed because it is too large. Load diff
-190
View File
@@ -1,190 +0,0 @@
///////////////////////////////////////////////////////////////////////
// File: thresholder.h
// Description: Base API for thresolding images in tesseract.
// Author: Ray Smith
// Created: Mon May 12 11:00:15 PDT 2008
//
// (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_THRESHOLDER_H_
#define TESSERACT_CCMAIN_THRESHOLDER_H_
#include "platform.h"
#include "publictypes.h"
struct Pix;
namespace tesseract {
/// Base class for all tesseract image thresholding classes.
/// Specific classes can add new thresholding methods by
/// overriding ThresholdToPix.
/// 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 TESS_API ImageThresholder {
public:
ImageThresholder();
virtual ~ImageThresholder();
/// Destroy the Pix if there is one, freeing memory.
virtual void Clear();
/// Return true if no image has been set.
bool IsEmpty() const;
/// 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.
/// Binary images of 1 bit per pixel may also be given but they must be
/// byte packed with the MSB of the first byte being the first pixel, and a
/// one pixel is WHITE. For binary images set bytes_per_pixel=0.
void SetImage(const unsigned char* imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line);
/// Store the coordinates of the rectangle to process for later use.
/// Doesn't actually do any thresholding.
void SetRectangle(int left, int top, int width, int height);
/// Get enough parameters to be able to rebuild bounding boxes in the
/// original image (not just within the rectangle).
/// Left and top are enough with top-down coordinates, but
/// the height of the rectangle and the image are needed for bottom-up.
virtual void GetImageSizes(int* left, int* top, int* width, int* height,
int* imagewidth, int* imageheight);
/// Return true if the source image is color.
bool IsColor() const {
return pix_channels_ >= 3;
}
/// Returns true if the source image is binary.
bool IsBinary() const {
return pix_channels_ == 0;
}
int GetScaleFactor() const {
return scale_;
}
// Set the resolution of the source image in pixels per inch.
// This should be called right after SetImage(), and will let us return
// appropriate font sizes for the text.
void SetSourceYResolution(int ppi) {
yres_ = ppi;
estimated_res_ = ppi;
}
int GetSourceYResolution() const {
return yres_;
}
int GetScaledYResolution() const {
return scale_ * yres_;
}
// Set the resolution of the source image in pixels per inch, as estimated
// by the thresholder from the text size found during thresholding.
// This value will be used to set internal size thresholds during recognition
// and will not influence the output "point size." The default value is
// the same as the source resolution. (yres_)
void SetEstimatedResolution(int ppi) {
estimated_res_ = ppi;
}
// Returns the estimated resolution, including any active scaling.
// This value will be used to set internal size thresholds during recognition.
int GetScaledEstimatedResolution() const {
return scale_ * estimated_res_;
}
/// 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.
/// 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.
/// 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* GetPixRect();
// 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:
// ----------------------------------------------------------------------
// Utility functions that may be useful components for other thresholders.
/// Common initialization shared between SetImage methods.
virtual void Init();
/// Return true if we are processing the full image.
bool IsFullImage() const {
return rect_left_ == 0 && rect_top_ == 0 &&
rect_width_ == image_width_ && rect_height_ == image_height_;
}
// 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 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;
protected:
/// Clone or other copy of the source Pix.
/// The pix will always be PixDestroy()ed on destruction of the class.
Pix* 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.
int estimated_res_; //< Resolution estimate from text size.
int rect_left_;
int rect_top_;
int rect_width_;
int rect_height_;
};
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_THRESHOLDER_H_
+39 -38
View File
@@ -2,7 +2,6 @@
// File: unichar.h
// Description: Unicode character/ligature class.
// Author: Ray Smith
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,17 +19,19 @@
#ifndef TESSERACT_CCUTIL_UNICHAR_H_
#define TESSERACT_CCUTIL_UNICHAR_H_
#include "export.h"
#include <memory.h>
#include <cstring>
#include <string>
#include <vector>
#include "platform.h"
namespace tesseract {
// 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.
using UNICHAR_ID = int;
@@ -40,23 +41,21 @@ static const int INVALID_UNICHAR_ID = -1;
static const char INVALID_UNICHAR[] = "__INVALID_UNICHAR__";
enum StrongScriptDirection {
DIR_NEUTRAL = 0, // Text contains only neutral characters.
DIR_LEFT_TO_RIGHT = 1, // Text contains no Right-to-Left characters.
DIR_RIGHT_TO_LEFT = 2, // Text contains no Left-to-Right characters.
DIR_MIX = 3, // Text contains a mixture of left-to-right
// and right-to-left characters.
DIR_NEUTRAL = 0, // Text contains only neutral characters.
DIR_LEFT_TO_RIGHT = 1, // Text contains no Right-to-Left characters.
DIR_RIGHT_TO_LEFT = 2, // Text contains no Left-to-Right characters.
DIR_MIX = 3, // Text contains a mixture of left-to-right
// 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
// multiple Unicode characters representing the NFKC expansion of a ligature
// such as fi, ffl etc. These are also stored as utf8.
class UNICHAR {
public:
class TESS_API UNICHAR {
public:
UNICHAR() {
memset(chars, 0, UNICHAR_LEN);
}
@@ -64,7 +63,7 @@ class UNICHAR {
// Construct from a utf8 string. If len<0 then the string is null terminated.
// If the string is too long to fit in the UNICHAR then it takes only what
// will fit.
UNICHAR(const char* utf8_str, int len);
UNICHAR(const char *utf8_str, int len);
// Construct from a single UCS4 character.
explicit UNICHAR(int unicode);
@@ -77,19 +76,19 @@ class UNICHAR {
// Get the length of the UTF8 string.
int utf8_len() const {
int len = chars[UNICHAR_LEN - 1];
return len >=0 && len < UNICHAR_LEN ? len : UNICHAR_LEN;
return len >= 0 && len < UNICHAR_LEN ? len : UNICHAR_LEN;
}
// Get a UTF8 string, but NOT nullptr terminated.
const char* utf8() const {
const char *utf8() const {
return chars;
}
// Get a terminated UTF8 string: Must delete[] it after use.
char* utf8_str() const;
char *utf8_str() const;
// Get the number of bytes in the first character of the given utf8 string.
static int utf8_step(const char* utf8_str);
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
@@ -105,15 +104,15 @@ class UNICHAR {
// int char_len = it.get_utf8(buf); buf[char_len] = '\0';
// tprintf("Char = %s\n", buf);
// }
class const_iterator {
using CI = const_iterator ;
class TESS_API const_iterator {
using CI = const_iterator;
public:
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++();
// 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
@@ -125,7 +124,7 @@ class UNICHAR {
// 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;
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;
@@ -133,43 +132,45 @@ class UNICHAR {
bool is_legal() const;
// Return the pointer into the string at the current position.
const char* utf8_data() const { return it_; }
const char *utf8_data() const {
return it_;
}
// Iterator equality operators.
friend bool operator==(const CI& lhs, const CI& rhs) {
friend bool operator==(const CI &lhs, const CI &rhs) {
return lhs.it_ == rhs.it_;
}
friend bool operator!=(const CI& lhs, const CI& rhs) {
friend bool operator!=(const CI &lhs, const CI &rhs) {
return !(lhs == rhs);
}
private:
private:
friend class UNICHAR;
explicit const_iterator(const char* it) : it_(it) {}
explicit const_iterator(const char *it) : it_(it) {}
const char* it_; // Pointer into the string.
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);
static const_iterator begin(const char *utf8_str, int byte_length);
static const_iterator end(const char *utf8_str, 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);
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);
static std::string UTF32ToUTF8(const std::vector<char32> &str32);
private:
private:
// A UTF-8 representation of 1 or more Unicode characters.
// The last element (chars[UNICHAR_LEN - 1]) is a length if
// its value < UNICHAR_LEN, otherwise it is a genuine character.
char chars[UNICHAR_LEN];
char chars[UNICHAR_LEN]{};
};
} // namespace tesseract
} // namespace tesseract
#endif // TESSERACT_CCUTIL_UNICHAR_H_
#endif // TESSERACT_CCUTIL_UNICHAR_H_
@@ -18,13 +18,19 @@
#ifndef TESSERACT_API_VERSION_H_
#define TESSERACT_API_VERSION_H_
#define TESSERACT_MAJOR_VERSION 4
// clang-format off
#define TESSERACT_MAJOR_VERSION 5
#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_
#define TESSERACT_VERSION \
(TESSERACT_MAJOR_VERSION << 16 | \
TESSERACT_MINOR_VERSION << 8 | \
TESSERACT_MICRO_VERSION)
#define TESSERACT_VERSION_STR "5.0.0"
// clang-format on
#endif // TESSERACT_API_VERSION_H_