diff --git a/Tesseract/include/tesseract/apitypes.h b/Tesseract/include/tesseract/apitypes.h new file mode 100644 index 0000000..2cb38ad --- /dev/null +++ b/Tesseract/include/tesseract/apitypes.h @@ -0,0 +1,33 @@ +/////////////////////////////////////////////////////////////////////// +// File: apitypes.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"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////// + +#ifndef TESSERACT_API_APITYPES_H__ +#define TESSERACT_API_APITYPES_H__ + +#include "publictypes.h" + +// 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__ diff --git a/Tesseract/include/tesseract/baseapi.h b/Tesseract/include/tesseract/baseapi.h new file mode 100644 index 0000000..a52c41d --- /dev/null +++ b/Tesseract/include/tesseract/baseapi.h @@ -0,0 +1,793 @@ +/////////////////////////////////////////////////////////////////////// +// File: baseapi.h +// Description: Simple API for calling tesseract. +// Author: Ray Smith +// Created: Fri Oct 06 15:35:01 PDT 2006 +// +// (C) Copyright 2006, Google Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////// + +#ifndef TESSERACT_API_BASEAPI_H__ +#define TESSERACT_API_BASEAPI_H__ + +#include +// To avoid collision with other typenames include the ABSOLUTE MINIMUM +// complexity of includes here. Use forward declarations wherever possible +// and hide includes of complex types in baseapi.cpp. +#include "platform.h" +#include "apitypes.h" +#include "thresholder.h" +#include "unichar.h" +#include "tesscallback.h" +#include "publictypes.h" +#include "pageiterator.h" +#include "resultiterator.h" + +template class GenericVector; +class PAGE_RES; +class PAGE_RES_IT; +class ParagraphModel; +class BlamerBundle; +class BLOCK_LIST; +class DENORM; +class IMAGE; +class MATRIX; +class PBLOB; +class ROW; +class STRING; +class WERD; +struct Pix; +struct Box; +struct Pixa; +struct Boxa; +class ETEXT_DESC; +struct OSResults; +class TBOX; +class UNICHARSET; + +// From oldlist.h +// TODO(antonova): remove when oldlist is deprecated. +struct list_rec; +typedef list_rec *LIST; + +#define MAX_NUM_INT_FEATURES 512 +struct INT_FEATURE_STRUCT; +typedef INT_FEATURE_STRUCT *INT_FEATURE; +typedef INT_FEATURE_STRUCT INT_FEATURE_ARRAY[MAX_NUM_INT_FEATURES]; +struct TBLOB; + +namespace tesseract { + +class CubeRecoContext; +class Dawg; +class Dict; +class EquationDetect; +class LTRResultIterator; +class MutableIterator; +class Tesseract; +class Trie; +class Wordrec; + +typedef int (Dict::*DictFunc)(void* void_dawg_args, + 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 void (Wordrec::*FillLatticeFunc)(const MATRIX &ratings, + const LIST &best_choices, + const UNICHARSET &unicharset, + BlamerBundle *blamer_bundle); +typedef TessCallback3 TruthCallback; + +/** + * Base class for all tesseract APIs. + * Specific classes can add ability to work on different inputs or produce + * different outputs. + * This class is mostly an interface layer on top of the Tesseract instance + * class to hide the data types so that users of this class don't have to + * include any other Tesseract headers. + */ +class TESS_API TessBaseAPI { + public: + TessBaseAPI(); + virtual ~TessBaseAPI(); + + /** + * Returns the version identifier as a static string. Do not delete. + */ + static const char* Version(); + + /** + * Set the name of the input file. Needed only for training and + * reading a UNLV zone file. + */ + void SetInputName(const char* name); + + /** Set the name of the bonus output files. Needed only for debugging. */ + void SetOutputName(const char* name); + + /** + * Set the value of an internal "parameter." + * Supply the name of the parameter and the value as a string, just as + * you would in a config file. + * Returns false if the name lookup failed. + * Eg SetVariable("tessedit_char_blacklist", "xyz"); to ignore x, y and z. + * Or SetVariable("classify_bln_numeric_mode", "1"); to set numeric-only mode. + * SetVariable may be used before Init, but settings will revert to + * defaults on End(). + * TODO(rays) Add a command-line option to dump the parameters to stdout + * and add a pointer to it in the FAQ + * + * Note: Must be called after Init(). Only works for non-init variables + * (init variables should be passed to Init()). + */ + 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. + * Fills in value with the value of the parameter. + */ + bool GetIntVariable(const char *name, int *value) const; + bool GetBoolVariable(const char *name, bool *value) const; + bool GetDoubleVariable(const char *name, double *value) const; + + /** + * Returns the pointer to the string that represents the value of the + * parameter if it was found among Tesseract parameters. + */ + const char *GetStringVariable(const char *name) const; + + /** + * Print Tesseract parameters to the given file. + */ + void PrintVariables(FILE *fp) const; + + /** + * Get value of named variable as a string, if it exists. + */ + bool GetVariableAsString(const char *name, STRING *val); + + /** + * Instances are now mostly thread-safe and totally independent, + * but some global parameters remain. Basically it is safe to use multiple + * TessBaseAPIs in different threads in parallel, UNLESS: + * you use SetVariable on some of the Params in classify and textord. + * If you do, then the effect will be to change it for all your instances. + * + * Start tesseract. Returns zero on success and -1 on failure. + * 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 NULL 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 [~][+[~]]* indicating + * that multiple languages are to be loaded. Eg hin+eng will load Hindi and + * English. Languages may specify internally that they want to be loaded + * with one or more other languages, so the ~ sign is available to override + * that. Eg if hin were set to load eng by default, then hin+~eng would force + * loading only hin. The number of loaded languages is limited only by + * memory, with the caveat that loading additional languages will impact + * both speed and accuracy, as there is more work to do to decide on the + * applicable language, and there is more chance of hallucinating incorrect + * words. + * WARNING: On changing languages, all Tesseract parameters are reset + * back to their default values. (Which may vary between languages.) + * If you have a rare need to set a Variable that controls + * initialization for a second call to Init you should explicitly + * call End() and then use SetVariable before Init. This is only a very + * rare use case, since there are very few uses that require any parameters + * to be set before Init. + * + * 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, + char **configs, int configs_size, + const GenericVector *vars_vec, + const GenericVector *vars_values, + bool set_only_non_debug_params); + int Init(const char* datapath, const char* language, OcrEngineMode oem) { + return Init(datapath, language, oem, NULL, 0, NULL, NULL, false); + } + int Init(const char* datapath, const char* language) { + return Init(datapath, language, OEM_DEFAULT, NULL, 0, NULL, NULL, false); + } + + /** + * Returns the languages string used in the last valid initialization. + * If the last initialization specified "deu+hin" then that will be + * returned. If hin loaded eng automatically as well, then that will + * not be included in this list. To find the languages actually + * loaded use GetLoadedLanguagesAsVector. + * The returned string should NOT be deleted. + */ + const char* GetInitLanguagesAsString() const; + + /** + * Returns the loaded languages in the vector of STRINGs. + * Includes all languages loaded by the last Init, including those loaded + * as dependencies of other loaded languages. + */ + void GetLoadedLanguagesAsVector(GenericVector* langs) const; + + /** + * Returns the available languages in the vector of STRINGs. + */ + void GetAvailableLanguagesAsVector(GenericVector* 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); + + /** + * Init only for page layout analysis. Use only for calls to SetImage and + * AnalysePage. Calls that attempt recognition will generate an error. + */ + void InitForAnalysePage(); + + /** + * Read a "config" file containing a set of param, value pairs. + * Searches the standard places: tessdata/configs, tessdata/tessconfigs + * 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); + /** Same as above, but only set debug params from the given config file. */ + void ReadDebugConfigFile(const char* filename); + + /** + * Set the current page segmentation mode. Defaults to PSM_SINGLE_BLOCK. + * The mode is stored as an IntParam so it can also be modified by + * ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string). + */ + void SetPageSegMode(PageSegMode mode); + + /** Return the current page segmentation mode. */ + PageSegMode GetPageSegMode() const; + + /** + * Recognize a rectangle from an image and return the result as a string. + * May be called many times for a single Init. + * Currently has no error checking. + * 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 + * 1 represents WHITE. For binary images set bytes_per_pixel=0. + * The recognized text is returned as a char* which is coded + * as UTF8 and must be freed with the delete [] operator. + * + * Note that TesseractRect is the simplified convenience interface. + * 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); + + /** + * Call between pages or documents etc to free up memory and forget + * adaptive data. + */ + void ClearAdaptiveClassifier(); + + /** + * @defgroup AdvancedAPI Advanced API + * The following methods break TesseractRect into pieces, so you can + * 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 + * TesseractRect above. Does not copy the image buffer, or take + * ownership. The source image may be destroyed after Recognize is called, + * either explicitly or implicitly via one of the Get*Text functions. + * SetImage clears all recognition results, and sets the rectangle to the + * full image, so it may be followed immediately by a GetUTF8Text, and it + * will automatically perform recognition. + */ + void SetImage(const unsigned char* imagedata, int width, int height, + int bytes_per_pixel, int bytes_per_line); + + /** + * Provide an image for Tesseract to recognize. As with SetImage above, + * Tesseract doesn't take a copy or ownership or pixDestroy the image, so + * it must persist until after Recognize. + * Pix vs raw, which to use? + * Use Pix where possible. A future version of Tesseract may choose to use Pix + * as its internal representation and discard IMAGE altogether. + * Because of that, an implementation that sources and targets Pix may end up + * with less copies than an implementation that does not. + */ + void SetImage(const Pix* pix); + + /** + * Set the resolution of the source image in pixels per inch so font size + * information can be calculated in results. Call this after SetImage(). + */ + void SetSourceResolution(int ppi); + + /** + * Restrict recognition to a sub-rectangle of the image. Call after SetImage. + * Each SetRectangle clears the recogntion results so multiple rectangles + * can be recognized with the same image. + */ + 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) { + if (thresholder_ != NULL) + 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(); + + /** + * 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); + + /** + * Get the textlines as a leptonica-style + * Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each line is also returned + * as an array of one element per line. delete [] after use. + */ + Boxa* GetTextlines(Pixa** pixa, int** blockids); + + /** + * Get textlines and strips of image regions as a leptonica-style Boxa, Pixa + * pair, in reading order. Enables downstream handling of non-rectangular + * regions. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each line is also returned as an + * array of one element per line. delete [] after use. + */ + 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); + + /** + * Gets the individual connected (text) components (created + * after pages segmentation step, but before recognition) + * as a leptonica-style Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * Note: the caller is responsible for calling boxaDestroy() + * on the returned Boxa array and pixaDestroy() on cc array. + */ + Boxa* GetConnectedComponents(Pixa** cc); + + /** + * Get the given level kind of components (block, textline, word etc.) as a + * leptonica-style Boxa, Pixa pair, in reading order. + * Can be called before or after Recognize. + * If blockids is not NULL, the block-id of each component is also returned + * as an array of one element per component. delete [] after use. + * If text_only is true, then only text components are returned. + */ + Boxa* GetComponentImages(PageIteratorLevel level, + bool text_only, + Pixa** pixa, int** blockids); + + /** + * Returns the scale factor of the thresholded image that would be returned by + * GetThresholdedImage() and the various GetX() methods that call + * GetComponentImages(). + * Returns 0 if no thresholder has been set. + */ + int GetThresholdedImageScaleFactor() const; + + /** + * Dump the internal binary image to a PGM file. + * @deprecated Use GetThresholdedImage and write the image using pixWrite + * instead if possible. + */ + void DumpPGM(const char* filename); + + /** + * Runs page layout analysis in the mode set by SetPageSegMode. + * May optionally be called prior to Recognize to get access to just + * the page layout results. Returns an iterator to the results. + * Returns NULL on error. + * The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * 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(); + + /** + * Recognize the image from SetAndThresholdImage, generating Tesseract + * internal structures. Returns 0 on success. + * 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); + + /** + * Methods to retrieve information after SetAndThresholdImage(), + * Recognize() or TesseractRect(). (Recognize is called implicitly if needed.) + */ + + /** Variant on Recognize used for testing chopper. */ + int RecognizeForChopTest(ETEXT_DESC* monitor); + + /** + * Recognizes all the pages in the named file, as a multi-page tiff or + * list of filenames, or single image, and gets the appropriate kind of text + * according to parameters: tessedit_create_boxfile, + * tessedit_make_boxes_from_boxes, tessedit_write_unlv, tessedit_create_hocr. + * Calls ProcessPage on each page in the input file, which may be a + * multi-page tiff, single-page other file format, or a plain text list of + * images to read. If tessedit_page_number is non-negative, processing begins + * at that page of a multi-page tiff file, or filelist. + * The text is returned in text_out. Returns false on error. + * If non-zero timeout_millisec terminates processing after the timeout on + * a single page. + * If non-NULL and non-empty, and some page fails for some reason, + * the page is reprocessed with the retry_config config file. Useful + * for interactively debugging a bad page. + */ + bool ProcessPages(const char* filename, + const char* retry_config, int timeout_millisec, + STRING* text_out); + + /** + * Recognizes a single page for ProcessPages, appending the text to text_out. + * The pix is the image processed - filename and page_index are metadata + * used by side-effect processes, such as reading a box file or formatting + * as hOCR. + * If non-zero timeout_millisec terminates processing after the timeout. + * If non-NULL and non-empty, and some page fails for some reason, + * the page is reprocessed with the retry_config config file. Useful + * for interactively debugging a bad page. + * The text is returned in text_out. Returns false on error. + */ + bool ProcessPage(Pix* pix, int page_index, const char* filename, + const char* retry_config, int timeout_millisec, + STRING* text_out); + + /** + * Get a reading-order iterator to the results of LayoutAnalysis and/or + * Recognize. The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * 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(); + + /** + * Get a mutable iterator to the results of LayoutAnalysis and/or Recognize. + * The returned iterator must be deleted after use. + * WARNING! This class points to data held within the TessBaseAPI class, and + * therefore can only be used while the TessBaseAPI class still exists and + * 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(); + + /** + * The recognized text is returned as a char* which is coded + * as UTF8 and must be freed with the delete [] operator. + */ + char* GetUTF8Text(); + + /** + * Make a HTML-formatted string with hOCR markup from the internal + * data structures. + * page_number is 0-based but will appear in the output as 1-based. + */ + char* GetHOCRText(int page_number); + /** + * The recognized text is returned as a char* which is coded in the same + * format as a box file used in training. Returned string must be freed with + * the delete [] operator. + * 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. + */ + char* GetBoxText(int page_number); + /** + * The recognized text is returned as a char* which is coded + * as UNLV format Latin-1 with specific reject and suspect codes + * and must be freed with the delete [] operator. + */ + char* GetUNLVText(); + /** Returns the (average) confidence value between 0 and 100. */ + int MeanTextConf(); + /** + * Returns all word confidences (between 0 and 100) in an array, terminated + * by -1. The calling function must delete [] after use. + * The number of confidences should correspond to the number of space- + * delimited words in GetUTF8Text. + */ + int* AllWordConfidences(); + + /** + * Applies the given word to the adaptive classifier if possible. + * The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can + * tell the boundaries of the graphemes. + * Assumes that SetImage/SetRectangle have been used to set the image + * to the given word. The mode arg should be PSM_SINGLE_WORD or + * PSM_CIRCLE_WORD, as that will be used to control layout analysis. + * The currently set PageSegMode is preserved. + * Returns false if adaption was not possible for some reason. + */ + bool AdaptToWordStr(PageSegMode mode, const char* wordstr); + + /** + * Free up recognition results and any stored image data, without actually + * freeing any recognition data that would be time-consuming to reload. + * Afterwards, you must call SetImage or TesseractRect before doing + * any Recognize or Get* operation. + */ + void Clear(); + + /** + * Close down tesseract and free up all memory. End() is equivalent to + * destructing and reconstructing your TessBaseAPI. + * Once End() has been used, none of the other API functions may be used + * other than Init and anything declared above it in the class definition. + */ + void End(); + + /** + * Check whether a word is valid according to Tesseract's language model + * @return 0 if the word is invalid, non-zero if valid. + * @warning temporary! This function will be removed from here and placed + * in a separate API at some future time. + */ + int IsValidWord(const char *word); + + bool GetTextDirection(int* out_offset, float* out_slope); + + /** Sets Dict::letter_is_okay_ function to point to the given function. */ + void SetDictFunc(DictFunc f); + + /** Sets Dict::probability_in_context_ function to point to the given + * function. + */ + void SetProbabilityInContextFunc(ProbabilityInContextFunc f); + + /** Sets Wordrec::fill_lattice_ function to point to the given function. */ + void SetFillLatticeFunc(FillLatticeFunc f); + + /** + * Estimates the Orientation And Script of the image. + * @return true if the image was processed successfully. + */ + bool DetectOS(OSResults*); + + /** This method returns the features associated with the input image. */ + void GetFeaturesForBlob(TBLOB* blob, const DENORM& denorm, + INT_FEATURE_ARRAY int_features, + int* num_features, int* FeatureOutlineIndex); + + /** + * This method returns the row to which a box of specified dimensions would + * belong. If no good match is found, it returns NULL. + */ + static ROW* FindRowForBox(BLOCK_LIST* blocks, int left, int top, + int right, int bottom); + + /** + * Method to run adaptive classifier on a blob. + * It returns at max num_max_matches results. + */ + void RunAdaptiveClassifier(TBLOB* blob, const DENORM& denorm, + int num_max_matches, + int* unichar_ids, + float* ratings, + int* num_matches_returned); + + /** This method returns the string form of the specified unichar. */ + const char* GetUnichar(int unichar_id); + + /** Return the pointer to the i-th dawg loaded into tesseract_ object. */ + const Dawg *GetDawg(int i) const; + + /** Return the number of dawgs loaded into tesseract_ object. */ + int NumDawgs() const; + + /** 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, DENORM *denorm); + + Tesseract* const tesseract() const { + return tesseract_; + } + + OcrEngineMode const oem() const { + return last_oem_requested_; + } + + void InitTruthCallback(TruthCallback *cb) { truth_cb_ = cb; } + + /** Return a pointer to underlying CubeRecoContext object if present. */ + CubeRecoContext *GetCubeRecoContext() const; + + void set_min_orientation_margin(double margin); + + /** + * Return text orientation of each block as determined by an earlier run + * of layout analysis. + */ + void GetBlockTextOrientations(int** block_orientation, + bool** vertical_writing); + + /** Find lines from the image making the BLOCK_LIST. */ + BLOCK_LIST* FindLinesCreateBlockList(); + + /** + * Delete a block list. + * This is to keep BLOCK_LIST pointer opaque + * and let go of including the other headers. + */ + static void DeleteBlockList(BLOCK_LIST* block_list); + /* @} */ + + protected: + + /** Common code for setting the image. Returns true if Init has been called. */ + TESS_LOCAL bool InternalSetImage(); + + /** + * Run the thresholder to make the thresholded image. If pix is not NULL, + * the source is thresholded to pix instead of the internal IMAGE. + */ + TESS_LOCAL virtual void Threshold(Pix** pix); + + /** + * Find lines from the image making the BLOCK_LIST. + * @return 0 on success. + */ + TESS_LOCAL int FindLines(); + + /** Delete the pageres and block list ready for a new page. */ + TESS_LOCAL void ClearResults(); + + /** + * Return an LTR Result Iterator -- used only for training, as we really want + * to ignore all BiDi smarts at that point. + * delete once you're done with it. + */ + TESS_LOCAL LTRResultIterator* GetLTRIterator(); + + /** + * Return the length of the output text string, as UTF8, assuming + * one newline per line and one per block, with a terminator, + * 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); + + /** @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); + + //// paragraphs.cpp //////////////////////////////////////////////////// + TESS_LOCAL void DetectParagraphs(bool after_text_recognition); + + /** + * 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_; + }; + /* @} */ + + protected: + Tesseract* tesseract_; ///< The underlying data object. + Tesseract* osd_tesseract_; ///< For orientation & script detection. + EquationDetect* equ_detect_; ///* 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 + + /** + * @defgroup ThresholderParams Thresholder Parameters + * Parameters saved from the Thresholder. Needed to rebuild coordinates. + */ + /* @{ */ + int rect_left_; + int rect_top_; + int rect_width_; + int rect_height_; + int image_width_; + int image_height_; + /* @} */ + +}; + +} // namespace tesseract. + +#endif // TESSERACT_API_BASEAPI_H__ diff --git a/Tesseract/include/tesseract/basedir.h b/Tesseract/include/tesseract/basedir.h new file mode 100644 index 0000000..60d56ba --- /dev/null +++ b/Tesseract/include/tesseract/basedir.h @@ -0,0 +1,31 @@ +/********************************************************************** + * File: basedir.h (Formerly getpath.h) + * Description: Header file for getpath.c. Provides relocatability of data. + * Author: Ray Smith + * Created: Mon Jul 09 09:13:03 BST 1990 + * + * (C) Copyright 1990, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef BASEDIR_H +#define BASEDIR_H + +#include "platform.h" +#include "strngs.h" + +// Returns the given code_path truncated to the last slash. +// Useful for getting to the directory of argv[0], but does not search +// any paths. +TESS_API void truncate_path(const char *code_path, STRING* trunc_path); + +#endif diff --git a/Tesseract/include/tesseract/capi.h b/Tesseract/include/tesseract/capi.h new file mode 100644 index 0000000..4c8a95b --- /dev/null +++ b/Tesseract/include/tesseract/capi.h @@ -0,0 +1,297 @@ +#ifndef TESSERACT_API_CAPI_H__ +#define TESSERACT_API_CAPI_H__ + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +# include "baseapi.h" +# include "pageiterator.h" +# include "resultiterator.h" +#else +# include "platform.h" +# include +#endif + +#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 +#endif + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +typedef tesseract::TessBaseAPI TessBaseAPI; +typedef tesseract::PageIterator TessPageIterator; +typedef tesseract::ResultIterator TessResultIterator; +typedef tesseract::MutableIterator TessMutableIterator; +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::FillLatticeFunc TessFillLatticeFunc; +typedef tesseract::Dawg TessDawg; +typedef tesseract::TruthCallback TessTruthCallback; +typedef tesseract::CubeRecoContext TessCubeRecoContext; +typedef tesseract::Orientation TessOrientation; +typedef tesseract::WritingDirection TessWritingDirection; +typedef tesseract::TextlineOrder TessTextlineOrder; +typedef PolyBlockType TessPolyBlockType; +typedef Pix PIX; +typedef Boxa BOXA; +typedef Pixa PIXA; +#else +typedef struct TessBaseAPI TessBaseAPI; +typedef struct TessPageIterator TessPageIterator; +typedef struct TessResultIterator TessResultIterator; +typedef struct TessMutableIterator TessMutableIterator; +typedef enum TessOcrEngineMode { OEM_TESSERACT_ONLY, OEM_CUBE_ONLY, OEM_TESSERACT_CUBE_COMBINED, OEM_DEFAULT } TessOcrEngineMode; +typedef enum TessPageSegMode { PSM_OSD_ONLY, PSM_AUTO_OSD, PSM_AUTO_ONLY, PSM_AUTO, PSM_SINGLE_COLUMN, PSM_SINGLE_BLOCK_VERT_TEXT, + PSM_SINGLE_BLOCK, PSM_SINGLE_LINE, PSM_SINGLE_WORD, PSM_CIRCLE_WORD, PSM_SINGLE_CHAR, PSM_COUNT } TessPageSegMode; +typedef enum TessPageIteratorLevel { RIL_BLOCK, RIL_PARA, RIL_TEXTLINE, RIL_WORD, RIL_SYMBOL} TessPageIteratorLevel; +typedef enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_TABLE, PT_VERTICAL_TEXT, + PT_CAPTION_TEXT, PT_FLOWING_IMAGE, PT_HEADING_IMAGE, PT_PULLOUT_IMAGE, PT_HORZ_LINE, PT_VERT_LINE, + PT_NOISE, PT_COUNT } TessPolyBlockType; +typedef enum TessOrientation { ORIENTATION_PAGE_UP, ORIENTATION_PAGE_RIGHT, ORIENTATION_PAGE_DOWN, ORIENTATION_PAGE_LEFT } TessOrientation; +typedef enum TessWritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT, WRITING_DIRECTION_RIGHT_TO_LEFT, WRITING_DIRECTION_TOP_TO_BOTTOM } TessWritingDirection; +typedef enum TessTextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT, TEXTLINE_ORDER_RIGHT_TO_LEFT, TEXTLINE_ORDER_TOP_TO_BOTTOM } TessTextlineOrder; +typedef struct ETEXT_DESC ETEXT_DESC; +typedef struct Pix PIX; +typedef struct Boxa BOXA; +typedef struct Pixa PIXA; +#endif + +/* 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); +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list); +#endif + +/* Base API */ + +TESS_API TessBaseAPI* + TESS_CALL TessBaseAPICreate(); +TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle); + +TESS_API void TESS_CALL TessBaseAPISetInputName( TessBaseAPI* handle, const char* name); +TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name); + +TESS_API BOOL TESS_CALL TessBaseAPISetVariable(TessBaseAPI* handle, const char* name, const char* value); +TESS_API BOOL TESS_CALL TessBaseAPISetDebugVariable(TessBaseAPI* handle, const char* name, const char* value); + +TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable( const TessBaseAPI* handle, const char* name, int* value); +TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable( const TessBaseAPI* handle, const char* name, BOOL* value); +TESS_API BOOL TESS_CALL TessBaseAPIGetDoubleVariable(const TessBaseAPI* handle, const char* name, double* value); +TESS_API const char* + TESS_CALL TessBaseAPIGetStringVariable(const TessBaseAPI* handle, const char* name); + +TESS_API void TESS_CALL TessBaseAPIPrintVariables( const TessBaseAPI* handle, FILE* fp); +TESS_API BOOL TESS_CALL TessBaseAPIPrintVariablesToFile(const TessBaseAPI* handle, const char* filename); +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val); +#endif + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API int TESS_CALL TessBaseAPIInit(TessBaseAPI* handle, const char* datapath, const char* language, + TessOcrEngineMode mode, char** configs, int configs_size, + const STRING* vars_vec, size_t vars_vec_size, + const STRING* vars_values, size_t vars_values_size, BOOL set_only_init_params); +#endif +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 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 int TESS_CALL TessBaseAPIInitLangMod(TessBaseAPI* handle, const char* datapath, const char* language); +TESS_API void TESS_CALL TessBaseAPIInitForAnalysePage(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 TESS_CALL TessBaseAPISetPageSegMode(TessBaseAPI* handle, TessPageSegMode mode); +TESS_API TessPageSegMode + TESS_CALL TessBaseAPIGetPageSegMode(const TessBaseAPI* handle); + +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 TESS_CALL TessBaseAPIClearAdaptiveClassifier(TessBaseAPI* handle); + +TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height, + int bytes_per_pixel, int bytes_per_line); +TESS_API void TESS_CALL TessBaseAPISetImage2(TessBaseAPI* handle, const PIX* pix); + +TESS_API void TESS_CALL TessBaseAPISetSourceResolution(TessBaseAPI* handle, int ppi); + +TESS_API void TESS_CALL TessBaseAPISetRectangle(TessBaseAPI* handle, int left, int top, int width, int height); + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API void TESS_CALL TessBaseAPISetThresholder(TessBaseAPI* handle, TessImageThresholder* thresholder); +#endif + +TESS_API PIX* TESS_CALL TessBaseAPIGetThresholdedImage( TessBaseAPI* handle); +TESS_API BOXA* TESS_CALL TessBaseAPIGetRegions( TessBaseAPI* handle, PIXA** pixa); +TESS_API BOXA* TESS_CALL TessBaseAPIGetTextlines( TessBaseAPI* handle, PIXA** pixa, int** blockids); +TESS_API BOXA* TESS_CALL TessBaseAPIGetStrips( TessBaseAPI* handle, PIXA** pixa, int** blockids); +TESS_API BOXA* TESS_CALL TessBaseAPIGetWords( TessBaseAPI* handle, PIXA** pixa); +TESS_API BOXA* TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, PIXA** cc); +TESS_API BOXA* TESS_CALL TessBaseAPIGetComponentImages( TessBaseAPI* handle, TessPageIteratorLevel level, BOOL text_only, PIXA** pixa, int** blockids); + +TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle); + +TESS_API void TESS_CALL TessBaseAPIDumpPGM(TessBaseAPI* handle, const char* filename); + +TESS_API TessPageIterator* + TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle); + +TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor); +TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor); +TESS_API char* TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config, + int timeout_millisec); +TESS_API char* TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, PIX* pix, int page_index, const char* filename, + const char* retry_config, int timeout_millisec); + +TESS_API TessResultIterator* + TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle); +TESS_API TessMutableIterator* + TESS_CALL TessBaseAPIGetMutableIterator(TessBaseAPI* handle); + +TESS_API char* TESS_CALL TessBaseAPIGetUTF8Text(TessBaseAPI* handle); +TESS_API char* TESS_CALL TessBaseAPIGetHOCRText(TessBaseAPI* handle, int page_number); +TESS_API char* TESS_CALL TessBaseAPIGetBoxText(TessBaseAPI* handle, int page_number); +TESS_API char* TESS_CALL TessBaseAPIGetUNLVText(TessBaseAPI* handle); +TESS_API int TESS_CALL TessBaseAPIMeanTextConf(TessBaseAPI* handle); +TESS_API int* TESS_CALL TessBaseAPIAllWordConfidences(TessBaseAPI* handle); +TESS_API BOOL TESS_CALL TessBaseAPIAdaptToWordStr(TessBaseAPI* handle, TessPageSegMode mode, const char* wordstr); + +TESS_API void TESS_CALL TessBaseAPIClear(TessBaseAPI* handle); +TESS_API void TESS_CALL TessBaseAPIEnd(TessBaseAPI* handle); + +TESS_API int TESS_CALL TessBaseAPIIsValidWord(TessBaseAPI* handle, const char *word); +TESS_API BOOL TESS_CALL TessBaseAPIGetTextDirection(TessBaseAPI* handle, int* out_offset, float* out_slope); + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API void TESS_CALL TessBaseAPISetDictFunc(TessBaseAPI* handle, TessDictFunc f); +TESS_API void TESS_CALL TessBaseAPISetProbabilityInContextFunc(TessBaseAPI* handle, TessProbabilityInContextFunc f); +TESS_API void TESS_CALL TessBaseAPISetFillLatticeFunc(TessBaseAPI* handle, TessFillLatticeFunc f); +TESS_API BOOL TESS_CALL TessBaseAPIDetectOS(TessBaseAPI* handle, OSResults* results); + +TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, const DENORM* denorm, INT_FEATURE_ARRAY int_features, + int* num_features, int* FeatureOutlineIndex); + +TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom); +TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, const DENORM* denorm, int num_max_matches, + int* unichar_ids, float* ratings, int* num_matches_returned); +#endif + +TESS_API const char* + TESS_CALL TessBaseAPIGetUnichar(TessBaseAPI* handle, int unichar_id); + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API const TessDawg* + TESS_CALL TessBaseAPIGetDawg(const TessBaseAPI* handle, int i); +TESS_API int TESS_CALL TessBaseAPINumDawgs(const TessBaseAPI* handle); +#endif + +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API ROW* TESS_CALL TessMakeTessOCRRow(float baseline, float xheight, float descender, float ascender); +TESS_API TBLOB* + TESS_CALL TessMakeTBLOB(Pix *pix); +TESS_API void TESS_CALL TessNormalizeTBLOB(TBLOB *tblob, ROW *row, BOOL numeric_mode, DENORM *denorm); + +TESS_API TessOcrEngineMode + TESS_CALL TessBaseAPIOem(const TessBaseAPI* handle); +TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback *cb); + +TESS_API TessCubeRecoContext* + TESS_CALL TessBaseAPIGetCubeRecoContext(const TessBaseAPI* handle); +#endif + +TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin); +#ifdef TESS_CAPI_INCLUDE_BASEAPI +TESS_API void TESS_CALL TessBaseGetBlockTextOrientations(TessBaseAPI* handle, int** block_orientation, bool** vertical_writing); + +TESS_API BLOCK_LIST* + TESS_CALL TessBaseAPIFindLinesCreateBlockList(TessBaseAPI* handle); +#endif + +/* Page iterator */ + +TESS_API void TESS_CALL TessPageIteratorDelete(TessPageIterator* handle); +TESS_API TessPageIterator* + TESS_CALL TessPageIteratorCopy(const TessPageIterator* handle); + +TESS_API void TESS_CALL TessPageIteratorBegin(TessPageIterator* handle); +TESS_API BOOL TESS_CALL TessPageIteratorNext(TessPageIterator* handle, TessPageIteratorLevel level); +TESS_API BOOL TESS_CALL TessPageIteratorIsAtBeginningOf(const TessPageIterator* handle, TessPageIteratorLevel level); +TESS_API BOOL TESS_CALL TessPageIteratorIsAtFinalElement(const TessPageIterator* handle, TessPageIteratorLevel level, + TessPageIteratorLevel element); + +TESS_API BOOL TESS_CALL TessPageIteratorBoundingBox(const TessPageIterator* handle, TessPageIteratorLevel level, + int* left, int* top, int* right, int* bottom); +TESS_API TessPolyBlockType + TESS_CALL TessPageIteratorBlockType(const TessPageIterator* handle); + +TESS_API PIX* TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level); +TESS_API PIX* TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding, + int* left, int* top); + +TESS_API BOOL TESS_CALL TessPageIteratorBaseline(const TessPageIterator* handle, TessPageIteratorLevel level, + int* x1, int* y1, int* x2, int* y2); + +TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation *orientation, + TessWritingDirection *writing_direction, TessTextlineOrder *textline_order, + float *deskew_angle); + +/* 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 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 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); + +#ifdef __cplusplus +} +#endif + +#endif /* TESSERACT_API_CAPI_H__ */ diff --git a/Tesseract/include/tesseract/errcode.h b/Tesseract/include/tesseract/errcode.h new file mode 100644 index 0000000..2bc2a03 --- /dev/null +++ b/Tesseract/include/tesseract/errcode.h @@ -0,0 +1,105 @@ +/********************************************************************** + * File: errcode.h (Formerly error.h) + * Description: Header file for generic error handler class + * Author: Ray Smith + * Created: Tue May 1 16:23:36 BST 1990 + * + * (C) Copyright 1990, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef ERRCODE_H +#define ERRCODE_H + +#include "host.h" + +/*Control parameters for error()*/ +enum TessErrorLogCode { + DBG = -1, /*log without alert */ + TESSLOG = 0, /*alert user */ + TESSEXIT = 1, /*exit after erro */ + ABORT = 2 /*abort after error */ +}; + +/* Explicit Error Abort codes */ +#define NO_ABORT_CODE 0 +#define LIST_ABORT 1 +#define MEMORY_ABORT 2 +#define FILE_ABORT 3 + +/* Location of code at error codes Reserve 0..2 (status codes 0..23 for UNLV)*/ +#define LOC_UNUSED0 0 +#define LOC_UNUSED1 1 +#define LOC_UNUSED2 2 +#define LOC_INIT 3 +#define LOC_EDGE_PROG 4 +#define LOC_TEXT_ORD_ROWS 5 +#define LOC_TEXT_ORD_WORDS 6 +#define LOC_PASS1 7 +#define LOC_PASS2 8 +/* Reserve up to 8..13 for adding subloc 0/3 plus subsubloc 0/1/2 */ +#define LOC_FUZZY_SPACE 14 +/* Reserve up to 14..20 for adding subloc 0/3 plus subsubloc 0/1/2 */ +#define LOC_MM_ADAPT 21 +#define LOC_DOC_BLK_REJ 22 +#define LOC_WRITE_RESULTS 23 +#define LOC_ADAPTIVE 24 +/* DONT DEFINE ANY LOCATION > 31 !!! */ + +/* Sub locatation determines whether pass2 was in normal mode or fix xht mode*/ +#define SUBLOC_NORM 0 +#define SUBLOC_FIX_XHT 3 + +/* Sub Sub locatation determines whether match_word_pass2 was in Tess + matcher, NN matcher or somewhere else */ + +#define SUBSUBLOC_OTHER 0 +#define SUBSUBLOC_TESS 1 +#define SUBSUBLOC_NN 2 + +class TESS_API ERRCODE { // error handler class + const char *message; // error message + public: + void error( // error print function + const char *caller, // function location + TessErrorLogCode action, // action to take + const char *format, ... // fprintf format + ) const; + ERRCODE(const char *string) { + message = string; + } // initialize with string +}; + +const ERRCODE ASSERT_FAILED = "Assert failed"; + +#define ASSERT_HOST(x) if (!(x)) \ +{ \ + ASSERT_FAILED.error(#x,ABORT,"in file %s, line %d", \ + __FILE__,__LINE__); \ +} + +void signal_exit( // + int signal_code //Signal which + ); +extern "C" +{ + void err_exit(); + //The real signal + void signal_termination_handler(int sig); +}; + +void set_global_loc_code(int loc_code); + +void set_global_subloc_code(int loc_code); + +void set_global_subsubloc_code(int loc_code); +#endif diff --git a/Tesseract/include/tesseract/fileerr.h b/Tesseract/include/tesseract/fileerr.h new file mode 100644 index 0000000..d3b6993 --- /dev/null +++ b/Tesseract/include/tesseract/fileerr.h @@ -0,0 +1,34 @@ +/********************************************************************** + * File: fileerr.h (Formerly filerr.h) + * Description: Errors for file utilities. + * Author: Ray Smith + * Created: Tue Aug 14 15:45:16 BST 1990 + * + * (C) Copyright 1990, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef FILEERR_H +#define FILEERR_H + +#include "errcode.h" + +const ERRCODE CANTOPENFILE = "Can't open file"; +const ERRCODE CANTCREATEFILE = "Can't create file"; +const ERRCODE CANTMAKEPIPE = "Can't create pipe"; +const ERRCODE CANTCONNECTPIPE = "Can't reconnect pipes to stdin/stdout"; +const ERRCODE READFAILED = "Read of file failed"; +const ERRCODE WRITEFAILED = "Write of file failed"; +const ERRCODE SELECTFAILED = "Select failed"; + +const ERRCODE EXECFAILED = "Could not exec new process"; +#endif diff --git a/Tesseract/include/tesseract/genericvector.h b/Tesseract/include/tesseract/genericvector.h new file mode 100644 index 0000000..5ac3532 --- /dev/null +++ b/Tesseract/include/tesseract/genericvector.h @@ -0,0 +1,807 @@ +/////////////////////////////////////////////////////////////////////// +// File: genericvector.h +// Description: Generic vector class +// Author: Daria Antonova +// Created: Mon Jun 23 11:26:43 PDT 2008 +// +// (C) Copyright 2007, 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_GENERICVECTOR_H_ +#define TESSERACT_CCUTIL_GENERICVECTOR_H_ + +#include +#include + +#include "tesscallback.h" +#include "errcode.h" +#include "helpers.h" +#include "ndminx.h" + +// Use PointerVector below in preference to GenericVector, as that +// provides automatic deletion of pointers, [De]Serialize that works, and +// sort that works. +template +class GenericVector { + public: + GenericVector() { this->init(kDefaultVectorSize); } + explicit GenericVector(int size) { this->init(size); } + + // Copy + GenericVector(const GenericVector& other) { + this->init(other.size()); + this->operator+=(other); + } + GenericVector &operator+=(const GenericVector& other); + GenericVector &operator=(const GenericVector& other); + + virtual ~GenericVector(); + + // Reserve some memory. + void reserve(int size); + // Double the size of the internal array. + void double_the_size(); + + // Resizes to size and sets all values to t. + void init_to_size(int size, T t); + + // Return the size used. + int size() const { + return size_used_; + } + + int length() const { + return size_used_; + } + + // Return true if empty. + bool empty() const { + return size_used_ == 0; + } + + // Return the object from an index. + T &get(int index) const; + T &back() const; + T &operator[](int index) const; + + // Return the index of the T object. + // This method NEEDS a compare_callback to be passed to + // set_compare_callback. + int get_index(T object) const; + + // Return true if T is in the array + bool contains(T object) const; + + // Return true if the index is valid + T contains_index(int index) const; + + // Push an element in the end of the array + int push_back(T object); + void operator+=(T t); + + // Push an element in the end of the array if the same + // element is not already contained in the array. + int push_back_new(T object); + + // Push an element in the front of the array + // Note: This function is O(n) + int push_front(T object); + + // Set the value at the given index + void set(T t, int index); + + // Insert t at the given index, push other elements to the right. + void insert(T t, int index); + + // Removes an element at the given index and + // shifts the remaining elements to the left. + virtual void remove(int index); + + // Truncates the array to the given size by removing the end. + // If the current size is less, the array is not expanded. + virtual void truncate(int size) { + if (size < size_used_) + size_used_ = size; + } + + // Add a callback to be called to delete the elements when the array took + // their ownership. + void set_clear_callback(TessCallback1* cb); + + // Add a callback to be called to compare the elements when needed (contains, + // get_id, ...) + void set_compare_callback(TessResultCallback2* cb); + + // Clear the array, calling the clear callback function if any. + // All the owned callbacks are also deleted. + // If you don't want the callbacks to be deleted, before calling clear, set + // the callback to NULL. + virtual void clear(); + + // Delete objects pointed to by data_[i] + void delete_data_pointers(); + + // This method clears the current object, then, does a shallow copy of + // its argument, and finally invalidates its argument. + // Callbacks are moved to the current object; + void move(GenericVector* from); + + // Read/Write the array to a file. This does _NOT_ read/write the callbacks. + // The callback given must be permanent since they will be called more than + // once. The given callback will be deleted at the end. + // If the callbacks are NULL, then the data is simply read/written using + // fread (and swapping)/fwrite. + // Returns false on error or if the callback returns false. + // DEPRECATED. Use [De]Serialize[Classes] instead. + bool write(FILE* f, TessResultCallback2* cb) const; + bool read(FILE* f, TessResultCallback3* cb, bool swap); + // Writes a vector of simple types to the given file. Assumes that bitwise + // read/write of T will work. Returns false in case of error. + virtual bool Serialize(FILE* fp) const; + // Reads a vector of simple types from the given file. Assumes that bitwise + // read/write will work with ReverseN according to sizeof(T). + // Returns false in case of error. + // If swap is true, assumes a big/little-endian swap is needed. + virtual bool DeSerialize(bool swap, FILE* fp); + // Writes a vector of classes to the given file. Assumes the existence of + // bool T::Serialize(FILE* fp) const that returns false in case of error. + // Returns false in case of error. + bool SerializeClasses(FILE* fp) const; + // Reads a vector of classes from the given file. Assumes the existence of + // bool T::Deserialize(bool swap, FILE* fp) that returns false in case of + // error. Also needs T::T() and T::T(constT&), as init_to_size is used in + // this function. Returns false in case of error. + // If swap is true, assumes a big/little-endian swap is needed. + bool DeSerializeClasses(bool swap, FILE* fp); + + // Allocates a new array of double the current_size, copies over the + // information from data to the new location, deletes data and returns + // the pointed to the new larger array. + // This function uses memcpy to copy the data, instead of invoking + // operator=() for each element like double_the_size() does. + static T *double_the_size_memcpy(int current_size, T *data) { + T *data_new = new T[current_size * 2]; + memcpy(data_new, data, sizeof(T) * current_size); + delete[] data; + return data_new; + } + + // Sorts the members of this vector using the less than comparator (cmp_lt), + // which compares the values. Useful for GenericVectors to primitive types. + // Will not work so great for pointers (unless you just want to sort some + // pointers). You need to provide a specialization to sort_cmp to use + // your type. + void sort(); + + // Sort the array into the order defined by the qsort function comparator. + // The comparator function is as defined by qsort, ie. it receives pointers + // to two Ts and returns negative if the first element is to appear earlier + // in the result and positive if it is to appear later, with 0 for equal. + void sort(int (*comparator)(const void*, const void*)) { + qsort(data_, size_used_, sizeof(*data_), comparator); + } + + // Searches the array (assuming sorted in ascending order, using sort()) for + // an element equal to target and returns true if it is present. + // Use binary_search to get the index of target, or its nearest candidate. + bool bool_binary_search(const T& target) const { + int index = binary_search(target); + if (index >= size_used_) + return false; + return data_[index] == target; + } + // Searches the array (assuming sorted in ascending order, using sort()) for + // an element equal to target and returns the index of the best candidate. + // The return value is conceptually the largest index i such that + // data_[i] <= target or 0 if target < the whole vector. + // NOTE that this function uses operator> so really the return value is + // the largest index i such that data_[i] > target is false. + int binary_search(const T& target) const { + int bottom = 0; + int top = size_used_; + do { + int middle = (bottom + top) / 2; + if (data_[middle] > target) + top = middle; + else + bottom = middle; + } + while (top - bottom > 1); + return bottom; + } + + // Compact the vector by deleting elements using operator!= on basic types. + // The vector must be sorted. + void compact_sorted() { + if (size_used_ == 0) + return; + + // First element is in no matter what, hence the i = 1. + int last_write = 0; + for (int i = 1; i < size_used_; ++i) { + // Finds next unique item and writes it. + if (data_[last_write] != data_[i]) + data_[++last_write] = data_[i]; + } + // last_write is the index of a valid data cell, so add 1. + size_used_ = last_write + 1; + } + + // Compact the vector by deleting elements for which delete_cb returns + // true. delete_cb is a permanent callback and will be deleted. + void compact(TessResultCallback1* delete_cb) { + int new_size = 0; + int old_index = 0; + // Until the callback returns true, the elements stay the same. + while (old_index < size_used_ && !delete_cb->Run(old_index++)) + ++new_size; + // Now just copy anything else that gets false from delete_cb. + for (; old_index < size_used_; ++old_index) { + if (!delete_cb->Run(old_index)) { + data_[new_size++] = data_[old_index]; + } + } + size_used_ = new_size; + delete delete_cb; + } + + T dot_product(const GenericVector& other) const { + T result = static_cast(0); + for (int i = MIN(size_used_, other.size_used_) - 1; i >= 0; --i) + result += data_[i] * other.data_[i]; + return result; + } + + protected: + + // Init the object, allocating size memory. + void init(int size); + + // We are assuming that the object generally placed in thie + // vector are small enough that for efficiency it makes sence + // to start with a larger initial size. + static const int kDefaultVectorSize = 4; + inT32 size_used_; + inT32 size_reserved_; + T* data_; + TessCallback1* clear_cb_; + // Mutable because Run method is not const + mutable TessResultCallback2* compare_cb_; +}; + +namespace tesseract { + +template +bool cmp_eq(T const & t1, T const & t2) { + return t1 == t2; +} + +// Used by sort() +// return < 0 if t1 < t2 +// return 0 if t1 == t2 +// return > 0 if t1 > t2 +template +int sort_cmp(const void* t1, const void* t2) { + const T* a = static_cast (t1); + const T* b = static_cast (t2); + if (*a < *b) { + return -1; + } else if (*b < *a) { + return 1; + } else { + return 0; + } +} + +// Used by PointerVector::sort() +// return < 0 if t1 < t2 +// return 0 if t1 == t2 +// return > 0 if t1 > t2 +template +int sort_ptr_cmp(const void* t1, const void* t2) { + const T* a = *reinterpret_cast(t1); + const T* b = *reinterpret_cast(t2); + if (*a < *b) { + return -1; + } else if (*b < *a) { + return 1; + } else { + return 0; + } +} + +// Subclass for a vector of pointers. Use in preference to GenericVector +// as it provides automatic deletion and correct serialization, with the +// corollary that all copy operations are deep copies of the pointed-to objects. +template +class PointerVector : public GenericVector { + public: + PointerVector() : GenericVector() { } + explicit PointerVector(int size) : GenericVector(size) { } + virtual ~PointerVector() { + // Clear must be called here, even though it is called again by the base, + // as the base will call the wrong clear. + clear(); + } + // Copy must be deep, as the pointers will be automatically deleted on + // destruction. + PointerVector(const PointerVector& other) { + this->init(other.size()); + this->operator+=(other); + } + PointerVector& operator+=(const PointerVector& other) { + this->reserve(this->size_used_ + other.size_used_); + for (int i = 0; i < other.size(); ++i) { + this->push_back(new T(*other.data_[i])); + } + return *this; + } + + PointerVector& operator=(const PointerVector& other) { + this->truncate(0); + this->operator+=(other); + return *this; + } + + // Removes an element at the given index and + // shifts the remaining elements to the left. + virtual void remove(int index) { + delete GenericVector::data_[index]; + GenericVector::remove(index); + } + + // Truncates the array to the given size by removing the end. + // If the current size is less, the array is not expanded. + virtual void truncate(int size) { + for (int i = size; i < GenericVector::size_used_; ++i) + delete GenericVector::data_[i]; + GenericVector::truncate(size); + } + + // Compact the vector by deleting elements for which delete_cb returns + // true. delete_cb is a permanent callback and will be deleted. + void compact(TessResultCallback1* delete_cb) { + int new_size = 0; + int old_index = 0; + // Until the callback returns true, the elements stay the same. + while (old_index < GenericVector::size_used_ && + !delete_cb->Run(GenericVector::data_[old_index++])) + ++new_size; + // Now just copy anything else that gets false from delete_cb. + for (; old_index < GenericVector::size_used_; ++old_index) { + if (!delete_cb->Run(GenericVector::data_[old_index])) { + GenericVector::data_[new_size++] = + GenericVector::data_[old_index]; + } else { + delete GenericVector::data_[old_index]; + } + } + GenericVector::size_used_ = new_size; + delete delete_cb; + } + + // Clear the array, calling the clear callback function if any. + // All the owned callbacks are also deleted. + // If you don't want the callbacks to be deleted, before calling clear, set + // the callback to NULL. + virtual void clear() { + GenericVector::delete_data_pointers(); + GenericVector::clear(); + } + + // Writes a vector of simple types to the given file. Assumes that bitwise + // read/write of T will work. Returns false in case of error. + virtual bool Serialize(FILE* fp) const { + inT32 used = GenericVector::size_used_; + if (fwrite(&used, sizeof(used), 1, fp) != 1) return false; + for (int i = 0; i < used; ++i) { + inT8 non_null = GenericVector::data_[i] != NULL; + if (fwrite(&non_null, sizeof(non_null), 1, fp) != 1) return false; + if (non_null && !GenericVector::data_[i]->Serialize(fp)) return false; + } + return true; + } + // Reads a vector of simple types from the given file. Assumes that bitwise + // read/write will work with ReverseN according to sizeof(T). + // Also needs T::T(), as new T is used in this function. + // Returns false in case of error. + // If swap is true, assumes a big/little-endian swap is needed. + virtual bool DeSerialize(bool swap, FILE* fp) { + inT32 reserved; + if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false; + if (swap) Reverse32(&reserved); + GenericVector::reserve(reserved); + for (int i = 0; i < reserved; ++i) { + inT8 non_null; + if (fread(&non_null, sizeof(non_null), 1, fp) != 1) return false; + T* item = NULL; + if (non_null) { + item = new T; + if (!item->DeSerialize(swap, fp)) return false; + } + this->push_back(item); + } + return true; + } + + // Sorts the items pointed to by the members of this vector using + // t::operator<(). + void sort() { + sort(&sort_ptr_cmp); + } +}; + +} // namespace tesseract + +// A useful vector that uses operator== to do comparisons. +template +class GenericVectorEqEq : public GenericVector { + public: + GenericVectorEqEq() { + GenericVector::set_compare_callback( + NewPermanentTessCallback(tesseract::cmp_eq)); + } + GenericVectorEqEq(int size) : GenericVector(size) { + GenericVector::set_compare_callback( + NewPermanentTessCallback(tesseract::cmp_eq)); + } +}; + +template +void GenericVector::init(int size) { + size_used_ = 0; + size_reserved_ = 0; + data_ = 0; + clear_cb_ = 0; + compare_cb_ = 0; + reserve(size); +} + +template +GenericVector::~GenericVector() { + clear(); +} + +// Reserve some memory. If the internal array contains elements, they are +// copied. +template +void GenericVector::reserve(int size) { + if (size_reserved_ >= size || size <= 0) + return; + T* new_array = new T[size]; + for (int i = 0; i < size_used_; ++i) + new_array[i] = data_[i]; + if (data_ != NULL) delete[] data_; + data_ = new_array; + size_reserved_ = size; +} + +template +void GenericVector::double_the_size() { + if (size_reserved_ == 0) { + reserve(kDefaultVectorSize); + } + else { + reserve(2 * size_reserved_); + } +} + +// Resizes to size and sets all values to t. +template +void GenericVector::init_to_size(int size, T t) { + reserve(size); + size_used_ = size; + for (int i = 0; i < size; ++i) + data_[i] = t; +} + + +// Return the object from an index. +template +T &GenericVector::get(int index) const { + ASSERT_HOST(index >= 0 && index < size_used_); + return data_[index]; +} + +template +T &GenericVector::operator[](int index) const { + return data_[index]; +} + +template +T &GenericVector::back() const { + ASSERT_HOST(size_used_ > 0); + return data_[size_used_ - 1]; +} + +// Return the object from an index. +template +void GenericVector::set(T t, int index) { + ASSERT_HOST(index >= 0 && index < size_used_); + data_[index] = t; +} + +// Shifts the rest of the elements to the right to make +// space for the new elements and inserts the given element +// at the specified index. +template +void GenericVector::insert(T t, int index) { + ASSERT_HOST(index >= 0 && index < size_used_); + if (size_reserved_ == size_used_) + double_the_size(); + for (int i = size_used_; i > index; --i) { + data_[i] = data_[i-1]; + } + data_[index] = t; + size_used_++; +} + +// Removes an element at the given index and +// shifts the remaining elements to the left. +template +void GenericVector::remove(int index) { + ASSERT_HOST(index >= 0 && index < size_used_); + for (int i = index; i < size_used_ - 1; ++i) { + data_[i] = data_[i+1]; + } + size_used_--; +} + +// Return true if the index is valindex +template +T GenericVector::contains_index(int index) const { + return index >= 0 && index < size_used_; +} + +// Return the index of the T object. +template +int GenericVector::get_index(T object) const { + for (int i = 0; i < size_used_; ++i) { + ASSERT_HOST(compare_cb_ != NULL); + if (compare_cb_->Run(object, data_[i])) + return i; + } + return -1; +} + +// Return true if T is in the array +template +bool GenericVector::contains(T object) const { + return get_index(object) != -1; +} + +// Add an element in the array +template +int GenericVector::push_back(T object) { + int index = 0; + if (size_used_ == size_reserved_) + double_the_size(); + index = size_used_++; + data_[index] = object; + return index; +} + +template +int GenericVector::push_back_new(T object) { + int index = get_index(object); + if (index >= 0) + return index; + return push_back(object); +} + +// Add an element in the array (front) +template +int GenericVector::push_front(T object) { + if (size_used_ == size_reserved_) + double_the_size(); + for (int i = size_used_; i > 0; --i) + data_[i] = data_[i-1]; + data_[0] = object; + ++size_used_; + return 0; +} + +template +void GenericVector::operator+=(T t) { + push_back(t); +} + +template +GenericVector &GenericVector::operator+=(const GenericVector& other) { + this->reserve(size_used_ + other.size_used_); + for (int i = 0; i < other.size(); ++i) { + this->operator+=(other.data_[i]); + } + return *this; +} + +template +GenericVector &GenericVector::operator=(const GenericVector& other) { + this->truncate(0); + this->operator+=(other); + return *this; +} + +// Add a callback to be called to delete the elements when the array took +// their ownership. +template +void GenericVector::set_clear_callback(TessCallback1* cb) { + clear_cb_ = cb; +} + +// Add a callback to be called to delete the elements when the array took +// their ownership. +template +void GenericVector::set_compare_callback(TessResultCallback2* cb) { + compare_cb_ = cb; +} + +// Clear the array, calling the callback function if any. +template +void GenericVector::clear() { + if (size_reserved_ > 0) { + if (clear_cb_ != NULL) + for (int i = 0; i < size_used_; ++i) + clear_cb_->Run(data_[i]); + delete[] data_; + data_ = NULL; + size_used_ = 0; + size_reserved_ = 0; + } + if (clear_cb_ != NULL) { + delete clear_cb_; + clear_cb_ = NULL; + } + if (compare_cb_ != NULL) { + delete compare_cb_; + compare_cb_ = NULL; + } +} + +template +void GenericVector::delete_data_pointers() { + for (int i = 0; i < size_used_; ++i) + if (data_[i]) { + delete data_[i]; + } +} + + +template +bool GenericVector::write( + FILE* f, TessResultCallback2* cb) const { + if (fwrite(&size_reserved_, sizeof(size_reserved_), 1, f) != 1) return false; + if (fwrite(&size_used_, sizeof(size_used_), 1, f) != 1) return false; + if (cb != NULL) { + for (int i = 0; i < size_used_; ++i) { + if (!cb->Run(f, data_[i])) { + delete cb; + return false; + } + } + delete cb; + } else { + if (fwrite(data_, sizeof(T), size_used_, f) != size_used_) return false; + } + return true; +} + +template +bool GenericVector::read(FILE* f, + TessResultCallback3* cb, + bool swap) { + inT32 reserved; + if (fread(&reserved, sizeof(reserved), 1, f) != 1) return false; + if (swap) Reverse32(&reserved); + reserve(reserved); + if (fread(&size_used_, sizeof(size_used_), 1, f) != 1) return false; + if (swap) Reverse32(&size_used_); + if (cb != NULL) { + for (int i = 0; i < size_used_; ++i) { + if (!cb->Run(f, data_ + i, swap)) { + delete cb; + return false; + } + } + delete cb; + } else { + if (fread(data_, sizeof(T), size_used_, f) != size_used_) return false; + if (swap) { + for (int i = 0; i < size_used_; ++i) + ReverseN(&data_[i], sizeof(T)); + } + } + return true; +} + +// Writes a vector of simple types to the given file. Assumes that bitwise +// read/write of T will work. Returns false in case of error. +template +bool GenericVector::Serialize(FILE* fp) const { + if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false; + if (fwrite(data_, sizeof(*data_), size_used_, fp) != size_used_) return false; + return true; +} + +// Reads a vector of simple types from the given file. Assumes that bitwise +// read/write will work with ReverseN according to sizeof(T). +// Returns false in case of error. +// If swap is true, assumes a big/little-endian swap is needed. +template +bool GenericVector::DeSerialize(bool swap, FILE* fp) { + inT32 reserved; + if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false; + if (swap) Reverse32(&reserved); + reserve(reserved); + size_used_ = reserved; + if (fread(data_, sizeof(T), size_used_, fp) != size_used_) return false; + if (swap) { + for (int i = 0; i < size_used_; ++i) + ReverseN(&data_[i], sizeof(data_[i])); + } + return true; +} + +// Writes a vector of classes to the given file. Assumes the existence of +// bool T::Serialize(FILE* fp) const that returns false in case of error. +// Returns false in case of error. +template +bool GenericVector::SerializeClasses(FILE* fp) const { + if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false; + for (int i = 0; i < size_used_; ++i) { + if (!data_[i].Serialize(fp)) return false; + } + return true; +} + +// Reads a vector of classes from the given file. Assumes the existence of +// bool T::Deserialize(bool swap, FILE* fp) that returns false in case of +// error. Alse needs T::T() and T::T(constT&), as init_to_size is used in +// this function. Returns false in case of error. +// If swap is true, assumes a big/little-endian swap is needed. +template +bool GenericVector::DeSerializeClasses(bool swap, FILE* fp) { + uinT32 reserved; + if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false; + if (swap) Reverse32(&reserved); + T empty; + init_to_size(reserved, empty); + for (int i = 0; i < reserved; ++i) { + if (!data_[i].DeSerialize(swap, fp)) return false; + } + return true; +} + +// This method clear the current object, then, does a shallow copy of +// its argument, and finally invalidates its argument. +template +void GenericVector::move(GenericVector* from) { + this->clear(); + this->data_ = from->data_; + this->size_reserved_ = from->size_reserved_; + this->size_used_ = from->size_used_; + this->compare_cb_ = from->compare_cb_; + this->clear_cb_ = from->clear_cb_; + from->data_ = NULL; + from->clear_cb_ = NULL; + from->compare_cb_ = NULL; + from->size_used_ = 0; + from->size_reserved_ = 0; +} + +template +void GenericVector::sort() { + sort(&tesseract::sort_cmp); +} + +#endif // TESSERACT_CCUTIL_GENERICVECTOR_H_ diff --git a/Tesseract/include/tesseract/helpers.h b/Tesseract/include/tesseract/helpers.h new file mode 100644 index 0000000..6d58520 --- /dev/null +++ b/Tesseract/include/tesseract/helpers.h @@ -0,0 +1,152 @@ +/* -*-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 +#include + +// Remove newline (if any) at the end of the string. +inline void chomp_string(char *str) { + int last_index = 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); +} + +// qsort function to sort 2 floats. +inline int sort_floats(const void *arg1, const void *arg2) { + float diff = *((float *) arg1) - *((float *) arg2); + if (diff > 0) { + return 1; + } else if (diff < 0) { + return -1; + } else { + return 0; + } +} + +// 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 +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 +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 +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 +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= 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(x + 0.5) : -static_cast(-x + 0.5); +} + +// Reverse the order of bytes in a n byte quantity for big/little-endian switch. +inline void ReverseN(void* ptr, int num_bytes) { + char *cptr = reinterpret_cast(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_ diff --git a/Tesseract/include/tesseract/host.h b/Tesseract/include/tesseract/host.h new file mode 100644 index 0000000..5c27d70 --- /dev/null +++ b/Tesseract/include/tesseract/host.h @@ -0,0 +1,153 @@ +/****************************************************************************** + ** Filename: Host.h + ** Purpose: This is the system independent typedefs and defines + ** Author: MN, JG, MD + ** Version: 5.4.1 + ** History: 11/7/94 MCD received the modification that Lennart made + ** to port to 32 bit world and modify this file so that it + ** will be shared between platform. + ** 11/9/94 MCD Make MSW32 subset of MSW. Now MSW means + ** MicroSoft Window and MSW32 means the 32 bit worlds + ** of MicroSoft Window. Therefore you want the environment + ** to be MicroSoft Window and in the 32 bit world - + ** _WIN32 must be defined by your compiler. + ** 11/30/94 MCD Incorporated comments received for more + ** readability and the missing typedef for FLOAT. + ** 12/1/94 MCD Added PFVOID typedef + ** 5/1/95 MCD. Made many changes based on the inputs. + ** Changes: + ** 1) Rearrange the #ifdef so that there're definitions for + ** particular platforms. + ** 2) Took out the #define for computer and environment + ** that developer can uncomment + ** 3) Added __OLDCODE__ where the defines will be + ** obsoleted in the next version and advise not to use. + ** 4) Added the definitions for the following: + ** FILE_HANDLE, MEMORY_HANDLE, BOOL8, + ** MAX_INT8, MAX_INT16, MAX_INT32, MAX_UINT8 + ** MAX_UINT16, MAX_UINT32, MAX_FLOAT32 + ** 06/19/96 MCD. Took out MAX_FLOAT32 + ** 07/15/96 MCD. Fixed the comments error + ** Add back BOOL8. + ** + ** (c) Copyright Hewlett-Packard Company, 1988-1996. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** 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 __HOST__ +#define __HOST__ + +/****************************************************************************** + ** IMPORTANT!!! ** + ** ** + ** Defines either _WIN32, __MAC__, __UNIX__, __OS2__, __PM__ to + ** use the specified definitions indicated below in the preprocessor settings. ** + ** ** + ** Also define either __FarProc__ or __FarData__ and __MOTO__ to use the + ** specified definitions indicated below in the preprocessor settings. ** + ** ** + ** If a preprocessor settings is not allow in the compiler that is being use, + ** then it is recommended that a "platform.h" is created with the definition + ** of the computer and/or operating system. + ******************************************************************************/ + +#include "platform.h" +/* _WIN32 */ +#ifdef _WIN32 +#include +#include // winbase.h contains windows.h +#endif + +/********************************************************/ +/* __MAC__ */ +#ifdef __MAC__ +#include +/*----------------------------*/ +/*----------------------------*/ +#endif +/********************************************************/ +#if defined(__UNIX__) || defined( __DOS__ ) || defined(__OS2__) || defined(__PM__) +/*----------------------------*/ +/* FarProc and FarData */ +/*----------------------------*/ +/*----------------------------*/ +#endif +/***************************************************************************** + ** + ** Standard GHC Definitions + ** + *****************************************************************************/ + +#ifdef __MOTO__ +#define __NATIVE__ MOTO +#else +#define __NATIVE__ INTEL +#endif + +//typedef HANDLE FD* PHANDLE; + +// definitions of portable data types (numbers and characters) +typedef SIGNED char inT8; +typedef unsigned char uinT8; +typedef short inT16; +typedef unsigned short uinT16; +typedef int inT32; +typedef unsigned int uinT32; +#if (_MSC_VER >= 1200) //%%% vkr for VC 6.0 +typedef INT64 inT64; +typedef UINT64 uinT64; +#else +typedef long long int inT64; +typedef unsigned long long int uinT64; +#endif //%%% vkr for VC 6.0 +typedef float FLOAT32; +typedef double FLOAT64; +typedef unsigned char BOOL8; + +#define INT32FORMAT "%d" +#define INT64FORMAT "%lld" + +#define MAX_INT8 0x7f +#define MAX_INT16 0x7fff +#define MAX_INT32 0x7fffffff +#define MAX_UINT8 0xff +#define MAX_UINT16 0xffff +#define MAX_UINT32 0xffffffff +#define MAX_FLOAT32 ((float)3.40282347e+38) + +#define MIN_INT8 0x80 +#define MIN_INT16 0x8000 +#define MIN_INT32 0x80000000 +#define MIN_UINT8 0x00 +#define MIN_UINT16 0x0000 +#define MIN_UINT32 0x00000000 +#define MIN_FLOAT32 ((float)1.17549435e-38) + +// Defines +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef NULL +#define NULL 0L +#endif + +// Return true if x is within tolerance of y +template bool NearlyEqual(T x, T y, T tolerance) { + T diff = x - y; + return diff <= tolerance && -diff <= tolerance; +} + +#endif diff --git a/Tesseract/include/tesseract/ltrresultiterator.h b/Tesseract/include/tesseract/ltrresultiterator.h new file mode 100644 index 0000000..9464aae --- /dev/null +++ b/Tesseract/include/tesseract/ltrresultiterator.h @@ -0,0 +1,203 @@ +/////////////////////////////////////////////////////////////////////// +// File: ltrresultiterator.h +// 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"); +// 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_LTR_RESULT_ITERATOR_H__ +#define TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H__ + +#include "platform.h" +#include "pageiterator.h" +#include "unicharset.h" + +class BLOB_CHOICE_IT; +class WERD_RES; + +namespace tesseract { + +class Tesseract; + +// Class to iterate over tesseract results, providing access to all levels +// of the page hierarchy, without including any tesseract headers or having +// to handle any tesseract structures. +// WARNING! This class points to data held within the TessBaseAPI class, and +// 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 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: + // 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 + // original image (in top-left-origin coordinates) and therefore the top-left + // needs to be added to any output boxes in order to specify coordinates + // in the original image. See TessBaseAPI::SetRectangle. + // The scale and scaled_yres are in case the Thresholder scaled the image + // rectangle prior to thresholding. Any coordinates in tesseract's image + // must be divided by scale before adding (rect_left, rect_top). + // 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, + int rect_width, int rect_height); + virtual ~LTRResultIterator(); + + // LTRResultIterators may be copied! This makes it possible to iterate over + // all the objects at a lower level, while maintaining an iterator to + // objects at a higher level. These constructors DO NOT CALL Begin, so + // iterations will continue from the location of src. + // TODO: For now the copy constructor and operator= only need the base class + // versions, but if new data members are added, don't forget to add them! + + // ============= Moving around within the page ============. + + // See PageIterator. + + // ============= Accessing data ==============. + + // 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; + + // Set the string inserted at the end of each text line. "\n" by default. + void SetLineSeparator(const char *new_line); + + // Set the string inserted at the end of each paragraph. "\n" by default. + void SetParagraphSeparator(const char *new_para); + + // Returns the mean confidence of the current object at the given level. + // The number should be interpreted as a percent probability. (0.0f-100.0f) + float Confidence(PageIteratorLevel level) const; + + // ============= Functions that refer to words only ============. + + // Returns the font attributes of the current word. If iterating at a higher + // level object than words, eg textlines, then this will return the + // attributes of the first word in that textline. + // The actual return value is a string representing a font name. It points + // to an internal table and SHOULD NOT BE DELETED. Lifespan is the same as + // 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; + + // Return the name of the language used to recognize this word. + // On error, NULL. Do not delete this pointer. + const char* WordRecognitionLanguage() const; + + // Return the overall directionality of this word. + StrongScriptDirection WordDirection() const; + + // Returns true if the current word was found in a dictionary. + bool WordIsFromDictionary() const; + + // Returns true if the current word is numeric. + bool WordIsNumeric() const; + + // Returns true if the word contains blamer information. + bool HasBlamerInfo() const; + + // Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle + // of the current word. + void *GetParamsTrainingBundle() const; + + // Returns a pointer to the string with blamer information for this word. + // Assumes that the word's blamer_bundle is not NULL. + const char *GetBlamerDebug() const; + + // Returns a pointer to the string with misadaption information for this word. + // Assumes that the word's blamer_bundle is not NULL. + const char *GetBlamerMisadaptionDebug() const; + + // Returns a null terminated UTF-8 encoded truth string for the current word. + // Use delete [] to free after use. + char* WordTruthUTF8Text() const; + + // Returns a pointer to serialized choice lattice. + // Fills lattice_size with the number of bytes in lattice data. + const char *WordLattice(int *lattice_size) const; + + // ============= Functions that refer to symbols only ============. + + // Returns true if the current symbol is a superscript. + // If iterating at a higher level object than symbols, eg words, then + // this will return the attributes of the first symbol in that word. + bool SymbolIsSuperscript() const; + // Returns true if the current symbol is a subscript. + // If iterating at a higher level object than symbols, eg words, then + // this will return the attributes of the first symbol in that word. + bool SymbolIsSubscript() const; + // Returns true if the current symbol is a dropcap. + // If iterating at a higher level object than symbols, eg words, then + // this will return the attributes of the first symbol in that word. + bool SymbolIsDropcap() const; + + protected: + const char *line_separator_; + const char *paragraph_separator_; +}; + +// Class to iterate over the classifier choices for a single RIL_SYMBOL. +class 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); + ~ChoiceIterator(); + + // Moves to the next choice for the symbol and returns false if there + // are none left. + bool Next(); + + // ============= Accessing data ==============. + + // Returns the null terminated UTF-8 encoded text string for the current + // 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; + + // Returns the confidence of the current choice. + // The number should be interpreted as a percent probability. (0.0f-100.0f) + float Confidence() const; + + private: + // Pointer to the WERD_RES object owned by the API. + WERD_RES* word_res_; + // Iterator over the blob choices. + BLOB_CHOICE_IT* choice_it_; +}; + +} // namespace tesseract. + +#endif // TESSERACT_CCMAIN_LTR_RESULT_ITERATOR_H__ diff --git a/Tesseract/include/tesseract/memry.h b/Tesseract/include/tesseract/memry.h new file mode 100644 index 0000000..66e146e --- /dev/null +++ b/Tesseract/include/tesseract/memry.h @@ -0,0 +1,43 @@ +/********************************************************************** + * File: memry.h (Formerly memory.h) + * Description: Header file for basic memory allocation/deallocation. + * Author: Ray Smith + * Created: Tue May 8 16:03:48 BST 1990 + * + * (C) Copyright 1990, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef MEMRY_H +#define MEMRY_H + +#include +#include "host.h" + +// allocate string +extern char *alloc_string(inT32 count); +// free a string. +extern void free_string(char *string); +// allocate memory +extern void *alloc_struct(inT32 count, const char *name = NULL); +// free a structure. +extern void free_struct(void *deadstruct, inT32, const char *name = NULL); +// get some memory +extern void *alloc_mem(inT32 count); +// get some memory initialized to 0. +extern void *alloc_big_zeros(inT32 count); +// free mem from alloc_mem +extern void free_mem(void *oldchunk); +// free mem from alloc_big_zeros +extern void free_big_mem(void *oldchunk); + +#endif diff --git a/Tesseract/include/tesseract/ndminx.h b/Tesseract/include/tesseract/ndminx.h new file mode 100644 index 0000000..9eee76c --- /dev/null +++ b/Tesseract/include/tesseract/ndminx.h @@ -0,0 +1,31 @@ +/********************************************************************** + * File: ndminx.h (Formerly ndminmax.h) + * Description: Extended ascii chars + * Author: Phil Cheatle + * Created: Mon Mar 29 14:46:01 BST 1993 + * + * (C) Copyright 1991, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef NDMINX_H +#define NDMINX_H + +#ifndef MAX +#define MAX(x,y) (((x) >= (y))?(x):(y)) +#endif + +#ifndef MIN +#define MIN(x,y) (((x) <= (y))?(x):(y)) +#endif + +#endif diff --git a/Tesseract/include/tesseract/pageiterator.h b/Tesseract/include/tesseract/pageiterator.h new file mode 100644 index 0000000..0d6084f --- /dev/null +++ b/Tesseract/include/tesseract/pageiterator.h @@ -0,0 +1,327 @@ +/////////////////////////////////////////////////////////////////////// +// File: pageiterator.h +// 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"); +// 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_PAGEITERATOR_H__ +#define TESSERACT_CCMAIN_PAGEITERATOR_H__ + +#include "publictypes.h" +#include "platform.h" + +class C_BLOB_IT; +class PBLOB_IT; +class PAGE_RES; +class PAGE_RES_IT; +class WERD; +struct Pix; + +namespace tesseract { + +class Tesseract; + +/** + * Class to iterate over tesseract page structure, providing access to all + * levels of the page hierarchy, without including any tesseract headers or + * having to handle any tesseract structures. + * WARNING! This class points to data held within the TessBaseAPI class, and + * 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 also ResultIterator, derived from PageIterator, which adds in the + * ability to access OCR output with text-specific methods. + */ + +class TESS_API PageIterator { + 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 + * original image (in top-left-origin coordinates) and therefore the top-left + * needs to be added to any output boxes in order to specify coordinates + * in the original image. See TessBaseAPI::SetRectangle. + * The scale and scaled_yres are in case the Thresholder scaled the image + * rectangle prior to thresholding. Any coordinates in tesseract's image + * must be divided by scale before adding (rect_left, rect_top). + * 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. + */ + 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(); + + /** + * Page/ResultIterators may be copied! This makes it possible to iterate over + * all the objects at a lower level, while maintaining an iterator to + * 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); + + /** Are we positioned at the same location as other? */ + bool PositionedAtSameWord(const PAGE_RES_IT* other) const; + + // ============= Moving around within the page ============. + + /** + * Moves the iterator to point to the start of the page to begin an + * iteration. + */ + virtual void Begin(); + + /** + * Moves the iterator to the beginning of the paragraph. + * This class implements this functionality by moving it to the zero indexed + * blob of the first (leftmost) word on the first row of the paragraph. + */ + virtual void RestartParagraph(); + + /** + * Return whether this iterator points anywhere in the first textline of a + * paragraph. + */ + bool IsWithinFirstTextlineOfParagraph() const; + + /** + * Moves the iterator to the beginning of the text line. + * This class implements this functionality by moving it to the zero indexed + * blob of the first (leftmost) word of the row. + */ + virtual void RestartRow(); + + /** + * Moves to the start of the next object at the given level in the + * page hierarchy, and returns false if the end of the page was reached. + * NOTE that RIL_SYMBOL will skip non-text blocks, but all other + * PageIteratorLevel level values will visit each non-text block once. + * Think of non text blocks as containing a single para, with a single line, + * with a single imaginary word. + * Calls to Next with different levels may be freely intermixed. + * This function iterates words in right-to-left scripts correctly, if + * the appropriate language has been loaded into Tesseract. + */ + virtual bool Next(PageIteratorLevel level); + + /** + * Returns true if the iterator is at the start of an object at the given + * level. + * + * For instance, suppose an iterator it is pointed to the first symbol of the + * first word of the third line of the second paragraph of the first block in + * a page, then: + * it.IsAtBeginningOf(RIL_BLOCK) = false + * it.IsAtBeginningOf(RIL_PARA) = false + * it.IsAtBeginningOf(RIL_TEXTLINE) = true + * it.IsAtBeginningOf(RIL_WORD) = true + * it.IsAtBeginningOf(RIL_SYMBOL) = true + */ + virtual bool IsAtBeginningOf(PageIteratorLevel level) const; + + /** + * Returns whether the iterator is positioned at the last element in a + * given level. (e.g. the last word in a line, the last line in a block) + * + * Here's some two-paragraph example + * text. It starts off innocuously + * enough but quickly turns bizarre. + * The author inserts a cornucopia + * of words to guard against confused + * references. + * + * Now take an iterator it pointed to the start of "bizarre." + * it.IsAtFinalElement(RIL_PARA, RIL_SYMBOL) = false + * it.IsAtFinalElement(RIL_PARA, RIL_WORD) = true + * it.IsAtFinalElement(RIL_BLOCK, RIL_WORD) = false + */ + virtual bool IsAtFinalElement(PageIteratorLevel level, + PageIteratorLevel element) const; + + /** + * Returns whether this iterator is positioned + * before other: -1 + * equal to other: 0 + * after other: 1 + */ + int Cmp(const PageIterator &other) const; + + // ============= Accessing data ==============. + // Coordinate system: + // Integer coordinates are at the cracks between the pixels. + // The top-left corner of the top-left pixel in the image is at (0,0). + // The bottom-right corner of the bottom-right pixel in the image is at + // (width, height). + // Every bounding box goes from the top-left of the top-left contained + // pixel to the bottom-right of the bottom-right contained pixel, so + // the bounding box of the single top-left pixel in the image is: + // (0,0)->(1,1). + // If an image rectangle has been set in the API, then returned coordinates + // relate to the original (full) image, rather than the rectangle. + + /** + * Returns the bounding rectangle of the current object at the given level. + * See comment on coordinate system above. + * Returns false if there is no such object at the current position. + * The returned bounding box is guaranteed to match the size and position + * of the image returned by GetBinaryImage, but may clip foreground pixels + * 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; + /** + * 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; + + /** 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. + */ + PolyBlockType BlockType() const; + + /** + * Returns a binary image of the current object at the given level. + * The position and size match the return from BoundingBoxInternal, and so + * this could be upscaled with respect to the original input image. + * Use pixDestroy to delete the image after use. + */ + Pix* GetBinaryImage(PageIteratorLevel level) const; + + /** + * Returns an image of the current object at the given level in greyscale + * if available in the input. To guarantee a binary image use BinaryImage. + * NOTE that in order to give the best possible image, the bounds are + * expanded slightly over the binary connected component, by the supplied + * padding, so the top-left position of the returned image is returned + * in (left,top). These will most likely not match the coordinates + * returned by BoundingBox. + * Use pixDestroy to delete the image after use. + */ + Pix* GetImage(PageIteratorLevel level, int padding, + int* left, int* top) const; + + /** + * Returns the baseline of the current object at the given level. + * The baseline is the line that passes through (x1, y1) and (x2, y2). + * 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; + + /** + * Returns orientation for the block the iterator points to. + * orientation, writing_direction, textline_order: see publictypes.h + * deskew_angle: after rotating the block so the text orientation is + * upright, how many radians does one have to rotate the + * block anti-clockwise for it to be level? + * -Pi/4 <= deskew_angle <= Pi/4 + */ + void Orientation(tesseract::Orientation *orientation, + tesseract::WritingDirection *writing_direction, + tesseract::TextlineOrder *textline_order, + float *deskew_angle) const; + + /** + * Returns information about the current paragraph, if available. + * + * justification - + * LEFT if ragged right, or fully justified and script is left-to-right. + * RIGHT if ragged left, or fully justified and script is right-to-left. + * unknown if it looks like source code or we have very few lines. + * is_list_item - + * true if we believe this is a member of an ordered or unordered list. + * is_crown - + * true if the first line of the paragraph is aligned with the other + * lines of the paragraph even though subsequent paragraphs have first + * line indents. This typically indicates that this is the continuation + * of a previous paragraph or that it is the very first paragraph in + * the chapter. + * first_line_indent - + * For LEFT aligned paragraphs, the first text line of paragraphs of + * this kind are indented this many pixels from the left edge of the + * rest of the paragraph. + * for RIGHT aligned paragraphs, the first text line of paragraphs of + * this kind are indented this many pixels from the right edge of the + * rest of the paragraph. + * NOTE 1: This value may be negative. + * NOTE 2: if *is_crown == true, the first line of this paragraph is + * actually flush, and first_line_indent is set to the "common" + * first_line_indent for subsequent paragraphs in this block + * of text. + */ + void ParagraphInfo(tesseract::ParagraphJustification *justification, + bool *is_list_item, + bool *is_crown, + int *first_line_indent) const; + + 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); + + /** Pointer to the page_res owned by the API. */ + PAGE_RES* page_res_; + /** Pointer to the Tesseract object owned by the API. */ + 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_; + /** + * The current input WERD being iterated. If there is an output from OCR, + * then word_ is NULL. Owned by the API + */ + WERD* word_; + /** The length of the current word_. */ + int word_length_; + /** The current blob index within the word. */ + int blob_index_; + /** + * Iterator to the blobs within the word. If NULL, then we are iterating + * OCR results in the box_word. + * Owned by this ResultIterator. + */ + C_BLOB_IT* cblob_it_; + /** Parameters saved from the Thresholder. Needed to rebuild coordinates.*/ + int scale_; + int scaled_yres_; + int rect_left_; + int rect_top_; + int rect_width_; + int rect_height_; +}; + +} // namespace tesseract. + +#endif // TESSERACT_CCMAIN_PAGEITERATOR_H__ diff --git a/Tesseract/include/tesseract/params.h b/Tesseract/include/tesseract/params.h new file mode 100644 index 0000000..f95ac63 --- /dev/null +++ b/Tesseract/include/tesseract/params.h @@ -0,0 +1,296 @@ +/********************************************************************** + * File: params.h + * Description: Class definitions of the *_VAR classes for tunable constants. + * Author: Ray Smith + * Created: Fri Feb 22 11:26:25 GMT 1991 + * + * (C) Copyright 1991, Hewlett-Packard Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** http://www.apache.org/licenses/LICENSE-2.0 + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ** See the License for the specific language governing permissions and + ** limitations under the License. + * + **********************************************************************/ + +#ifndef PARAMS_H +#define PARAMS_H + +#include + +#include "genericvector.h" +#include "strngs.h" + +namespace tesseract { + +class IntParam; +class BoolParam; +class StringParam; +class DoubleParam; + +// Enum for constraints on what kind of params should be set by SetParam(). +enum SetParamConstraint { + SET_PARAM_CONSTRAINT_NONE, + SET_PARAM_CONSTRAINT_DEBUG_ONLY, + SET_PARAM_CONSTRAINT_NON_DEBUG_ONLY, + SET_PARAM_CONSTRAINT_NON_INIT_ONLY, +}; + +struct ParamsVectors { + GenericVector int_params; + GenericVector bool_params; + GenericVector string_params; + GenericVector double_params; +}; + +// Utility functions for working with Tesseract parameters. +class ParamUtils { + public: + // Reads a file of parameter definitions and set/modify the values therein. + // If the filename begins with a + or -, the BoolVariables will be + // ORed or ANDed with any current values. + // Blank lines and lines beginning # are ignored. + // Values may have any whitespace after the name and are the rest of line. + static bool ReadParamsFile( + const char *file, // filename to read + SetParamConstraint constraint, + ParamsVectors *member_params); + + // Read parameters from the given file pointer (stop at end_offset). + static bool ReadParamsFromFp(FILE *fp, inT64 end_offset, + SetParamConstraint constraint, + ParamsVectors *member_params); + + // Set a parameters to have the given value. + static bool SetParam(const char *name, const char* value, + SetParamConstraint constraint, + ParamsVectors *member_params); + + // Returns the pointer to the parameter with the given name (of the + // appropriate type) if it was found in the vector obtained from + // GlobalParams() or in the given member_params. + template + static T *FindParam(const char *name, + const GenericVector &global_vec, + const GenericVector &member_vec) { + int i; + for (i = 0; i < global_vec.size(); ++i) { + if (strcmp(global_vec[i]->name_str(), name) == 0) return global_vec[i]; + } + for (i = 0; i < member_vec.size(); ++i) { + if (strcmp(member_vec[i]->name_str(), name) == 0) return member_vec[i]; + } + return NULL; + } + // Removes the given pointer to the param from the given vector. + template + static void RemoveParam(T *param_ptr, GenericVector *vec) { + for (int i = 0; i < vec->size(); ++i) { + if ((*vec)[i] == param_ptr) { + vec->remove(i); + return; + } + } + } + // Fetches the value of the named param as a STRING. Returns false if not + // found. + static bool GetParamAsString(const char *name, + const ParamsVectors* member_params, + STRING *value); + + // Print parameters to the given file. + static void PrintParams(FILE *fp, const ParamsVectors *member_params); +}; + +// Definition of various parameter types. +class Param { + public: + ~Param() {} + + const char *name_str() const { return name_; } + const char *info_str() const { return info_; } + bool is_init() const { return init_; } + bool is_debug() const { return debug_; } + bool constraint_ok(SetParamConstraint constraint) const { + return (constraint == SET_PARAM_CONSTRAINT_NONE || + (constraint == SET_PARAM_CONSTRAINT_DEBUG_ONLY && + this->is_debug()) || + (constraint == SET_PARAM_CONSTRAINT_NON_DEBUG_ONLY && + !this->is_debug()) || + (constraint == SET_PARAM_CONSTRAINT_NON_INIT_ONLY && + !this->is_init())); + } + + protected: + Param(const char *name, const char *comment, bool init) : + name_(name), info_(comment), init_(init) { + debug_ = (strstr(name, "debug") != NULL) || (strstr(name, "display")); + } + + const char *name_; // name of this parameter + const char *info_; // for menus + bool init_; // needs to be set before init + bool debug_; +}; + +class IntParam : public Param { + public: + IntParam(inT32 value, const char *name, const char *comment, bool init, + ParamsVectors *vec) : Param(name, comment, init) { + value_ = value; + params_vec_ = &(vec->int_params); + vec->int_params.push_back(this); + } + ~IntParam() { ParamUtils::RemoveParam(this, params_vec_); } + operator inT32() const { return value_; } + void set_value(inT32 value) { value_ = value; } + + private: + inT32 value_; + // Pointer to the vector that contains this param (not owened by this class). + GenericVector *params_vec_; +}; + +class BoolParam : public Param { + public: + BoolParam(bool value, const char *name, const char *comment, bool init, + ParamsVectors *vec) : Param(name, comment, init) { + value_ = value; + params_vec_ = &(vec->bool_params); + vec->bool_params.push_back(this); + } + ~BoolParam() { ParamUtils::RemoveParam(this, params_vec_); } + operator BOOL8() const { return value_; } + void set_value(BOOL8 value) { value_ = value; } + + private: + BOOL8 value_; + // Pointer to the vector that contains this param (not owned by this class). + GenericVector *params_vec_; +}; + +class StringParam : public Param { + public: + StringParam(const char *value, const char *name, + const char *comment, bool init, + ParamsVectors *vec) : Param(name, comment, init) { + value_ = value; + params_vec_ = &(vec->string_params); + vec->string_params.push_back(this); + } + ~StringParam() { ParamUtils::RemoveParam(this, params_vec_); } + operator STRING &() { return value_; } + const char *string() const { return value_.string(); } + bool empty() { return value_.length() <= 0; } + void set_value(const STRING &value) { value_ = value; } + + private: + STRING value_; + // Pointer to the vector that contains this param (not owened by this class). + GenericVector *params_vec_; +}; + +class DoubleParam : public Param { + public: + DoubleParam(double value, const char *name, const char *comment, + bool init, ParamsVectors *vec) : Param(name, comment, init) { + value_ = value; + params_vec_ = &(vec->double_params); + vec->double_params.push_back(this); + } + ~DoubleParam() { ParamUtils::RemoveParam(this, params_vec_); } + operator double() const { return value_; } + void set_value(double value) { value_ = value; } + + private: + double value_; + // Pointer to the vector that contains this param (not owned by this class). + GenericVector *params_vec_; +}; + +} // namespace tesseract + +// Global parameter lists. +// +// To avoid the problem of undetermined order of static initialization +// global_params are accessed through the GlobalParams function that +// initializes the static pointer to global_params only on the first +// first time GlobalParams() is called. +// +// TODO(daria): remove GlobalParams() when all global Tesseract +// parameters are converted to members. +tesseract::ParamsVectors *GlobalParams(); + +/************************************************************************* + * Note on defining parameters. + * + * The values of the parameters defined with *_INIT_* macros are guaranteed + * to be loaded from config files before Tesseract initialization is done + * (there is no such guarantee for parameters defined with the other macros). + *************************************************************************/ + +#define INT_VAR_H(name,val,comment)\ + tesseract::IntParam name + +#define BOOL_VAR_H(name,val,comment)\ + tesseract::BoolParam name + +#define STRING_VAR_H(name,val,comment)\ + tesseract::StringParam name + +#define double_VAR_H(name,val,comment)\ + tesseract::DoubleParam name + +#define INT_VAR(name,val,comment)\ + tesseract::IntParam name(val,#name,comment,false,GlobalParams()) + +#define BOOL_VAR(name,val,comment)\ + tesseract::BoolParam name(val,#name,comment,false,GlobalParams()) + +#define STRING_VAR(name,val,comment)\ + tesseract::StringParam name(val,#name,comment,false,GlobalParams()) + +#define double_VAR(name,val,comment)\ + tesseract::DoubleParam name(val,#name,comment,false,GlobalParams()) + +#define INT_INIT_VAR(name,val,comment)\ + tesseract::IntParam name(val,#name,comment,true,GlobalParams()) + +#define BOOL_INIT_VAR(name,val,comment)\ + tesseract::BoolParam name(val,#name,comment,true,GlobalParams()) + +#define STRING_INIT_VAR(name,val,comment)\ + tesseract::StringParam name(val,#name,comment,true,GlobalParams()) + +#define double_INIT_VAR(name,val,comment)\ + tesseract::DoubleParam name(val,#name,comment,true,GlobalParams()) + +#define INT_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, false, vec) + +#define BOOL_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, false, vec) + +#define STRING_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, false, vec) + +#define double_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, false, vec) + +#define INT_INIT_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, true, vec) + +#define BOOL_INIT_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, true, vec) + +#define STRING_INIT_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, true, vec) + +#define double_INIT_MEMBER(name, val, comment, vec)\ + name(val, #name, comment, true, vec) + +#endif diff --git a/Tesseract/include/tesseract/platform.h b/Tesseract/include/tesseract/platform.h new file mode 100644 index 0000000..4f8a816 --- /dev/null +++ b/Tesseract/include/tesseract/platform.h @@ -0,0 +1,72 @@ +/////////////////////////////////////////////////////////////////////// +// 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 +#ifdef __GNUC__ +#define ultoa _ultoa +typedef struct _BLOB { + unsigned int cbSize; + char *pBlobData; +} BLOB, *LPBLOB; +#endif /* __GNUC__ */ +#define SIGNED +#define snprintf _snprintf +#if (_MSC_VER <= 1400) +#define vsnprintf _vsnprintf +#endif /* _WIN32 */ +#else +#define __UNIX__ +#include +#ifndef PATH_MAX +#define MAX_PATH 4096 +#else +#define MAX_PATH PATH_MAX +#endif +#define SIGNED signed +#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__ diff --git a/Tesseract/include/tesseract/publictypes.h b/Tesseract/include/tesseract/publictypes.h new file mode 100644 index 0000000..3640d54 --- /dev/null +++ b/Tesseract/include/tesseract/publictypes.h @@ -0,0 +1,249 @@ +/////////////////////////////////////////////////////////////////////// +// 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"); +// 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_CCSTRUCT_PUBLICTYPES_H__ +#define TESSERACT_CCSTRUCT_PUBLICTYPES_H__ + +// This file contains types that are used both by the API and internally +// to Tesseract. In order to decouple the API from Tesseract and prevent cyclic +// dependencies, THIS FILE SHOULD NOT DEPEND ON ANY OTHER PART OF TESSERACT. +// Restated: It is OK for low-level Tesseract files to include publictypes.h, +// 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. */ +const int kPointsPerInch = 72; + +/** + * 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. + * 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_COUNT +}; + +/** Returns true if PolyBlockType is of horizontal line type */ +inline bool PTIsLineType(PolyBlockType type) { + return type == PT_HORZ_LINE || type == PT_VERT_LINE; +} +/** Returns true if PolyBlockType is of image type */ +inline bool PTIsImageType(PolyBlockType type) { + return type == PT_FLOWING_IMAGE || type == PT_HEADING_IMAGE || + type == PT_PULLOUT_IMAGE; +} +/** Returns true if PolyBlockType is of text type */ +inline bool PTIsTextType(PolyBlockType type) { + return type == PT_FLOWING_TEXT || type == PT_HEADING_TEXT || + type == PT_PULLOUT_TEXT || type == PT_TABLE || + type == PT_VERTICAL_TEXT || type == PT_CAPTION_TEXT || + type == PT_INLINE_EQUATION; +} + +/** String name for each block type. Keep in sync with PolyBlockType. */ +extern const char* kPolyBlockNames[]; + +namespace tesseract { +/** + * +------------------+ Orientation Example: + * | 1 Aaaa Aaaa Aaaa | ==================== + * | Aaa aa aaa aa | To left is a diagram of some (1) English and + * | aaaaaa A aa aaa. | (2) Chinese text and a (3) photo credit. + * | 2 | + * | ####### c c C | Upright Latin characters are represented as A and a. + * | ####### c c c | '<' represents a latin character rotated + * | < ####### c c c | anti-clockwise 90 degrees. + * | < ####### c c | + * | < ####### . c | Upright Chinese characters are represented C and c. + * | 3 ####### c | + * +------------------+ NOTA BENE: enum values here should match goodoc.proto + + * If you orient your head so that "up" aligns with Orientation, + * then the characters will appear "right side up" and readable. + * + * In the example above, both the English and Chinese paragraphs are oriented + * so their "up" is the top of the page (page up). The photo credit is read + * with one's head turned leftward ("up" is to page left). + * + * The values of this enum match the convention of Tesseract's osdetect.h +*/ +enum Orientation { + ORIENTATION_PAGE_UP = 0, + ORIENTATION_PAGE_RIGHT = 1, + ORIENTATION_PAGE_DOWN = 2, + ORIENTATION_PAGE_LEFT = 3, +}; + +/** + * The grapheme clusters within a line of text are laid out logically + * in this direction, judged when looking at the text line rotated so that + * its Orientation is "page up". + * + * 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, + WRITING_DIRECTION_TOP_TO_BOTTOM = 2, +}; + +/** + * The text lines are read in the given sequence. + * + * In English, the order is top-to-bottom. + * In Chinese, vertical text lines are read right-to-left. Mongolian is + * written in vertical columns top to bottom like Chinese, but the lines + * order left-to right. + * + * 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, + TEXTLINE_ORDER_TOP_TO_BOTTOM = 2, +}; + +/** + * 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_COUNT ///< Number of enum entries. +}; + +/** + * Macros that act on a PageSegMode to determine whether components of + * layout analysis are enabled. + * *Depend critically on the order of elements of PageSegMode.* +*/ +#define PSM_OSD_ENABLED(pageseg_mode) ((pageseg_mode) <= PSM_AUTO_OSD) +#define PSM_COL_FIND_ENABLED(pageseg_mode) \ + ((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_AUTO) +#define PSM_BLOCK_FIND_ENABLED(pageseg_mode) \ + ((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_COLUMN) +#define PSM_LINE_FIND_ENABLED(pageseg_mode) \ + ((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_BLOCK) +#define PSM_WORD_FIND_ENABLED(pageseg_mode) \ + ((pageseg_mode) >= PSM_AUTO_OSD && (pageseg_mode) <= PSM_SINGLE_LINE) + +/** + * 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. +}; + +/** + * JUSTIFICATION_UNKNONW + * The alignment is not clearly one of the other options. This could happen + * for example if there are only one or two lines of text or the text looks + * like source code or poetry. + * + * NOTA BENE: Fully justified paragraphs (text aligned to both left and right + * margins) are marked by Tesseract with JUSTIFICATION_LEFT if their text + * is written with a left-to-right script and with JUSTIFICATION_RIGHT if + * their text is written in a right-to-left script. + * + * Interpretation for text read in vertical lines: + * "Left" is wherever the starting reading position is. + * + * JUSTIFICATION_LEFT + * Each line, except possibly the first, is flush to the same left tab stop. + * + * JUSTIFICATION_CENTER + * The text lines of the paragraph are centered about a line going + * down through their middle of the text lines. + * + * JUSTIFICATION_RIGHT + * Each line, except possibly the first, is flush to the same right tab stop. +*/ +enum ParagraphJustification { + JUSTIFICATION_UNKNOWN, + JUSTIFICATION_LEFT, + JUSTIFICATION_CENTER, + JUSTIFICATION_RIGHT, +}; + +/** + * When Tesseract/Cube is initialized we can choose to instantiate/load/run + * only the Tesseract part, only the Cube part or both along with the combiner. + * The preference of which engine to use is stored in tessedit_ocr_engine_mode. + * + * ATTENTION: When modifying this enum, please make sure to make the + * 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 + OEM_CUBE_ONLY, // Run Cube only - better accuracy, but slower + OEM_TESSERACT_CUBE_COMBINED, // Run both and combine results - best accuracy + OEM_DEFAULT // Specify this mode when calling init_*(), + // 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. +}; + +} // namespace tesseract. + +#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H__ diff --git a/Tesseract/include/tesseract/resultiterator.h b/Tesseract/include/tesseract/resultiterator.h new file mode 100644 index 0000000..c9d880b --- /dev/null +++ b/Tesseract/include/tesseract/resultiterator.h @@ -0,0 +1,237 @@ +/////////////////////////////////////////////////////////////////////// +// File: resultiterator.h +// Description: Iterator for tesseract results that is capable of +// 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"); +// 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_RESULT_ITERATOR_H__ +#define TESSERACT_CCMAIN_RESULT_ITERATOR_H__ + +#include "platform.h" +#include "ltrresultiterator.h" +#include "genericvector.h" + +class BLOB_CHOICE_IT; +class WERD_RES; +class STRING; + +namespace tesseract { + +class Tesseract; + +class TESS_API ResultIterator : public LTRResultIterator { + public: + static ResultIterator *StartOfParagraph(const LTRResultIterator &resit); + + /** + * ResultIterator is copy constructible! + * The default copy constructor works just fine for us. + */ + virtual ~ResultIterator() {} + + // ============= Moving around within the page ============. + /** + * Moves the iterator to point to the start of the page to begin + * an iteration. + */ + virtual void Begin(); + + /** + * Moves to the start of the next object at the given level in the + * page hierarchy in the appropriate reading order and returns false if + * the end of the page was reached. + * NOTE that RIL_SYMBOL will skip non-text blocks, but all other + * PageIteratorLevel level values will visit each non-text block once. + * Think of non text blocks as containing a single para, with a single line, + * with a single imaginary word. + * Calls to Next with different levels may be freely intermixed. + * This function iterates words in right-to-left scripts correctly, if + * the appropriate language has been loaded into Tesseract. + */ + virtual bool Next(PageIteratorLevel level); + + /** + * IsAtBeginningOf() returns whether we're at the logical beginning of the + * given level. (as opposed to ResultIterator's left-to-right top-to-bottom + * order). Otherwise, this acts the same as PageIterator::IsAtBeginningOf(). + * For a full description, see pageiterator.h + */ + virtual bool IsAtBeginningOf(PageIteratorLevel level) const; + + /** + * 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; + + // ============= Accessing data ==============. + + /** + * 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; + + /** + * 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 =============. + + /** + * Yields the reading order as a sequence of indices and (optional) + * meta-marks for a set of words (given left-to-right). + * The meta marks are passed as negative values: + * kMinorRunStart Start of minor direction text. + * kMinorRunEnd End of minor direction text. + * kComplexWord The next indexed word contains both left-to-right and + * right-to-left characters and was treated as neutral. + * + * For example, suppose we have five words in a text line, + * indexed [0,1,2,3,4] from the leftmost side of the text line. + * The following are all believable reading_orders: + * + * Left-to-Right (in ltr paragraph): + * { 0, 1, 2, 3, 4 } + * Left-to-Right (in rtl paragraph): + * { kMinorRunStart, 0, 1, 2, 3, 4, kMinorRunEnd } + * Right-to-Left (in rtl paragraph): + * { 4, 3, 2, 1, 0 } + * Left-to-Right except for an RTL phrase in words 2, 3 in an ltr paragraph: + * { 0, 1, kMinorRunStart, 3, 2, kMinorRunEnd, 4 } + */ + static void CalculateTextlineOrder( + bool paragraph_is_ltr, + const GenericVector &word_dirs, + GenericVectorEqEq *reading_order); + + static const int kMinorRunStart; + static const int kMinorRunEnd; + static const int kComplexWord; + + 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); + + private: + /** + * Calculates the current paragraph's dominant writing direction. + * Typically, members should use current_paragraph_ltr_ instead. + */ + bool CurrentParagraphIsLtr() const; + + /** + * Returns word indices as measured from resit->RestartRow() = index 0 + * for the reading order of words within a textline given an iterator + * into the middle of the text line. + * In addition to non-negative word indices, the following negative values + * may be inserted: + * kMinorRunStart Start of minor direction text. + * kMinorRunEnd End of minor direction text. + * kComplexWord The previous word contains both left-to-right and + * right-to-left characters and was treated as neutral. + */ + void CalculateTextlineOrder(bool paragraph_is_ltr, + const LTRResultIterator &resit, + GenericVectorEqEq *indices) const; + /** Same as above, but the caller's ssd gets filled in if ssd != NULL. */ + void CalculateTextlineOrder(bool paragraph_is_ltr, + const LTRResultIterator &resit, + GenericVector *ssd, + GenericVectorEqEq *indices) const; + + /** + * What is the index of the current word in a strict left-to-right reading + * of the row? + */ + int LTRWordIndex() const; + + /** + * Given an iterator pointing at a word, returns the logical reading order + * of blob indices for the word. + */ + void CalculateBlobOrder(GenericVector *blob_indices) const; + + /** Precondition: current_paragraph_is_ltr_ is set. */ + void MoveToLogicalStartOfTextline(); + + /** + * Precondition: current_paragraph_is_ltr_ and in_minor_direction_ + * are set. + */ + void MoveToLogicalStartOfWord(); + + /** Are we pointing at the final (reading order) symbol of the word? */ + bool IsAtFinalSymbolOfWord() const; + + /** Are we pointing at the first (reading order) symbol of the word? */ + bool IsAtFirstSymbolOfWord() const; + + /** + * 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; + + /** Appends the current word in reading order to the given buffer.*/ + void AppendUTF8WordText(STRING *text) const; + + /** + * Appends the text of the current text line, *assuming this iterator is + * positioned at the beginning of the text line* This function + * updates the iterator to point to the first position past the text line. + * 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); + + /** + * Appends the text of the current paragraph in reading order + * to the given buffer. + * Each textline is terminated in a single newline character, and the + * paragraph gets an extra newline at the end. + */ + void AppendUTF8ParagraphText(STRING *text) const; + + /** Returns whether the bidi_debug flag is set to at least min_level. */ + bool BidiDebug(int min_level) const; + + bool current_paragraph_is_ltr_; + + /** + * Is the currently pointed-at character at the beginning of + * a minor-direction run? + */ + bool at_beginning_of_minor_run_; + + /** Is the currently pointed-at character in a minor-direction sequence? */ + bool in_minor_direction_; +}; + +} // namespace tesseract. + +#endif // TESSERACT_CCMAIN_RESULT_ITERATOR_H__ diff --git a/Tesseract/include/tesseract/serialis.h b/Tesseract/include/tesseract/serialis.h new file mode 100644 index 0000000..9d80acd --- /dev/null +++ b/Tesseract/include/tesseract/serialis.h @@ -0,0 +1,43 @@ +/********************************************************************** + * 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 +#include +#include +#include "memry.h" +#include "errcode.h" +#include "fileerr.h" + +// Switch endinan. +extern DLLSYM uinT64 reverse64(uinT64); +extern DLLSYM uinT32 reverse32(uinT32); +extern DLLSYM uinT16 reverse16(uinT16); + +/*********************************************************************** + QUOTE_IT MACRO DEFINITION + =========================== +Replace with "". may be an arbitrary number of tokens +***********************************************************************/ + +#define QUOTE_IT( parm ) #parm + +#endif diff --git a/Tesseract/include/tesseract/strngs.h b/Tesseract/include/tesseract/strngs.h new file mode 100644 index 0000000..04d7314 --- /dev/null +++ b/Tesseract/include/tesseract/strngs.h @@ -0,0 +1,161 @@ +/********************************************************************** + * 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 +#include +#include "platform.h" +#include "memry.h" + +// 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 class GenericVector; + +class TESS_API STRING +{ + public: + STRING(); + STRING(const STRING &string); + STRING(const char *string); + ~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); + + BOOL8 contains(const char c) const; + inT32 length() const; + inT32 size() const { return length(); } + const char *string() const; + + inline char* strdup() const { + inT32 len = length() + 1; + return strncpy(new char[len], GetCStr(), len); + } + +#if STRING_IS_PROTECTED + const char &operator[] (inT32 index) const; + // len is number of chars in s to insert starting at index in this string + void insert_range(inT32 index, const char*s, int len); + void erase_range(inT32 index, int len); +#else + char &operator[] (inT32 index) const; +#endif + void split(const char c, GenericVector *splited); + void truncate_at(inT32 index); + + BOOL8 operator== (const STRING & string) const; + BOOL8 operator!= (const STRING & string) const; + BOOL8 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); + + // ensure capcaity but keep pointer encapsulated + inline void ensure(inT32 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 NULL (not even the '\0') + // else if used_ > 0 then it is strlen() + 1 (because it includes '\0') + // else strlen is >= 0 (not NULL) but needs to be computed. + // 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() == NULL) : (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 min_capacity); + + void FixHeader() const; // make used_ non-negative, even if const + + char* AllocData(int used, int capacity); + void DiscardData(); +}; +#endif diff --git a/Tesseract/include/tesseract/tesscallback.h b/Tesseract/include/tesseract/tesscallback.h new file mode 100644 index 0000000..b34cdb1 --- /dev/null +++ b/Tesseract/include/tesseract/tesscallback.h @@ -0,0 +1,1238 @@ +/////////////////////////////////////////////////////////////////////// +// File: tesscallback.h +// Description: classes and functions to replace pointer-to-functions +// Author: Samuel Charron +// +// (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 _TESS_CALLBACK_SPECIALIZATIONS_H +#define _TESS_CALLBACK_SPECIALIZATIONS_H + +#include "host.h" // For NULL. + +struct TessCallbackUtils_ { + static void FailIsRepeatable(const char* name); +}; + + +class TessClosure { + public: + virtual ~TessClosure() { } + virtual void Run() = 0; +}; + +template +class TessResultCallback { + public: + virtual ~TessResultCallback() { } + virtual R Run() = 0; +}; + +template +class _ConstTessMemberResultCallback_0_0 : public TessResultCallback { + public: + typedef TessResultCallback base; + typedef R (T::*MemberSignature)() const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_0( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run() { + if (!del) { + R result = (object_->*member_)(); + return result; + } else { + R result = (object_->*member_)(); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _ConstTessMemberResultCallback_0_0 + : public TessClosure { + public: + typedef TessClosure base; + typedef void (T::*MemberSignature)() const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_0( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run() { + if (!del) { + (object_->*member_)(); + } else { + (object_->*member_)(); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_0::base* +NewTessCallback( + const T1* obj, R (T2::*member)() const) { + return new _ConstTessMemberResultCallback_0_0( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_0::base* +NewPermanentTessCallback( + const T1* obj, R (T2::*member)() const) { + return new _ConstTessMemberResultCallback_0_0( + obj, member); +} +#endif + +template +class _TessMemberResultCallback_0_0 : public TessResultCallback { + public: + typedef TessResultCallback base; + typedef R (T::*MemberSignature)() ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_0( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run() { + if (!del) { + R result = (object_->*member_)(); + return result; + } else { + R result = (object_->*member_)(); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessMemberResultCallback_0_0 + : public TessClosure { + public: + typedef TessClosure base; + typedef void (T::*MemberSignature)() ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_0( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run() { + if (!del) { + (object_->*member_)(); + } else { + (object_->*member_)(); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_0::base* +NewTessCallback( + T1* obj, R (T2::*member)() ) { + return new _TessMemberResultCallback_0_0( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_0::base* +NewPermanentTessCallback( + T1* obj, R (T2::*member)() ) { + return new _TessMemberResultCallback_0_0( + obj, member); +} +#endif + +template +class _TessFunctionResultCallback_0_0 : public TessResultCallback { + public: + typedef TessResultCallback base; + typedef R (*FunctionSignature)(); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_0( + FunctionSignature function) + : function_(function) { + } + + virtual R Run() { + if (!del) { + R result = (*function_)(); + return result; + } else { + R result = (*function_)(); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessFunctionResultCallback_0_0 + : public TessClosure { + public: + typedef TessClosure base; + typedef void (*FunctionSignature)(); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_0( + FunctionSignature function) + : function_(function) { + } + + virtual void Run() { + if (!del) { + (*function_)(); + } else { + (*function_)(); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + } + } +}; + +template +inline typename _TessFunctionResultCallback_0_0::base* +NewTessCallback(R (*function)()) { + return new _TessFunctionResultCallback_0_0(function); +} + +template +inline typename _TessFunctionResultCallback_0_0::base* +NewPermanentTessCallback(R (*function)()) { + return new _TessFunctionResultCallback_0_0(function); +} + +template +class TessCallback1 { + public: + virtual ~TessCallback1() { } + virtual void Run(A1) = 0; +}; + +template +class TessResultCallback1 { + public: + virtual ~TessResultCallback1() { } + virtual R Run(A1) = 0; +}; + +template +class _ConstTessMemberResultCallback_0_1 : public TessResultCallback1 { + public: + typedef TessResultCallback1 base; + typedef R (T::*MemberSignature)(A1) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_1( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1) { + if (!del) { + R result = (object_->*member_)(a1); + return result; + } else { + R result = (object_->*member_)(a1); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _ConstTessMemberResultCallback_0_1 + : public TessCallback1 { + public: + typedef TessCallback1 base; + typedef void (T::*MemberSignature)(A1) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_1( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1) { + if (!del) { + (object_->*member_)(a1); + } else { + (object_->*member_)(a1); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_1::base* +NewTessCallback( + const T1* obj, R (T2::*member)(A1) const) { + return new _ConstTessMemberResultCallback_0_1( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_1::base* +NewPermanentTessCallback( + const T1* obj, R (T2::*member)(A1) const) { + return new _ConstTessMemberResultCallback_0_1( + obj, member); +} +#endif + +template +class _TessMemberResultCallback_0_1 : public TessResultCallback1 { + public: + typedef TessResultCallback1 base; + typedef R (T::*MemberSignature)(A1) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_1( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1) { + if (!del) { + R result = (object_->*member_)(a1); + return result; + } else { + R result = (object_->*member_)(a1); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessMemberResultCallback_0_1 + : public TessCallback1 { + public: + typedef TessCallback1 base; + typedef void (T::*MemberSignature)(A1) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_1( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1) { + if (!del) { + (object_->*member_)(a1); + } else { + (object_->*member_)(a1); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_1::base* +NewTessCallback( + T1* obj, R (T2::*member)(A1) ) { + return new _TessMemberResultCallback_0_1( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_1::base* +NewPermanentTessCallback( + T1* obj, R (T2::*member)(A1) ) { + return new _TessMemberResultCallback_0_1( + obj, member); +} +#endif + +template +class _TessFunctionResultCallback_0_1 : public TessResultCallback1 { + public: + typedef TessResultCallback1 base; + typedef R (*FunctionSignature)(A1); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_1( + FunctionSignature function) + : function_(function) { + } + + virtual R Run(A1 a1) { + if (!del) { + R result = (*function_)(a1); + return result; + } else { + R result = (*function_)(a1); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessFunctionResultCallback_0_1 + : public TessCallback1 { + public: + typedef TessCallback1 base; + typedef void (*FunctionSignature)(A1); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_1( + FunctionSignature function) + : function_(function) { + } + + virtual void Run(A1 a1) { + if (!del) { + (*function_)(a1); + } else { + (*function_)(a1); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + } + } +}; + +template +inline typename _TessFunctionResultCallback_0_1::base* +NewTessCallback(R (*function)(A1)) { + return new _TessFunctionResultCallback_0_1(function); +} + +template +inline typename _TessFunctionResultCallback_0_1::base* +NewPermanentTessCallback(R (*function)(A1)) { + return new _TessFunctionResultCallback_0_1(function); +} + +template +class TessCallback2 { + public: + virtual ~TessCallback2() { } + virtual void Run(A1,A2) = 0; +}; + +template +class TessResultCallback2 { + public: + virtual ~TessResultCallback2() { } + virtual R Run(A1,A2) = 0; +}; + +template +class _ConstTessMemberResultCallback_0_2 : public TessResultCallback2 { + public: + typedef TessResultCallback2 base; + typedef R (T::*MemberSignature)(A1,A2) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_2( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1,A2 a2) { + if (!del) { + R result = (object_->*member_)(a1,a2); + return result; + } else { + R result = (object_->*member_)(a1,a2); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _ConstTessMemberResultCallback_0_2 + : public TessCallback2 { + public: + typedef TessCallback2 base; + typedef void (T::*MemberSignature)(A1,A2) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_2( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1,A2 a2) { + if (!del) { + (object_->*member_)(a1,a2); + } else { + (object_->*member_)(a1,a2); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_2::base* +NewTessCallback( + const T1* obj, R (T2::*member)(A1,A2) const) { + return new _ConstTessMemberResultCallback_0_2( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_2::base* +NewPermanentTessCallback( + const T1* obj, R (T2::*member)(A1,A2) const) { + return new _ConstTessMemberResultCallback_0_2( + obj, member); +} +#endif + +template +class _TessMemberResultCallback_0_2 : public TessResultCallback2 { + public: + typedef TessResultCallback2 base; + typedef R (T::*MemberSignature)(A1,A2) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_2( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1,A2 a2) { + if (!del) { + R result = (object_->*member_)(a1,a2); + return result; + } else { + R result = (object_->*member_)(a1,a2); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessMemberResultCallback_0_2 + : public TessCallback2 { + public: + typedef TessCallback2 base; + typedef void (T::*MemberSignature)(A1,A2) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_2( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1,A2 a2) { + if (!del) { + (object_->*member_)(a1,a2); + } else { + (object_->*member_)(a1,a2); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_2::base* +NewTessCallback( + T1* obj, R (T2::*member)(A1,A2) ) { + return new _TessMemberResultCallback_0_2( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_2::base* +NewPermanentTessCallback( + T1* obj, R (T2::*member)(A1,A2) ) { + return new _TessMemberResultCallback_0_2( + obj, member); +} +#endif + +template +class _TessFunctionResultCallback_0_2 : public TessResultCallback2 { + public: + typedef TessResultCallback2 base; + typedef R (*FunctionSignature)(A1,A2); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_2( + FunctionSignature function) + : function_(function) { + } + + virtual R Run(A1 a1,A2 a2) { + if (!del) { + R result = (*function_)(a1,a2); + return result; + } else { + R result = (*function_)(a1,a2); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessFunctionResultCallback_0_2 + : public TessCallback2 { + public: + typedef TessCallback2 base; + typedef void (*FunctionSignature)(A1,A2); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_2( + FunctionSignature function) + : function_(function) { + } + + virtual void Run(A1 a1,A2 a2) { + if (!del) { + (*function_)(a1,a2); + } else { + (*function_)(a1,a2); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + } + } +}; + +template +inline typename _TessFunctionResultCallback_0_2::base* +NewTessCallback(R (*function)(A1,A2)) { + return new _TessFunctionResultCallback_0_2(function); +} + +template +inline typename _TessFunctionResultCallback_0_2::base* +NewPermanentTessCallback(R (*function)(A1,A2)) { + return new _TessFunctionResultCallback_0_2(function); +} + +template +class TessCallback3 { + public: + virtual ~TessCallback3() { } + virtual void Run(A1,A2,A3) = 0; +}; + +template +class TessResultCallback3 { + public: + virtual ~TessResultCallback3() { } + virtual R Run(A1,A2,A3) = 0; +}; + +template +class _ConstTessMemberResultCallback_0_3 : public TessResultCallback3 { + public: + typedef TessResultCallback3 base; + typedef R (T::*MemberSignature)(A1,A2,A3) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_3( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + R result = (object_->*member_)(a1,a2,a3); + return result; + } else { + R result = (object_->*member_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _ConstTessMemberResultCallback_0_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (T::*MemberSignature)(A1,A2,A3) const; + + private: + const T* object_; + MemberSignature member_; + + public: + inline _ConstTessMemberResultCallback_0_3( + const T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + (object_->*member_)(a1,a2,a3); + } else { + (object_->*member_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_3::base* +NewTessCallback( + const T1* obj, R (T2::*member)(A1,A2,A3) const) { + return new _ConstTessMemberResultCallback_0_3( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_0_3::base* +NewPermanentTessCallback( + const T1* obj, R (T2::*member)(A1,A2,A3) const) { + return new _ConstTessMemberResultCallback_0_3( + obj, member); +} +#endif + +template +class _TessMemberResultCallback_0_3 : public TessResultCallback3 { + public: + typedef TessResultCallback3 base; + typedef R (T::*MemberSignature)(A1,A2,A3) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_3( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual R Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + R result = (object_->*member_)(a1,a2,a3); + return result; + } else { + R result = (object_->*member_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessMemberResultCallback_0_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (T::*MemberSignature)(A1,A2,A3) ; + + private: + T* object_; + MemberSignature member_; + + public: + inline _TessMemberResultCallback_0_3( + T* object, MemberSignature member) + : object_(object), + member_(member) { + } + + virtual void Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + (object_->*member_)(a1,a2,a3); + } else { + (object_->*member_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_3::base* +NewTessCallback( + T1* obj, R (T2::*member)(A1,A2,A3) ) { + return new _TessMemberResultCallback_0_3( + obj, member); +} +#endif + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_0_3::base* +NewPermanentTessCallback( + T1* obj, R (T2::*member)(A1,A2,A3) ) { + return new _TessMemberResultCallback_0_3( + obj, member); +} +#endif + +template +class _TessFunctionResultCallback_0_3 : public TessResultCallback3 { + public: + typedef TessResultCallback3 base; + typedef R (*FunctionSignature)(A1,A2,A3); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_3( + FunctionSignature function) + : function_(function) { + } + + virtual R Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + R result = (*function_)(a1,a2,a3); + return result; + } else { + R result = (*function_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessFunctionResultCallback_0_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (*FunctionSignature)(A1,A2,A3); + + private: + FunctionSignature function_; + + public: + inline _TessFunctionResultCallback_0_3( + FunctionSignature function) + : function_(function) { + } + + virtual void Run(A1 a1,A2 a2,A3 a3) { + if (!del) { + (*function_)(a1,a2,a3); + } else { + (*function_)(a1,a2,a3); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + } + } +}; + +template +inline typename _TessFunctionResultCallback_0_3::base* +NewTessCallback(R (*function)(A1,A2,A3)) { + return new _TessFunctionResultCallback_0_3(function); +} + +template +inline typename _TessFunctionResultCallback_0_3::base* +NewPermanentTessCallback(R (*function)(A1,A2,A3)) { + return new _TessFunctionResultCallback_0_3(function); +} + +// Specified by TR1 [4.7.2] Reference modifications. +template struct remove_reference; +template struct remove_reference { typedef T type; }; +template struct remove_reference { typedef T type; }; + +// Identity::type is a typedef of T. Useful for preventing the +// compiler from inferring the type of an argument in templates. +template +struct Identity { + typedef T type; +}; + +template +class _ConstTessMemberResultCallback_1_3 + : public TessResultCallback3 { + public: + typedef TessResultCallback3 base; + typedef R (T::*MemberSignature)(P1,A1,A2,A3) const; + + private: + T* object_; + MemberSignature member_; + typename remove_reference::type p1_; + + public: + inline _ConstTessMemberResultCallback_1_3(T* object, + MemberSignature member, P1 p1) + : object_(object), member_(member), p1_(p1) { } + + virtual R Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + R result = (object_->*member_)(p1_,a1,a2,a3); + return result; + } else { + R result = (object_->*member_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _ConstTessMemberResultCallback_1_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (T::*MemberSignature)(P1,A1,A2,A3) const; + + private: + T* object_; + MemberSignature member_; + typename remove_reference::type p1_; + + public: + inline _ConstTessMemberResultCallback_1_3(T* object, + MemberSignature member, P1 p1) + : object_(object), member_(member), p1_(p1) { } + + virtual void Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + (object_->*member_)(p1_,a1,a2,a3); + } else { + (object_->*member_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_1_3::base* +NewTessCallback( T1* obj, R (T2::*member)(P1,A1,A2,A3) , typename Identity::type p1) { + return new _ConstTessMemberResultCallback_1_3(obj, member, p1); +} +#endif + +#ifndef SWIG +template +inline typename _ConstTessMemberResultCallback_1_3::base* +NewPermanentTessCallback( T1* obj, R (T2::*member)(P1,A1,A2,A3) , typename Identity::type p1) { + return new _ConstTessMemberResultCallback_1_3(obj, member, p1); +} +#endif + +template +class _TessMemberResultCallback_1_3 : public TessResultCallback3 { + public: + typedef TessResultCallback3 base; + typedef R (T::*MemberSignature)(P1,A1,A2,A3) ; + + private: + T* object_; + MemberSignature member_; + typename remove_reference::type p1_; + + public: + inline _TessMemberResultCallback_1_3(T* object, + MemberSignature member, P1 p1) + : object_(object), member_(member), p1_(p1) { } + + virtual R Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + R result = (object_->*member_)(p1_,a1,a2,a3); + return result; + } else { + R result = (object_->*member_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessMemberResultCallback_1_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (T::*MemberSignature)(P1,A1,A2,A3) ; + + private: + T* object_; + MemberSignature member_; + typename remove_reference::type p1_; + + public: + inline _TessMemberResultCallback_1_3(T* object, + MemberSignature member, P1 p1) + : object_(object), member_(member), p1_(p1) { } + + virtual void Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + (object_->*member_)(p1_,a1,a2,a3); + } else { + (object_->*member_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + member_ = NULL; + delete this; + } + } +}; + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_1_3::base* +NewTessCallback( T1* obj, R (T2::*member)(P1,A1,A2,A3) , typename Identity::type p1) { + return new _TessMemberResultCallback_1_3(obj, member, p1); +} +#endif + +#ifndef SWIG +template +inline typename _TessMemberResultCallback_1_3::base* +NewPermanentTessCallback( T1* obj, R (T2::*member)(P1,A1,A2,A3) , typename Identity::type p1) { + return new _TessMemberResultCallback_1_3(obj, member, p1); +} +#endif + +template +class _TessFunctionResultCallback_1_3 : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef R (*FunctionSignature)(P1,A1,A2,A3); + + private: + FunctionSignature function_; + typename remove_reference::type p1_; + + public: + inline _TessFunctionResultCallback_1_3(FunctionSignature function, P1 p1) + : function_(function), p1_(p1) { } + + virtual R Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + R result = (*function_)(p1_,a1,a2,a3); + return result; + } else { + R result = (*function_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + return result; + } + } +}; + +template +class _TessFunctionResultCallback_1_3 + : public TessCallback3 { + public: + typedef TessCallback3 base; + typedef void (*FunctionSignature)(P1,A1,A2,A3); + + private: + FunctionSignature function_; + typename remove_reference::type p1_; + + public: + inline _TessFunctionResultCallback_1_3(FunctionSignature function, P1 p1) + : function_(function), p1_(p1) { } + + virtual void Run(A1 a1, A2 a2, A3 a3) { + if (!del) { + (*function_)(p1_,a1,a2,a3); + } else { + (*function_)(p1_,a1,a2,a3); + // zero out the pointer to ensure segfault if used again + function_ = NULL; + delete this; + } + } +}; + +template +inline typename _TessFunctionResultCallback_1_3::base* +NewTessCallback(R (*function)(P1,A1,A2,A3), typename Identity::type p1) { + return new _TessFunctionResultCallback_1_3(function, p1); +} + +template +inline typename _TessFunctionResultCallback_1_3::base* +NewPermanentTessCallback(R (*function)(P1,A1,A2,A3), typename Identity::type p1) { + return new _TessFunctionResultCallback_1_3(function, p1); +} + +#endif /* _TESS_CALLBACK_SPECIALIZATIONS_H */ diff --git a/Tesseract/include/tesseract/thresholder.h b/Tesseract/include/tesseract/thresholder.h new file mode 100644 index 0000000..a22cf0c --- /dev/null +++ b/Tesseract/include/tesseract/thresholder.h @@ -0,0 +1,191 @@ +/////////////////////////////////////////////////////////////////////// +// 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__ + +class IMAGE; +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 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 only the metadata, not the underlying + /// image buffer. It promises to treat the source as read-only in either case, + /// but in return assumes that the Pix or image buffer remain valid + /// throughout the life of the ImageThresholder. + /// 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 image_bytespp_ >= 3; + } + + /// Returns true if the source image is binary. + bool IsBinary() const { + return image_bytespp_ == 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? + /// Implementations should provide the ability to source and target Pix + /// where possible. A future version of Tesseract may choose to use Pix + /// as its internal representation and discard IMAGE altogether. + /// Because of that, an implementation that sources and targets Pix may end up + /// with less copies than an implementation that does not. + /// NOTE: Opposite to SetImage for raw images, SetImage for Pix clones its + /// input, so the source pix may be pixDestroyed immediately after. + void SetImage(const Pix* pix); + + /// Threshold the source image as efficiently as possible to the output Pix. + /// Creates a Pix and sets pix to point to the resulting pointer. + /// Caller must use pixDestroy to free the created Pix. + virtual void ThresholdToPix(Pix** pix); + + /// 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. + /// The returned Pix must be pixDestroyed. + /// This function will be used in the future by the page layout analysis, and + /// the layout analysis that uses it will only be available with Leptonica, + /// so there is no raw equivalent. + Pix* GetPixRectGrey(); + + 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 threshold the rectangle, taking everything except the image buffer + /// pointer from the class, to the output Pix. + void OtsuThresholdRectToPix(const unsigned char* imagedata, + int bytes_per_pixel, int bytes_per_line, + Pix** pix) const; + + /// Threshold the rectangle, taking everything except the image buffer pointer + /// from the class, using thresholds/hi_values to the output IMAGE. + void ThresholdRectToPix(const unsigned char* imagedata, + int bytes_per_pixel, int bytes_per_line, + const int* thresholds, const int* hi_values, + Pix** pix) const; + + /// Copy the raw image rectangle, taking all data from the class, to the Pix. + void RawRectToPix(Pix** pix) const; + + protected: + /// Clone or other copy of the source Pix. + /// The pix will always be PixDestroy()ed on destruction of the class. + Pix* pix_; + /// Exactly one of pix_ and image_data_ is not NULL. + const unsigned char* image_data_; //< Raw source image. + + int image_width_; //< Width of source image/pix. + int image_height_; //< Height of source image/pix. + int image_bytespp_; //< Bytes per pixel of source image/pix. + int image_bytespl_; //< Bytes per line of source image/pix. + // 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__ diff --git a/Tesseract/include/tesseract/unichar.h b/Tesseract/include/tesseract/unichar.h new file mode 100644 index 0000000..d1c8e51 --- /dev/null +++ b/Tesseract/include/tesseract/unichar.h @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////// +// 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"); +// 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_UNICHAR_H__ +#define TESSERACT_CCUTIL_UNICHAR_H__ + +#include +#include + +// 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 + +// A UNICHAR_ID is the unique id of a unichar. +typedef int UNICHAR_ID; + +// A variable to indicate an invalid or uninitialized unichar id. +static const int INVALID_UNICHAR_ID = -1; +// A special unichar that corresponds to INVALID_UNICHAR_ID. +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. +}; + +// The UNICHAR class holds a single classification result. This may be +// a single Unicode character (stored as between 1 and 4 utf8 bytes) or +// multple Unicode characters representing the NFKC expansion of a ligature +// such as fi, ffl etc. These are also stored as utf8. +class UNICHAR { + public: + UNICHAR() { + memset(chars, 0, UNICHAR_LEN); + } + + // 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); + + // Construct from a single UCS4 character. + explicit UNICHAR(int unicode); + + // Default copy constructor and operator= are OK. + + // Get the first character as UCS-4. + int first_uni() const; + + // 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; + } + + // Get a UTF8 string, but NOT NULL terminated. + const char* utf8() const { + return chars; + } + + // Get a terminated UTF8 string: Must delete[] it after use. + 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); + + 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]; +}; + +#endif // TESSERACT_CCUTIL_UNICHAR_H__ diff --git a/Tesseract/include/tesseract/unicharmap.h b/Tesseract/include/tesseract/unicharmap.h new file mode 100644 index 0000000..ad90158 --- /dev/null +++ b/Tesseract/include/tesseract/unicharmap.h @@ -0,0 +1,82 @@ +/////////////////////////////////////////////////////////////////////// +// File: unicharmap.h +// Description: Unicode character/ligature to integer id class. +// Author: Thomas Kielbus +// Created: Wed Jun 28 17:05:01 PDT 2006 +// +// (C) Copyright 2006, Google Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////// + +#ifndef TESSERACT_CCUTIL_UNICHARMAP_H__ +#define TESSERACT_CCUTIL_UNICHARMAP_H__ + +#include "unichar.h" + +// A UNICHARMAP stores unique unichars. Each of them is associated with one +// UNICHAR_ID. +class UNICHARMAP { + public: + + // Create an empty UNICHARMAP + UNICHARMAP(); + + ~UNICHARMAP(); + + // Insert the given unichar represention in the UNICHARMAP and associate it + // with the given id. The length of the representation MUST be non-zero. + void insert(const char* const unichar_repr, UNICHAR_ID id); + + // Return the id associated with the given unichar representation, + // this representation MUST exist within the UNICHARMAP. + // The length of the representation MUST be non-zero. + UNICHAR_ID unichar_to_id(const char* const unichar_repr) const; + + // Return the id associated with the given unichar representation, + // this representation MUST exist within the UNICHARMAP. The first + // length characters (maximum) from unichar_repr are used. The length + // MUST be non-zero. + UNICHAR_ID unichar_to_id(const char* const unichar_repr, int length) const; + + // Return true if the given unichar representation is already present in the + // UNICHARMAP. The length of the representation MUST be non-zero. + bool contains(const char* const unichar_repr) const; + + // Return true if the given unichar representation is already present in the + // UNICHARMAP. The first length characters (maximum) from unichar_repr are + // used. The length MUST be non-zero. + bool contains(const char* const unichar_repr, int length) const; + + // Return the minimum number of characters that must be used from this string + // to obtain a match in the UNICHARMAP. + int minmatch(const char* const unichar_repr) const; + + // Clear the UNICHARMAP. All previous data is lost. + void clear(); + + private: + + // The UNICHARMAP is represented as a tree whose nodes are of type + // UNICHARMAP_NODE. + struct UNICHARMAP_NODE { + + UNICHARMAP_NODE(); + ~UNICHARMAP_NODE(); + + UNICHARMAP_NODE* children; + UNICHAR_ID id; + }; + + UNICHARMAP_NODE* nodes; +}; + +#endif // TESSERACT_CCUTIL_UNICHARMAP_H__ diff --git a/Tesseract/include/tesseract/unicharset.h b/Tesseract/include/tesseract/unicharset.h new file mode 100644 index 0000000..24f1b28 --- /dev/null +++ b/Tesseract/include/tesseract/unicharset.h @@ -0,0 +1,884 @@ +/////////////////////////////////////////////////////////////////////// +// File: unicharset.h +// Description: Unicode character/ligature set class. +// Author: Thomas Kielbus +// Created: Wed Jun 28 17:05:01 PDT 2006 +// +// (C) Copyright 2006, Google Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////// + +#ifndef TESSERACT_CCUTIL_UNICHARSET_H__ +#define TESSERACT_CCUTIL_UNICHARSET_H__ + +#include "errcode.h" +#include "helpers.h" +#include "strngs.h" +#include "tesscallback.h" +#include "unichar.h" +#include "unicharmap.h" + +class CHAR_FRAGMENT { + public: + // Minimum number of characters used for fragment representation. + static const int kMinLen = 6; + // Maximum number of characters used for fragment representation. + static const int kMaxLen = 3 + UNICHAR_LEN + 2; + // Maximum number of fragments per character. + static const int kMaxChunks = 5; + + // Setters and Getters. + inline void set_all(const char *unichar, int pos, int total, bool natural) { + set_unichar(unichar); + set_pos(pos); + set_total(total); + set_natural(natural); + } + inline void set_unichar(const char *uch) { + strncpy(this->unichar, uch, UNICHAR_LEN); + this->unichar[UNICHAR_LEN] = '\0'; + } + inline void set_pos(int p) { this->pos = p; } + inline void set_total(int t) { this->total = t; } + inline const char* get_unichar() const { return this->unichar; } + inline int get_pos() const { return this->pos; } + inline int get_total() const { return this->total; } + + // Returns the string that represents a fragment + // with the given unichar, pos and total. + static STRING to_string(const char *unichar, int pos, int total, + bool natural); + // Returns the string that represents this fragment. + STRING to_string() const { + return to_string(unichar, pos, total, natural); + } + + // Checks whether a fragment has the same unichar, + // position and total as the given inputs. + inline bool equals(const char *other_unichar, + int other_pos, int other_total) const { + return (strcmp(this->unichar, other_unichar) == 0 && + this->pos == other_pos && this->total == other_total); + } + inline bool equals(const CHAR_FRAGMENT *other) const { + return this->equals(other->get_unichar(), + other->get_pos(), + other->get_total()); + } + + // Checks whether a given fragment is a continuation of this fragment. + // Assumes that the given fragment pointer is not NULL. + inline bool is_continuation_of(const CHAR_FRAGMENT *fragment) const { + return (strcmp(this->unichar, fragment->get_unichar()) == 0 && + this->total == fragment->get_total() && + this->pos == fragment->get_pos() + 1); + } + + // Returns true if this fragment is a beginning fragment. + inline bool is_beginning() const { return this->pos == 0; } + + // Returns true if this fragment is an ending fragment. + inline bool is_ending() const { return this->pos == this->total-1; } + + // Returns true if the fragment was a separate component to begin with, + // ie did not need chopping to be isolated, but may have been separated + // out from a multi-outline blob. + inline bool is_natural() const { return natural; } + void set_natural(bool value) { natural = value; } + + // Parses the string to see whether it represents a character fragment + // (rather than a regular character). If so, allocates memory for a new + // CHAR_FRAGMENT instance and fills it in with the corresponding fragment + // information. Fragments are of the form: + // |m|1|2, meaning chunk 1 of 2 of character m, or + // |:|1n2, meaning chunk 1 of 2 of character :, and no chopping was needed + // to divide the parts, as they were already separate connected components. + // + // If parsing succeeded returns the pointer to the allocated CHAR_FRAGMENT + // instance, otherwise (if the string does not represent a fragment or it + // looks like it does, but parsing it as a fragment fails) returns NULL. + // + // Note: The caller is responsible for deallocating memory + // associated with the returned pointer. + static CHAR_FRAGMENT *parse_from_string(const char *str); + + private: + char unichar[UNICHAR_LEN + 1]; + // True if the fragment was a separate component to begin with, + // ie did not need chopping to be isolated, but may have been separated + // out from a multi-outline blob. + bool natural; + inT16 pos; // fragment position in the character + inT16 total; // total number of fragments in the character +}; + +// The UNICHARSET class is an utility class for Tesseract that holds the +// set of characters that are used by the engine. Each character is identified +// by a unique number, from 0 to (size - 1). +class UNICHARSET { + public: + // Custom list of characters and their ligature forms (UTF8) + // These map to unicode values in the private use area (PUC) and are supported + // by only few font families (eg. Wyld, Adobe Caslon Pro). + static const char* kCustomLigatures[][2]; + + // ICU 2.0 UCharDirection enum (from third_party/icu/include/unicode/uchar.h) + enum Direction { + U_LEFT_TO_RIGHT = 0, + U_RIGHT_TO_LEFT = 1, + U_EUROPEAN_NUMBER = 2, + U_EUROPEAN_NUMBER_SEPARATOR = 3, + U_EUROPEAN_NUMBER_TERMINATOR = 4, + U_ARABIC_NUMBER = 5, + U_COMMON_NUMBER_SEPARATOR = 6, + U_BLOCK_SEPARATOR = 7, + U_SEGMENT_SEPARATOR = 8, + U_WHITE_SPACE_NEUTRAL = 9, + U_OTHER_NEUTRAL = 10, + U_LEFT_TO_RIGHT_EMBEDDING = 11, + U_LEFT_TO_RIGHT_OVERRIDE = 12, + U_RIGHT_TO_LEFT_ARABIC = 13, + U_RIGHT_TO_LEFT_EMBEDDING = 14, + U_RIGHT_TO_LEFT_OVERRIDE = 15, + U_POP_DIRECTIONAL_FORMAT = 16, + U_DIR_NON_SPACING_MARK = 17, + U_BOUNDARY_NEUTRAL = 18, + U_CHAR_DIRECTION_COUNT + }; + + // Create an empty UNICHARSET + UNICHARSET(); + + ~UNICHARSET(); + + // Return the UNICHAR_ID of a given unichar representation within the + // UNICHARSET. + const UNICHAR_ID unichar_to_id(const char* const unichar_repr) const; + + // Return the UNICHAR_ID of a given unichar representation within the + // UNICHARSET. Only the first length characters from unichar_repr are used. + const UNICHAR_ID unichar_to_id(const char* const unichar_repr, + int length) const; + + // Return the minimum number of bytes that matches a legal UNICHAR_ID, + // while leaving a legal UNICHAR_ID afterwards. In other words, if there + // is both a short and a long match to the string, return the length that + // ensures there is a legal match after it. + int step(const char* str) const; + + // Return whether the given UTF-8 string is encodable with this UNICHARSET. + // If not encodable, write the first byte offset which cannot be converted + // into the second (return) argument. + bool encodable_string(const char *str, int *first_bad_position) const; + + // Return the unichar representation corresponding to the given UNICHAR_ID + // within the UNICHARSET. + const char* const id_to_unichar(UNICHAR_ID id) const; + + // Return the UTF8 representation corresponding to the given UNICHAR_ID after + // resolving any private encodings internal to Tesseract. This method is + // preferrable to id_to_unichar for outputting text that will be visible to + // external applications. + const char* const id_to_unichar_ext(UNICHAR_ID id) const; + + // Return a STRING that reformats the utf8 str into the str followed + // by its hex unicodes. + static STRING debug_utf8_str(const char* str); + + // Return a STRING containing debug information on the unichar, including + // the id_to_unichar, its hex unicodes and the properties. + STRING debug_str(UNICHAR_ID id) const; + STRING debug_str(const char * unichar_repr) const { + return debug_str(unichar_to_id(unichar_repr)); + } + + // Add a unichar representation to the set. + void unichar_insert(const char* const unichar_repr); + + // Return true if the given unichar id exists within the set. + // Relies on the fact that unichar ids are contiguous in the unicharset. + bool contains_unichar_id(UNICHAR_ID unichar_id) const { + return unichar_id != INVALID_UNICHAR_ID && unichar_id < size_used && + unichar_id >= 0; + } + + // Return true if the given unichar representation exists within the set. + bool contains_unichar(const char* const unichar_repr) const; + bool contains_unichar(const char* const unichar_repr, int length) const; + + // Return true if the given unichar representation corresponds to the given + // UNICHAR_ID within the set. + bool eq(UNICHAR_ID unichar_id, const char* const unichar_repr) const; + + // Delete CHAR_FRAGMENTs stored in properties of unichars array. + void delete_pointers_in_unichars() { + for (int i = 0; i < size_used; ++i) { + if (unichars[i].properties.fragment != NULL) { + delete unichars[i].properties.fragment; + unichars[i].properties.fragment = NULL; + } + } + } + + // Clear the UNICHARSET (all the previous data is lost). + void clear() { + if (script_table != NULL) { + for (int i = 0; i < script_table_size_used; ++i) + delete[] script_table[i]; + delete[] script_table; + script_table = NULL; + script_table_size_used = 0; + } + if (unichars != NULL) { + delete_pointers_in_unichars(); + delete[] unichars; + unichars = NULL; + } + script_table_size_reserved = 0; + size_reserved = 0; + size_used = 0; + ids.clear(); + top_bottom_set_ = false; + script_has_upper_lower_ = false; + script_has_xheight_ = false; + null_sid_ = 0; + common_sid_ = 0; + latin_sid_ = 0; + cyrillic_sid_ = 0; + greek_sid_ = 0; + han_sid_ = 0; + hiragana_sid_ = 0; + katakana_sid_ = 0; + } + + // Return the size of the set (the number of different UNICHAR it holds). + int size() const { + return size_used; + } + + // Reserve enough memory space for the given number of UNICHARS + void reserve(int unichars_number); + + // Opens the file indicated by filename and saves unicharset to that file. + // Returns true if the operation is successful. + bool save_to_file(const char * const filename) const { + FILE* file = fopen(filename, "w+b"); + if (file == NULL) return false; + bool result = save_to_file(file); + fclose(file); + return result; + } + + // Saves the content of the UNICHARSET to the given file. + // Returns true if the operation is successful. + bool save_to_file(FILE *file) const; + + // Load a unicharset from a unicharset file that has been loaded into + // the given memory buffer. + // Returns true if the operation is successful. + bool load_from_inmemory_file(const char* const memory, int mem_size, + bool skip_fragments); + // Returns true if the operation is successful. + bool load_from_inmemory_file(const char* const memory, int mem_size) { + return load_from_inmemory_file(memory, mem_size, false); + } + + // Opens the file indicated by filename and loads the UNICHARSET + // from the given file. The previous data is lost. + // Returns true if the operation is successful. + bool load_from_file(const char* const filename, bool skip_fragments) { + FILE* file = fopen(filename, "rb"); + if (file == NULL) return false; + bool result = load_from_file(file, skip_fragments); + fclose(file); + return result; + } + // returns true if the operation is successful. + bool load_from_file(const char* const filename) { + return load_from_file(filename, false); + } + + // Loads the UNICHARSET from the given file. The previous data is lost. + // Returns true if the operation is successful. + bool load_from_file(FILE *file, bool skip_fragments); + bool load_from_file(FILE *file) { return load_from_file(file, false); } + + // Sets up internal data after loading the file, based on the char + // properties. Called from load_from_file, but also needs to be run + // during set_unicharset_properties. + void post_load_setup(); + + // Returns true if right_to_left scripts are significant in the unicharset, + // but without being so sensitive that "universal" unicharsets containing + // characters from many scripts, like orientation and script detection, + // look like they are right_to_left. + bool major_right_to_left() const; + + // Set a whitelist and/or blacklist of characters to recognize. + // An empty or NULL whitelist enables everything (minus any blacklist). + // An empty or NULL blacklist disables nothing. + // The blacklist overrides the whitelist. + // Each list is a string of utf8 character strings. Boundaries between + // unicharset units are worked out automatically, and characters not in + // the unicharset are silently ignored. + void set_black_and_whitelist(const char* blacklist, const char* whitelist); + + // Set the isalpha property of the given unichar to the given value. + void set_isalpha(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.isalpha = value; + } + + // Set the islower property of the given unichar to the given value. + void set_islower(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.islower = value; + } + + // Set the isupper property of the given unichar to the given value. + void set_isupper(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.isupper = value; + } + + // Set the isdigit property of the given unichar to the given value. + void set_isdigit(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.isdigit = value; + } + + // Set the ispunctuation property of the given unichar to the given value. + void set_ispunctuation(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.ispunctuation = value; + } + + // Set the isngram property of the given unichar to the given value. + void set_isngram(UNICHAR_ID unichar_id, bool value) { + unichars[unichar_id].properties.isngram = value; + } + + // Set the script name of the given unichar to the given value. + // Value is copied and thus can be a temporary; + void set_script(UNICHAR_ID unichar_id, const char* value) { + unichars[unichar_id].properties.script_id = add_script(value); + } + + // Set other_case unichar id in the properties for the given unichar id. + void set_other_case(UNICHAR_ID unichar_id, UNICHAR_ID other_case) { + unichars[unichar_id].properties.other_case = other_case; + } + + // Set the direction property of the given unichar to the given value. + void set_direction(UNICHAR_ID unichar_id, UNICHARSET::Direction value) { + unichars[unichar_id].properties.direction = value; + } + + // Set mirror unichar id in the properties for the given unichar id. + void set_mirror(UNICHAR_ID unichar_id, UNICHAR_ID mirror) { + unichars[unichar_id].properties.mirror = mirror; + } + + // Record normalized version of unichar with the given unichar_id. + void set_normed(UNICHAR_ID unichar_id, const char* normed) { + unichars[unichar_id].properties.normed = normed; + } + + // Return the isalpha property of the given unichar. + bool get_isalpha(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.isalpha; + } + + // Return the islower property of the given unichar. + bool get_islower(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.islower; + } + + // Return the isupper property of the given unichar. + bool get_isupper(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.isupper; + } + + // Return the isdigit property of the given unichar. + bool get_isdigit(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.isdigit; + } + + // Return the ispunctuation property of the given unichar. + bool get_ispunctuation(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.ispunctuation; + } + + // Return the isngram property of the given unichar. + bool get_isngram(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return false; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.isngram; + } + + // Returns whether the unichar id represents a unicode value in the private + // use area. + bool get_isprivate(UNICHAR_ID unichar_id) const; + + // Returns true if the ids have useful min/max top/bottom values. + bool top_bottom_useful() const { + return top_bottom_set_; + } + // Sets all ranges to empty, so they can be expanded to set the values. + void set_ranges_empty(); + // Sets all the properties for this unicharset given a src_unicharset with + // everything set. The unicharsets don't have to be the same, and graphemes + // are correctly accounted for. + void SetPropertiesFromOther(const UNICHARSET& src); + // Expands the tops and bottoms and widths for this unicharset given a + // src_unicharset with ranges in it. The unicharsets don't have to be the + // same, and graphemes are correctly accounted for. + void ExpandRangesFromOther(const UNICHARSET& src); + // For each id in src, if it does not occur in this, add it, as in + // SetPropertiesFromOther, otherwise expand the ranges, as in + // ExpandRangesFromOther. + void AppendOtherUnicharset(const UNICHARSET& src); + // Returns the min and max bottom and top of the given unichar in + // baseline-normalized coordinates, ie, where the baseline is + // kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight + // (See normalis.h for the definitions). + void get_top_bottom(UNICHAR_ID unichar_id, + int* min_bottom, int* max_bottom, + int* min_top, int* max_top) const { + if (INVALID_UNICHAR_ID == unichar_id) { + *min_bottom = *min_top = 0; + *max_bottom = *max_top = 256; // kBlnCellHeight + return; + } + ASSERT_HOST(contains_unichar_id(unichar_id)); + *min_bottom = unichars[unichar_id].properties.min_bottom; + *max_bottom = unichars[unichar_id].properties.max_bottom; + *min_top = unichars[unichar_id].properties.min_top; + *max_top = unichars[unichar_id].properties.max_top; + } + void set_top_bottom(UNICHAR_ID unichar_id, + int min_bottom, int max_bottom, + int min_top, int max_top) { + unichars[unichar_id].properties.min_bottom = + static_cast(ClipToRange(min_bottom, 0, MAX_UINT8)); + unichars[unichar_id].properties.max_bottom = + static_cast(ClipToRange(max_bottom, 0, MAX_UINT8)); + unichars[unichar_id].properties.min_top = + static_cast(ClipToRange(min_top, 0, MAX_UINT8)); + unichars[unichar_id].properties.max_top = + static_cast(ClipToRange(max_top, 0, MAX_UINT8)); + } + // Returns the width range of the given unichar in baseline-normalized + // coordinates, ie, where the baseline is kBlnBaselineOffset and the + // meanline is kBlnBaselineOffset + kBlnXHeight. + // (See normalis.h for the definitions). + void get_width_range(UNICHAR_ID unichar_id, + int* min_width, int* max_width) const { + if (INVALID_UNICHAR_ID == unichar_id) { + *min_width = 0; + *max_width = 256; // kBlnCellHeight; + return; + } + ASSERT_HOST(contains_unichar_id(unichar_id)); + *min_width = unichars[unichar_id].properties.min_width; + *max_width = unichars[unichar_id].properties.max_width; + } + void set_width_range(UNICHAR_ID unichar_id, int min_width, int max_width) { + unichars[unichar_id].properties.min_width = + static_cast(ClipToRange(min_width, 0, MAX_INT16)); + unichars[unichar_id].properties.max_width = + static_cast(ClipToRange(max_width, 0, MAX_INT16)); + } + // Returns the range of the x-bearing of the given unichar in + // baseline-normalized coordinates, ie, where the baseline is + // kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight. + // (See normalis.h for the definitions). + void get_bearing_range(UNICHAR_ID unichar_id, + int* min_bearing, int* max_bearing) const { + if (INVALID_UNICHAR_ID == unichar_id) { + *min_bearing = *max_bearing = 0; + return; + } + ASSERT_HOST(contains_unichar_id(unichar_id)); + *min_bearing = unichars[unichar_id].properties.min_bearing; + *max_bearing = unichars[unichar_id].properties.max_bearing; + } + void set_bearing_range(UNICHAR_ID unichar_id, + int min_bearing, int max_bearing) { + unichars[unichar_id].properties.min_bearing = + static_cast(ClipToRange(min_bearing, 0, MAX_INT16)); + unichars[unichar_id].properties.max_bearing = + static_cast(ClipToRange(max_bearing, 0, MAX_INT16)); + } + // Returns the range of the x-advance of the given unichar in + // baseline-normalized coordinates, ie, where the baseline is + // kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight. + // (See normalis.h for the definitions). + void get_advance_range(UNICHAR_ID unichar_id, + int* min_advance, int* max_advance) const { + if (INVALID_UNICHAR_ID == unichar_id) { + *min_advance = *max_advance = 0; + return; + } + ASSERT_HOST(contains_unichar_id(unichar_id)); + *min_advance = unichars[unichar_id].properties.min_advance; + *max_advance = unichars[unichar_id].properties.max_advance; + } + void set_advance_range(UNICHAR_ID unichar_id, + int min_advance, int max_advance) { + unichars[unichar_id].properties.min_advance = + static_cast(ClipToRange(min_advance, 0, MAX_INT16)); + unichars[unichar_id].properties.max_advance = + static_cast(ClipToRange(max_advance, 0, MAX_INT16)); + } + + // Return the script name of the given unichar. + // The returned pointer will always be the same for the same script, it's + // managed by unicharset and thus MUST NOT be deleted + int get_script(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return null_sid_; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.script_id; + } + + // Return the character properties, eg. alpha/upper/lower/digit/punct, + // as a bit field of unsigned int. + unsigned int get_properties(UNICHAR_ID unichar_id) const; + + // Return the character property as a single char. If a character has + // multiple attributes, the main property is defined by the following order: + // upper_case : 'A' + // lower_case : 'a' + // alpha : 'x' + // digit : '0' + // punctuation: 'p' + char get_chartype(UNICHAR_ID unichar_id) const; + + // Get other_case unichar id in the properties for the given unichar id. + UNICHAR_ID get_other_case(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.other_case; + } + + // Returns the direction property of the given unichar. + Direction get_direction(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return UNICHARSET::U_OTHER_NEUTRAL; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.direction; + } + + // Get mirror unichar id in the properties for the given unichar id. + UNICHAR_ID get_mirror(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.mirror; + } + + // Returns UNICHAR_ID of the corresponding lower-case unichar. + UNICHAR_ID to_lower(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID; + ASSERT_HOST(contains_unichar_id(unichar_id)); + if (unichars[unichar_id].properties.islower) return unichar_id; + return unichars[unichar_id].properties.other_case; + } + + // Returns UNICHAR_ID of the corresponding upper-case unichar. + UNICHAR_ID to_upper(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return INVALID_UNICHAR_ID; + ASSERT_HOST(contains_unichar_id(unichar_id)); + if (unichars[unichar_id].properties.isupper) return unichar_id; + return unichars[unichar_id].properties.other_case; + } + + // Return a pointer to the CHAR_FRAGMENT class if the given + // unichar id represents a character fragment. + const CHAR_FRAGMENT *get_fragment(UNICHAR_ID unichar_id) const { + if (INVALID_UNICHAR_ID == unichar_id) return NULL; + ASSERT_HOST(contains_unichar_id(unichar_id)); + return unichars[unichar_id].properties.fragment; + } + + // Return the isalpha property of the given unichar representation. + bool get_isalpha(const char* const unichar_repr) const { + return get_isalpha(unichar_to_id(unichar_repr)); + } + + // Return the islower property of the given unichar representation. + bool get_islower(const char* const unichar_repr) const { + return get_islower(unichar_to_id(unichar_repr)); + } + + // Return the isupper property of the given unichar representation. + bool get_isupper(const char* const unichar_repr) const { + return get_isupper(unichar_to_id(unichar_repr)); + } + + // Return the isdigit property of the given unichar representation. + bool get_isdigit(const char* const unichar_repr) const { + return get_isdigit(unichar_to_id(unichar_repr)); + } + + // Return the ispunctuation property of the given unichar representation. + bool get_ispunctuation(const char* const unichar_repr) const { + return get_ispunctuation(unichar_to_id(unichar_repr)); + } + + // Return the character properties, eg. alpha/upper/lower/digit/punct, + // of the given unichar representation + unsigned int get_properties(const char* const unichar_repr) const { + return get_properties(unichar_to_id(unichar_repr)); + } + + char get_chartype(const char* const unichar_repr) const { + return get_chartype(unichar_to_id(unichar_repr)); + } + + // Return the script name of the given unichar representation. + // The returned pointer will always be the same for the same script, it's + // managed by unicharset and thus MUST NOT be deleted + int get_script(const char* const unichar_repr) const { + return get_script(unichar_to_id(unichar_repr)); + } + + // Return a pointer to the CHAR_FRAGMENT class struct if the given + // unichar representation represents a character fragment. + const CHAR_FRAGMENT *get_fragment(const char* const unichar_repr) const { + if (unichar_repr == NULL || unichar_repr[0] == '\0' || + !ids.contains(unichar_repr)) { + return NULL; + } + return get_fragment(unichar_to_id(unichar_repr)); + } + + // Return the isalpha property of the given unichar representation. + // Only the first length characters from unichar_repr are used. + bool get_isalpha(const char* const unichar_repr, + int length) const { + return get_isalpha(unichar_to_id(unichar_repr, length)); + } + + // Return the islower property of the given unichar representation. + // Only the first length characters from unichar_repr are used. + bool get_islower(const char* const unichar_repr, + int length) const { + return get_islower(unichar_to_id(unichar_repr, length)); + } + + // Return the isupper property of the given unichar representation. + // Only the first length characters from unichar_repr are used. + bool get_isupper(const char* const unichar_repr, + int length) const { + return get_isupper(unichar_to_id(unichar_repr, length)); + } + + // Return the isdigit property of the given unichar representation. + // Only the first length characters from unichar_repr are used. + bool get_isdigit(const char* const unichar_repr, + int length) const { + return get_isdigit(unichar_to_id(unichar_repr, length)); + } + + // Return the ispunctuation property of the given unichar representation. + // Only the first length characters from unichar_repr are used. + bool get_ispunctuation(const char* const unichar_repr, + int length) const { + return get_ispunctuation(unichar_to_id(unichar_repr, length)); + } + + // Returns normalized version of unichar with the given unichar_id. + const char *get_normed_unichar(UNICHAR_ID unichar_id) const { + return unichars[unichar_id].properties.normed.string(); + } + + // Return the script name of the given unichar representation. + // Only the first length characters from unichar_repr are used. + // The returned pointer will always be the same for the same script, it's + // managed by unicharset and thus MUST NOT be deleted + int get_script(const char* const unichar_repr, + int length) const { + return get_script(unichar_to_id(unichar_repr, length)); + } + + // Return the (current) number of scripts in the script table + int get_script_table_size() const { + return script_table_size_used; + } + + // Return the script string from its id + const char* get_script_from_script_id(int id) const { + if (id >= script_table_size_used || id < 0) + return null_script; + return script_table[id]; + } + + // Returns the id from the name of the script, or 0 if script is not found. + // Note that this is an expensive operation since it involves iteratively + // comparing strings in the script table. To avoid dependency on STL, we + // won't use a hash. Instead, the calling function can use this to lookup + // and save the ID for relevant scripts for fast comparisons later. + int get_script_id_from_name(const char* script_name) const; + + // Return true if the given script is the null script + bool is_null_script(const char* script) const { + return script == null_script; + } + + // Uniquify the given script. For two scripts a and b, if strcmp(a, b) == 0, + // then the returned pointer will be the same. + // The script parameter is copied and thus can be a temporary. + int add_script(const char* script); + + // Return the enabled property of the given unichar. + bool get_enabled(UNICHAR_ID unichar_id) const { + return unichars[unichar_id].properties.enabled; + } + + + int null_sid() const { return null_sid_; } + int common_sid() const { return common_sid_; } + int latin_sid() const { return latin_sid_; } + int cyrillic_sid() const { return cyrillic_sid_; } + int greek_sid() const { return greek_sid_; } + int han_sid() const { return han_sid_; } + int hiragana_sid() const { return hiragana_sid_; } + int katakana_sid() const { return katakana_sid_; } + int default_sid() const { return default_sid_; } + + // Returns true if the unicharset has the concept of upper/lower case. + bool script_has_upper_lower() const { + return script_has_upper_lower_; + } + // Returns true if the unicharset has the concept of x-height. + // script_has_xheight can be true even if script_has_upper_lower is not, + // when the script has a sufficiently predominant top line with ascenders, + // such as Devanagari and Thai. + bool script_has_xheight() const { + return script_has_xheight_; + } + + private: + + struct UNICHAR_PROPERTIES { + UNICHAR_PROPERTIES(); + // Initializes all properties to sensible default values. + void Init(); + // Sets all ranges wide open. Initialization default in case there are + // no useful values available. + void SetRangesOpen(); + // Sets all ranges to empty. Used before expanding with font-based data. + void SetRangesEmpty(); + // Returns true if any of the top/bottom/width/bearing/advance ranges is + // emtpy. + bool AnyRangeEmpty() const; + // Expands the ranges with the ranges from the src properties. + void ExpandRangesFrom(const UNICHAR_PROPERTIES& src); + // Copies the properties from src into this. + void CopyFrom(const UNICHAR_PROPERTIES& src); + + bool isalpha; + bool islower; + bool isupper; + bool isdigit; + bool ispunctuation; + bool isngram; + bool enabled; + // Possible limits of the top and bottom of the bounding box in + // baseline-normalized coordinates, ie, where the baseline is + // kBlnBaselineOffset and the meanline is kBlnBaselineOffset + kBlnXHeight + // (See normalis.h for the definitions). + uinT8 min_bottom; + uinT8 max_bottom; + uinT8 min_top; + uinT8 max_top; + // Limits on the widths of bounding box, also in baseline-normalized coords. + inT16 min_width; + inT16 max_width; + // Limits on the x-bearing and advance, also in baseline-normalized coords. + inT16 min_bearing; + inT16 max_bearing; + inT16 min_advance; + inT16 max_advance; + int script_id; + UNICHAR_ID other_case; // id of the corresponding upper/lower case unichar + Direction direction; // direction of this unichar + // Mirror property is useful for reverse DAWG lookup for words in + // right-to-left languages (e.g. "(word)" would be in + // '[open paren]' 'w' 'o' 'r' 'd' '[close paren]' in a UTF8 string. + // However, what we want in our DAWG is + // '[open paren]', 'd', 'r', 'o', 'w', '[close paren]' not + // '[close paren]', 'd', 'r', 'o', 'w', '[open paren]'. + UNICHAR_ID mirror; + STRING normed; // normalized version of this unichar + // Contains meta information about the fragment if a unichar represents + // a fragment of a character, otherwise should be set to NULL. + // It is assumed that character fragments are added to the unicharset + // after the corresponding 'base' characters. + CHAR_FRAGMENT *fragment; + }; + + struct UNICHAR_SLOT { + char representation[UNICHAR_LEN + 1]; + UNICHAR_PROPERTIES properties; + }; + + // Gets the properties for a grapheme string, combining properties for + // multiple characters in a meaningful way where possible. + // Returns false if no valid match was found in the unicharset. + // NOTE that script_id, mirror, and other_case refer to this unicharset on + // return and will need redirecting if the target unicharset is different. + bool GetStrProperties(const char* utf8_str, + UNICHAR_PROPERTIES* props) const; + + // Load ourselves from a "file" where our only interface to the file is + // an implementation of fgets(). This is the parsing primitive accessed by + // the public routines load_from_file() and load_from_inmemory_file(). + bool load_via_fgets(TessResultCallback2 *fgets_cb, + bool skip_fragments); + + UNICHAR_SLOT* unichars; + UNICHARMAP ids; + int size_used; + int size_reserved; + char** script_table; + int script_table_size_used; + int script_table_size_reserved; + const char* null_script; + // True if the unichars have their tops/bottoms set. + bool top_bottom_set_; + // True if the unicharset has significant upper/lower case chars. + bool script_has_upper_lower_; + // True if the unicharset has a significant mean-line with significant + // ascenders above that. + bool script_has_xheight_; + + // A few convenient script name-to-id mapping without using hash. + // These are initialized when unicharset file is loaded. Anything + // missing from this list can be looked up using get_script_id_from_name. + int null_sid_; + int common_sid_; + int latin_sid_; + int cyrillic_sid_; + int greek_sid_; + int han_sid_; + int hiragana_sid_; + int katakana_sid_; + // The most frequently occurring script in the charset. + int default_sid_; +}; + +#endif // TESSERACT_CCUTIL_UNICHARSET_H__ diff --git a/Tesseract/lib/libjpeg.a b/Tesseract/lib/libjpeg.a new file mode 100644 index 0000000..da46052 Binary files /dev/null and b/Tesseract/lib/libjpeg.a differ diff --git a/Tesseract/lib/liblept.a b/Tesseract/lib/liblept.a new file mode 100644 index 0000000..4eb7d77 Binary files /dev/null and b/Tesseract/lib/liblept.a differ diff --git a/Tesseract/lib/libtesseract.a b/Tesseract/lib/libtesseract.a new file mode 100644 index 0000000..ccdfe21 Binary files /dev/null and b/Tesseract/lib/libtesseract.a differ diff --git a/Tesseract/share/man/man1/ambiguous_words.1 b/Tesseract/share/man/man1/ambiguous_words.1 new file mode 100644 index 0000000..ce32f4c --- /dev/null +++ b/Tesseract/share/man/man1/ambiguous_words.1 @@ -0,0 +1,46 @@ +'\" t +.\" Title: ambiguous_words +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "AMBIGUOUS_WORDS" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +ambiguous_words \- generate sets of words Tesseract is likely to find ambiguous +.SH "SYNOPSIS" +.sp +\fBambiguous_words\fR [\-l lang] \fITESSDATADIR\fR \fIWORDLIST\fR \fIAMBIGUOUSFILE\fR +.SH "DESCRIPTION" +.sp +ambiguous_words(1) runs Tesseract in a special mode, and for each word in word list, produces a set of words which Tesseract thinks might be ambiguous with it\&. \fITESSDATADIR\fR must be set to the absolute path of a directory containing \fItessdata/lang\&.traineddata\fR\&. +.SH "SEE ALSO" +.sp +tesseract(1) +.SH "COPYING" +.sp +Copyright (C) 2012 Google, Inc\&. Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/cntraining.1 b/Tesseract/share/man/man1/cntraining.1 new file mode 100644 index 0000000..1acc8f8 --- /dev/null +++ b/Tesseract/share/man/man1/cntraining.1 @@ -0,0 +1,54 @@ +'\" t +.\" Title: cntraining +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "CNTRAINING" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +cntraining \- character normalization training for Tesseract +.SH "SYNOPSIS" +.sp +\fBcntraining\fR [\-D \fIdir\fR] \fIFILE\fR\&... +.SH "DESCRIPTION" +.sp +cntraining takes a list of \&.tr files, from which it generates the \fBnormproto\fR data file (the character normalization sensitivity prototypes)\&. +.SH "OPTIONS" +.PP +\-D \fIdir\fR +.RS 4 +Directory to write output files to\&. +.RE +.SH "SEE ALSO" +.sp +tesseract(1), shapeclustering(1), mftraining(1) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "COPYING" +.sp +Copyright (c) Hewlett\-Packard Company, 1988 Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/combine_tessdata.1 b/Tesseract/share/man/man1/combine_tessdata.1 new file mode 100644 index 0000000..926d183 --- /dev/null +++ b/Tesseract/share/man/man1/combine_tessdata.1 @@ -0,0 +1,215 @@ +'\" t +.\" Title: combine_tessdata +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "COMBINE_TESSDATA" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +combine_tessdata \- combine/extract/overwrite Tesseract data +.SH "SYNOPSIS" +.sp +\fBcombine_tessdata\fR [\fIOPTION\fR] \fIFILE\fR\&... +.SH "DESCRIPTION" +.sp +combine_tessdata(1) is the main program to combine/extract/overwrite tessdata components in [lang]\&.traineddata files\&. +.sp +To combine all the individual tessdata components (unicharset, DAWGs, classifier templates, ambiguities, language configs) located at, say, /home/$USER/temp/eng\&.* run: +.sp +.if n \{\ +.RS 4 +.\} +.nf +combine_tessdata /home/$USER/temp/eng\&. +.fi +.if n \{\ +.RE +.\} +.sp +The result will be a combined tessdata file /home/$USER/temp/eng\&.traineddata +.sp +Specify option \-e if you would like to extract individual components from a combined traineddata file\&. For example, to extract language config file and the unicharset from tessdata/eng\&.traineddata run: +.sp +.if n \{\ +.RS 4 +.\} +.nf +combine_tessdata \-e tessdata/eng\&.traineddata \e + /home/$USER/temp/eng\&.config /home/$USER/temp/eng\&.unicharset +.fi +.if n \{\ +.RE +.\} +.sp +The desired config file and unicharset will be written to /home/$USER/temp/eng\&.config /home/$USER/temp/eng\&.unicharset +.sp +Specify option \-o to overwrite individual components of the given [lang]\&.traineddata file\&. For example, to overwrite language config and unichar ambiguities files in tessdata/eng\&.traineddata use: +.sp +.if n \{\ +.RS 4 +.\} +.nf +combine_tessdata \-o tessdata/eng\&.traineddata \e + /home/$USER/temp/eng\&.config /home/$USER/temp/eng\&.unicharambigs +.fi +.if n \{\ +.RE +.\} +.sp +As a result, tessdata/eng\&.traineddata will contain the new language config and unichar ambigs, plus all the original DAWGs, classifier templates, etc\&. +.sp +Note: the file names of the files to extract to and to overwrite from should have the appropriate file suffixes (extensions) indicating their tessdata component type (\&.unicharset for the unicharset, \&.unicharambigs for unichar ambigs, etc)\&. See k*FileSuffix variable in ccutil/tessdatamanager\&.h\&. +.sp +Specify option \-u to unpack all the components to the specified path: +.sp +.if n \{\ +.RS 4 +.\} +.nf +combine_tessdata \-u tessdata/eng\&.traineddata /home/$USER/temp/eng\&. +.fi +.if n \{\ +.RE +.\} +.sp +This will create /home/$USER/temp/eng\&.* files with individual tessdata components from tessdata/eng\&.traineddata\&. +.SH "OPTIONS" +.sp +\fB\-e\fR \fI\&.traineddata\fR \fIFILE\fR\&...: Extracts the specified components from the \&.traineddata file +.sp +\fB\-o\fR \fI\&.traineddata\fR \fIFILE\fR\&...: Overwrites the specified components of the \&.traineddata file with those provided on the comand line\&. +.sp +\fB\-u\fR \fI\&.traineddata\fR \fIPATHPREFIX\fR Unpacks the \&.traineddata using the provided prefix\&. +.SH "CAVEATS" +.sp +\fIPrefix\fR refers to the full file prefix, including period (\&.) +.SH "COMPONENTS" +.sp +The components in a Tesseract lang\&.traineddata file as of Tesseract 3\&.02 are briefly described below; For more information on many of these files, see \m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.PP +lang\&.config +.RS 4 +(Optional) Language\-specific overrides to default config variables\&. +.RE +.PP +lang\&.unicharset +.RS 4 +(Required) The list of symbols that Tesseract recognizes, with properties\&. See unicharset(5)\&. +.RE +.PP +lang\&.unicharambigs +.RS 4 +(Optional) This file contains information on pairs of recognized symbols which are often confused\&. For example, +\fIrn\fR +and +\fIm\fR\&. +.RE +.PP +lang\&.inttemp +.RS 4 +(Required) Character shape templates for each unichar\&. Produced by mftraining(1)\&. +.RE +.PP +lang\&.pffmtable +.RS 4 +(Required) The number of features expected for each unichar\&. Produced by mftraining(1) from +\fB\&.tr\fR +files\&. +.RE +.PP +lang\&.normproto +.RS 4 +(Required) Character normalization prototypes generated by cntraining(1) from +\fB\&.tr\fR +files\&. +.RE +.PP +lang\&.punc\-dawg +.RS 4 +(Optional) A dawg made from punctuation patterns found around words\&. The "word" part is replaced by a single space\&. +.RE +.PP +lang\&.word\-dawg +.RS 4 +(Optional) A dawg made from dictionary words from the language\&. +.RE +.PP +lang\&.number\-dawg +.RS 4 +(Optional) A dawg made from tokens which originally contained digits\&. Each digit is replaced by a space character\&. +.RE +.PP +lang\&.freq\-dawg +.RS 4 +(Optional) A dawg made from the most frequent words which would have gone into word\-dawg\&. +.RE +.PP +lang\&.fixed\-length\-dawgs +.RS 4 +(Optional) Several dawgs of different fixed lengths \(em useful for languages like Chinese\&. +.RE +.PP +lang\&.cube\-unicharset +.RS 4 +(Optional) A unicharset for cube, if cube was trained on a different set of symbols\&. +.RE +.PP +lang\&.cube\-word\-dawg +.RS 4 +(Optional) A word dawg for cube\(cqs alternate unicharset\&. Not needed if Cube was trained with Tesseract\(cqs unicharset\&. +.RE +.PP +lang\&.shapetable +.RS 4 +(Optional) When present, a shapetable is an extra layer between the character classifier and the word recognizer that allows the character classifier to return a collection of unichar ids and fonts instead of a single unichar\-id and font\&. +.RE +.PP +lang\&.bigram\-dawg +.RS 4 +(Optional) A dawg of word bigrams where the words are separated by a space and each digit is replaced by a +\fI?\fR\&. +.RE +.PP +lang\&.unambig\-dawg +.RS 4 +(Optional) TODO: Describe\&. +.RE +.PP +lang\&.params\-training\-model +.RS 4 +(Optional) TODO: Describe\&. +.RE +.SH "HISTORY" +.sp +combine_tessdata(1) first appeared in version 3\&.00 of Tesseract +.SH "SEE ALSO" +.sp +tesseract(1), wordlist2dawg(1), cntraining(1), mftraining(1), unicharset(5), unicharambigs(5) +.SH "COPYING" +.sp +Copyright (C) 2009, Google Inc\&. Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/dawg2wordlist.1 b/Tesseract/share/man/man1/dawg2wordlist.1 new file mode 100644 index 0000000..2d73da3 --- /dev/null +++ b/Tesseract/share/man/man1/dawg2wordlist.1 @@ -0,0 +1,55 @@ +'\" t +.\" Title: dawg2wordlist +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "DAWG2WORDLIST" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +dawg2wordlist \- convert a Tesseract DAWG to a wordlist +.SH "SYNOPSIS" +.sp +\fBdawg2wordlist\fR \fIUNICHARSET\fR \fIDAWG\fR \fIWORDLIST\fR +.SH "DESCRIPTION" +.sp +dawg2wordlist(1) converts a Tesseract Directed Acyclic Word Graph (DAWG) to a list of words using a unicharset as key\&. +.SH "OPTIONS" +.sp +\fIUNICHARSET\fR The unicharset of the language\&. This is the unicharset generated by mftraining(1)\&. +.sp +\fIDAWG\fR The input DAWG, created by wordlist2dawg(1) +.sp +\fIWORDLIST\fR Plain text (output) file in UTF\-8, one word per line +.SH "SEE ALSO" +.sp +tesseract(1), mftraining(1), wordlist2dawg(1), unicharset(5), combine_tessdata(1) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "COPYING" +.sp +Copyright (C) 2012 Google, Inc\&. Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/mftraining.1 b/Tesseract/share/man/man1/mftraining.1 new file mode 100644 index 0000000..441e03b --- /dev/null +++ b/Tesseract/share/man/man1/mftraining.1 @@ -0,0 +1,94 @@ +'\" t +.\" Title: mftraining +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "MFTRAINING" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +mftraining \- feature training for Tesseract +.SH "SYNOPSIS" +.sp +mftraining \-U \fIunicharset\fR \-O \fIlang\&.unicharset\fR \fIFILE\fR\&... +.SH "DESCRIPTION" +.sp +mftraining takes a list of \&.tr files, from which it generates the files \fBinttemp\fR (the shape prototypes), \fBshapetable\fR, and \fBpffmtable\fR (the number of expected features for each character)\&. (A fourth file called Microfeat is also written by this program, but it is not used\&.) +.SH "OPTIONS" +.PP +\-U \fIFILE\fR +.RS 4 +(Input) The unicharset generated by unicharset_extractor(1) +.RE +.PP +\-F \fIfont_properties_file\fR +.RS 4 +(Input) font properties file, each line is of the following form, where each field other than the font name is 0 or 1: +.sp +.if n \{\ +.RS 4 +.\} +.nf +*font_name* *italic* *bold* *fixed_pitch* *serif* *fraktur* +.fi +.if n \{\ +.RE +.\} +.RE +.PP +\-X \fIxheights_file\fR +.RS 4 +(Input) x heights file, each line is of the following form, where xheight is calculated as the pixel x height of a character drawn at 32pt on 300 dpi\&. [ That is, if base x height + ascenders + descenders = 133, how much is x height? ] +.sp +.if n \{\ +.RS 4 +.\} +.nf +*font_name* *xheight* +.fi +.if n \{\ +.RE +.\} +.RE +.PP +\-D \fIdir\fR +.RS 4 +Directory to write output files to\&. +.RE +.PP +\-O \fIFILE\fR +.RS 4 +(Output) The output unicharset that will be given to combine_tessdata(1) +.RE +.SH "SEE ALSO" +.sp +tesseract(1), cntraining(1), unicharset_extractor(1), combine_tessdata(1), shapeclustering(1), unicharset(5) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "COPYING" +.sp +Copyright (C) Hewlett\-Packard Company, 1988 Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/shapeclustering.1 b/Tesseract/share/man/man1/shapeclustering.1 new file mode 100644 index 0000000..d59783f --- /dev/null +++ b/Tesseract/share/man/man1/shapeclustering.1 @@ -0,0 +1,94 @@ +'\" t +.\" Title: shapeclustering +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "SHAPECLUSTERING" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +shapeclustering \- shape clustering training for Tesseract +.SH "SYNOPSIS" +.sp +shapeclustering \-D \fIoutput_dir\fR \-U \fIunicharset\fR \-O \fImfunicharset\fR \-F \fIfont_props\fR \-X \fIxheights\fR \fIFILE\fR\&... +.SH "DESCRIPTION" +.sp +shapeclustering(1) takes extracted feature \&.tr files (generated by tesseract(1) run in a special mode from box files) and produces a file \fBshapetable\fR and an enhanced unicharset\&. This program is still experimental, and is not required (yet) for training Tesseract\&. +.SH "OPTIONS" +.PP +\-U \fIFILE\fR +.RS 4 +The unicharset generated by unicharset_extractor(1)\&. +.RE +.PP +\-D \fIdir\fR +.RS 4 +Directory to write output files to\&. +.RE +.PP +\-F \fIfont_properties_file\fR +.RS 4 +(Input) font properties file, where each line is of the following form, where each field other than the font name is 0 or 1: +.sp +.if n \{\ +.RS 4 +.\} +.nf +\*(Aqfont_name\*(Aq \*(Aqitalic\*(Aq \*(Aqbold\*(Aq \*(Aqfixed_pitch\*(Aq \*(Aqserif\*(Aq \*(Aqfraktur\*(Aq +.fi +.if n \{\ +.RE +.\} +.RE +.PP +\-X \fIxheights_file\fR +.RS 4 +(Input) x heights file, each line is of the following form, where xheight is calculated as the pixel x height of a character drawn at 32pt on 300 dpi\&. [ That is, if base x height + ascenders + descenders = 133, how much is x height? ] +.sp +.if n \{\ +.RS 4 +.\} +.nf +\*(Aqfont_name\*(Aq \*(Aqxheight\*(Aq +.fi +.if n \{\ +.RE +.\} +.RE +.PP +\-O \fIFILE\fR +.RS 4 +The output unicharset that will be given to combine_tessdata(1)\&. +.RE +.SH "SEE ALSO" +.sp +tesseract(1), cntraining(1), unicharset_extractor(1), combine_tessdata(1), unicharset(5) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "COPYING" +.sp +Copyright (C) Google, 2011 Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/tesseract.1 b/Tesseract/share/man/man1/tesseract.1 new file mode 100644 index 0000000..8189016 --- /dev/null +++ b/Tesseract/share/man/man1/tesseract.1 @@ -0,0 +1,194 @@ +'\" t +.\" Title: tesseract +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 04/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "TESSERACT" "1" "04/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +tesseract \- command\-line OCR engine +.SH "SYNOPSIS" +.sp +\fBtesseract\fR \fIimagename\fR \fIoutbase\fR [\fI\-l lang\fR] [\fI\-psm N\fR] [\fIconfigfile\fR \&...] +.SH "DESCRIPTION" +.sp +tesseract(1) is a commercial quality OCR engine originally developed at HP between 1985 and 1995\&. In 1995, this engine was among the top 3 evaluated by UNLV\&. It was open\-sourced by HP and UNLV in 2005, and has been developed at Google since then\&. +.SH "OPTIONS" +.PP +\fIimagename\fR +.RS 4 +The name of the input image\&. Most image file formats (anything readable by Leptonica) are supported\&. +.RE +.PP +\fIoutbase\fR +.RS 4 +The basename of the output file (to which the appropriate extension will be appended)\&. By default the output will be named +\fIoutbase\&.txt\fR\&. +.RE +.PP +\fI\-l lang\fR +.RS 4 +The language to use\&. If none is specified, English is assumed\&. Multiple languages may be specified, separated by plus characters\&. Tesseract uses 3\-character ISO 639\-2 language codes\&. (See LANGUAGES) +.RE +.PP +\fI\-psm N\fR +.RS 4 +Set Tesseract to only run a subset of layout analysis and assume a certain form of image\&. The options for +\fBN\fR +are: +.sp +.if n \{\ +.RS 4 +.\} +.nf +0 = Orientation and script detection (OSD) only\&. +1 = Automatic page segmentation with OSD\&. +2 = Automatic page segmentation, but no OSD, or OCR\&. +3 = Fully automatic page segmentation, but no OSD\&. (Default) +4 = Assume a single column of text of variable sizes\&. +5 = Assume a single uniform block of vertically aligned text\&. +6 = Assume a single uniform block of text\&. +7 = Treat the image as a single text line\&. +8 = Treat the image as a single word\&. +9 = Treat the image as a single word in a circle\&. +10 = Treat the image as a single character\&. +.fi +.if n \{\ +.RE +.\} +.RE +.PP +\fI\-v\fR +.RS 4 +Returns the current version of the tesseract(1) executable\&. +.RE +.PP +\fIconfigfile\fR +.RS 4 +The name of a config to use\&. A config is a plaintext file which contains a list of variables and their values, one per line, with a space separating variable from value\&. Interesting config files include: + +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +hocr \- Output in hOCR format instead of as a text file\&. +.RE +.RE +.sp +\fBNota Bene:\fR The options \fI\-l lang\fR and \fI\-psm N\fR must occur before any \fIconfigfile\fR\&. +.SH "LANGUAGES" +.sp +There are currently language packs available for the following languages: +.sp +\fBara\fR (Arabic), \fBaze\fR (Azerbauijani), \fBbul\fR (Bulgarian), \fBcat\fR (Catalan), \fBces\fR (Czech), \fBchi_sim\fR (Simplified Chinese), \fBchi_tra\fR (Traditional Chinese), \fBchr\fR (Cherokee), \fBdan\fR (Danish), \fBdan\-frak\fR (Danish (Fraktur)), \fBdeu\fR (German), \fBell\fR (Greek), \fBeng\fR (English), \fBenm\fR (Old English), \fBepo\fR (Esperanto), \fBest\fR (Estonian), \fBfin\fR (Finnish), \fBfra\fR (French), \fBfrm\fR (Old French), \fBglg\fR (Galician), \fBheb\fR (Hebrew), \fBhin\fR (Hindi), \fBhrv\fR (Croation), \fBhun\fR (Hungarian), \fBind\fR (Indonesian), \fBita\fR (Italian), \fBjpn\fR (Japanese), \fBkor\fR (Korean), \fBlav\fR (Latvian), \fBlit\fR (Lithuanian), \fBnld\fR (Dutch), \fBnor\fR (Norwegian), \fBpol\fR (Polish), \fBpor\fR (Portuguese), \fBron\fR (Romanian), \fBrus\fR (Russian), \fBslk\fR (Slovakian), \fBslv\fR (Slovenian), \fBsqi\fR (Albanian), \fBspa\fR (Spanish), \fBsrp\fR (Serbian), \fBswe\fR (Swedish), \fBtam\fR (Tamil), \fBtel\fR (Telugu), \fBtgl\fR (Tagalog), \fBtha\fR (Thai), \fBtur\fR (Turkish), \fBukr\fR (Ukrainian), \fBvie\fR (Vietnamese) +.sp +To use a non\-standard language pack named \fBfoo\&.traineddata\fR, set the \fBTESSDATA_PREFIX\fR environment variable so the file can be found at \fBTESSDATA_PREFIX\fR/tessdata/\fBfoo\fR\&.traineddata and give Tesseract the argument \fI\-l foo\fR\&. +.SH "CONFIG FILES AND AUGMENTING WITH USER DATA" +.sp +Tesseract config files consist of lines with variable\-value pairs (space separated)\&. The variables are documented as flags in the source code like the following one in tesseractclass\&.h: +.sp +STRING_VAR_H(tessedit_char_blacklist, "", "Blacklist of chars not to recognize"); +.sp +These variables may enable or disable various features of the engine, and may cause it to load (or not load) various data\&. For instance, let\(cqs suppose you want to OCR in English, but suppress the normal dictionary and load an alternative word list and an alternative list of patterns \(em these two files are the most commonly used extra data files\&. +.sp +If your language pack is in /path/to/eng\&.traineddata and the hocr config is in /path/to/configs/hocr then create three new files: +.sp +/path/to/eng\&.user\-words: +.sp +.if n \{\ +.RS 4 +.\} +.nf +the +quick +brown +fox +jumped +.fi +.if n \{\ +.RE +.\} +.sp +/path/to/eng\&.user\-patterns: +.sp +.if n \{\ +.RS 4 +.\} +.nf +1\-\ed\ed\ed\-GOOG\-411 +www\&.\en\e\e\e*\&.com +.fi +.if n \{\ +.RE +.\} +.sp +/path/to/configs/bazaar: +.sp +.if n \{\ +.RS 4 +.\} +.nf +load_system_dawg F +load_freq_dawg F +user_words_suffix user\-words +user_patterns_suffix user\-patterns +.fi +.if n \{\ +.RE +.\} +.sp +Now, if you pass the word \fIbazaar\fR as a trailing command line parameter to Tesseract, Tesseract will not bother loading the system dictionary nor the dictionary of frequent words and will load and use the eng\&.user\-words and eng\&.user\-patterns files you provided\&. The former is a simple word list, one per line\&. The format of the latter is documented in dict/trie\&.h on read_pattern_list()\&. +.SH "HISTORY" +.sp +The engine was developed at Hewlett Packard Laboratories Bristol and at Hewlett Packard Co, Greeley Colorado between 1985 and 1994, with some more changes made in 1996 to port to Windows, and some C++izing in 1998\&. A lot of the code was written in C, and then some more was written in C++\&. The C\e++ code makes heavy use of a list system using macros\&. This predates stl, was portable before stl, and is more efficient than stl lists, but has the big negative that if you do get a segmentation violation, it is hard to debug\&. +.sp +Version 2\&.00 brought Unicode (UTF\-8) support, six languages, and the ability to train Tesseract\&. +.sp +Tesseract was included in UNLV\(cqs Fourth Annual Test of OCR Accuracy\&. See \m[blue]\fBhttp://www\&.isri\&.unlv\&.edu/downloads/AT\-1995\&.pdf\fR\m[]\&. With Tesseract 2\&.00, scripts are now included to allow anyone to reproduce some of these tests\&. See \m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TestingTesseract\fR\m[] for more details\&. +.sp +Tesseract 3\&.00 adds a number of new languages, including Chinese, Japanese, and Korean\&. It also introduces a new, single\-file based system of managing language data\&. +.sp +Tesseract 3\&.02 adds BiDirectional text support, the ability to recognize multiple languages in a single image, and improved layout analysis\&. +.sp +For further details, see the file ReleaseNotes included with the distribution\&. +.SH "RESOURCES" +.sp +Main web site: \m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/\fR\m[] Information on training: \m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "SEE ALSO" +.sp +ambiguous_words(1), cntraining(1), combine_tessdata(1), dawg2wordlist(1), shape_training(1), mftraining(1), unicharambigs(5), unicharset(5), unicharset_extractor(1), wordlist2dawg(1) +.SH "AUTHOR" +.sp +Tesseract development was led at Hewlett\-Packard and Google by Ray Smith\&. The development team has included: +.sp +Ahmad Abdulkader, Chris Newton, Dan Johnson, Dar\-Shyang Lee, David Eger, Eric Wiseblatt, Faisal Shafait, Hiroshi Takenaka, Joe Liu, Joern Wanke, Mark Seaman, Mickey Namiki, Nicholas Beato, Oded Fuhrmann, Phil Cheatle, Pingping Xiu, Pong Eksombatchai (Chantat), Ranjith Unnikrishnan, Raquel Romano, Ray Smith, Rika Antonova, Robert Moss, Samuel Charron, Sheelagh Lloyd, Shobhit Saxena, and Thomas Kielbus\&. +.SH "COPYING" +.sp +Licensed under the Apache License, Version 2\&.0 diff --git a/Tesseract/share/man/man1/unicharset_extractor.1 b/Tesseract/share/man/man1/unicharset_extractor.1 new file mode 100644 index 0000000..c3bdf2f --- /dev/null +++ b/Tesseract/share/man/man1/unicharset_extractor.1 @@ -0,0 +1,69 @@ +'\" t +.\" Title: unicharset_extractor +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "UNICHARSET_EXTRACTOR" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +unicharset_extractor \- extract unicharset from Tesseract boxfiles +.SH "SYNOPSIS" +.sp +\fBunicharset_extractor\fR \fI[\-D dir]\fR \fIFILE\fR\&... +.SH "DESCRIPTION" +.sp +Tesseract needs to know the set of possible characters it can output\&. To generate the unicharset data file, use the unicharset_extractor program on the same training pages bounding box files as used for clustering: +.sp +.if n \{\ +.RS 4 +.\} +.nf +unicharset_extractor fontfile_1\&.box fontfile_2\&.box \&.\&.\&. +.fi +.if n \{\ +.RE +.\} +.sp +The unicharset will be put into the file \fIdir/unicharset\fR, or simply \fI\&./unicharset\fR if no output directory is provided\&. +.sp +Tesseract also needs to have access to character properties isalpha, isdigit, isupper, islower, ispunctuation\&. all of this auxilury data and more is encoded in this file\&. (See unicharset(5)) +.sp +If your system supports the wctype functions, these values will be set automatically by unicharset_extractor and there is no need to edit the unicharset file\&. On some older systems (eg Windows 95), the unicharset file must be edited by hand to add these property description codes\&. +.sp +\fBNOTE\fR The unicharset file must be regenerated whenever inttemp, normproto and pffmtable are generated (i\&.e\&. they must all be recreated when the box file is changed) as they have to be in sync\&. This is made easier than in previous versions by running unicharset_extractor before mftraining and cntraining, and giving the unicharset to mftraining\&. +.SH "SEE ALSO" +.sp +tesseract(1), unicharset(5) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "HISTORY" +.sp +unicharset_extractor first appeared in Tesseract 2\&.00\&. +.SH "COPYING" +.sp +Copyright (C) 2006, Google Inc\&. Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man1/wordlist2dawg.1 b/Tesseract/share/man/man1/wordlist2dawg.1 new file mode 100644 index 0000000..930a782 --- /dev/null +++ b/Tesseract/share/man/man1/wordlist2dawg.1 @@ -0,0 +1,72 @@ +'\" t +.\" Title: wordlist2dawg +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "WORDLIST2DAWG" "1" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +wordlist2dawg \- convert a wordlist to a DAWG for Tesseract +.SH "SYNOPSIS" +.sp +\fBwordlist2dawg\fR \fIWORDLIST\fR \fIDAWG\fR \fIlang\&.unicharset\fR +.sp +\fBwordlist2dawg\fR \-t \fIWORDLIST\fR \fIDAWG\fR \fIlang\&.unicharset\fR +.sp +\fBwordlist2dawg\fR \-r 1 \fIWORDLIST\fR \fIDAWG\fR \fIlang\&.unicharset\fR +.sp +\fBwordlist2dawg\fR \-r 2 \fIWORDLIST\fR \fIDAWG\fR \fIlang\&.unicharset\fR +.sp +\fBwordlist2dawg\fR \-l \fIWORDLIST\fR \fIDAWG\fR \fIlang\&.unicharset\fR +.SH "DESCRIPTION" +.sp +wordlist2dawg(1) converts a wordlist to a Directed Acyclic Word Graph (DAWG) for use with Tesseract\&. A DAWG is a compressed, space and time efficient representation of a word list\&. +.SH "OPTIONS" +.sp +\-t Verify that a given dawg file is equivalent to a given wordlist\&. +.sp +\-r 1 Reverse a word if it contains an RTL character\&. +.sp +\-r 2 Reverse all words\&. +.sp +\-l Produce a file with several dawgs in it, one each for words of length , ,\&... +.SH "ARGUMENTS" +.sp +\fIWORDLIST\fR A plain text file in UTF\-8, one word per line\&. +.sp +\fIDAWG\fR The output DAWG to write\&. +.sp +\fIlang\&.unicharset\fR The unicharset of the language\&. This is the unicharset generated by mftraining(1)\&. +.SH "SEE ALSO" +.sp +tesseract(1), combine_tessdata(1), dawg2wordlist(1) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "COPYING" +.sp +Copyright (C) 2006 Google, Inc\&. Licensed under the Apache License, Version 2\&.0 +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man5/unicharambigs.5 b/Tesseract/share/man/man5/unicharambigs.5 new file mode 100644 index 0000000..4e756e0 --- /dev/null +++ b/Tesseract/share/man/man5/unicharambigs.5 @@ -0,0 +1,120 @@ +'\" t +.\" Title: unicharambigs +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "UNICHARAMBIGS" "5" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +unicharambigs \- Tesseract unicharset ambiguities +.SH "DESCRIPTION" +.sp +The unicharambigs file (a component of traineddata, see combine_tessdata(1) ) is used by Tesseract to represent possible ambiguities between characters, or groups of characters\&. +.sp +The file contains a number of lines, laid out as follow: +.sp +.if n \{\ +.RS 4 +.\} +.nf +[num] [char(s)] [num] [char(s)] [num] +.fi +.if n \{\ +.RE +.\} +.sp +.TS +tab(:); +lt lt +lt lt +lt lt +lt lt +lt lt. +T{ +.sp +Field one +T}:T{ +.sp +the number of characters contained in field two +T} +T{ +.sp +Field two +T}:T{ +.sp +the character sequence to be replaced +T} +T{ +.sp +Field three +T}:T{ +.sp +the number of characters contained in field four +T} +T{ +.sp +Field four +T}:T{ +.sp +the character sequence used to replace field two +T} +T{ +.sp +Field five +T}:T{ +.sp +contains either 1 or 0\&. 1 denotes a mandatory replacement, 0 denotes an optional replacement\&. +T} +.TE +.sp 1 +.sp +Characters appearing in fields two and four should appear in unicharset\&. The numbers in fields one and three refer to the number of unichars (not bytes)\&. +.SH "EXAMPLE" +.sp +.if n \{\ +.RS 4 +.\} +.nf +2 \*(Aq \*(Aq 1 " 1 +1 m 2 r n 0 +3 i i i 1 m 0 +.fi +.if n \{\ +.RE +.\} +.sp +In this example, all instances of the \fI2\fR character sequence \fI\*(Aq\fR\*(Aq will \fBalways\fR be replaced by the \fI1\fR character sequence \fI"\fR; a \fI1\fR character sequence \fIm\fR \fBmay\fR be replaced by the \fI2\fR character sequence \fIrn\fR, and the \fI3\fR character sequence \fBmay\fR be replaced by the \fI1\fR character sequence \fIm\fR\&. +.SH "HISTORY" +.sp +The unicharambigs file first appeared in Tesseract 3\&.00; prior to that, a similar format, called DangAmbigs (\fIdangerous ambiguities\fR) was used: the format was almost identical, except only mandatory replacements could be specified, and field 5 was absent\&. +.SH "BUGS" +.sp +This is a documentation "bug": it\(cqs not currently clear what should be done in the case of ligatures (such as \fIfi\fR) which may also appear as regular letters in the unicharset\&. +.SH "SEE ALSO" +.sp +tesseract(1), unicharset(5) +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/man/man5/unicharset.5 b/Tesseract/share/man/man5/unicharset.5 new file mode 100644 index 0000000..fd9cccd --- /dev/null +++ b/Tesseract/share/man/man5/unicharset.5 @@ -0,0 +1,220 @@ +'\" t +.\" Title: unicharset +.\" Author: [see the "AUTHOR" section] +.\" Generator: DocBook XSL Stylesheets v1.75.2 +.\" Date: 02/09/2012 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "UNICHARSET" "5" "02/09/2012" "\ \&" "\ \&" +.\" ----------------------------------------------------------------- +.\" * Define some portability stuff +.\" ----------------------------------------------------------------- +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.\" http://bugs.debian.org/507673 +.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html +.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.\" ----------------------------------------------------------------- +.\" * set default formatting +.\" ----------------------------------------------------------------- +.\" disable hyphenation +.nh +.\" disable justification (adjust text to left margin only) +.ad l +.\" ----------------------------------------------------------------- +.\" * MAIN CONTENT STARTS HERE * +.\" ----------------------------------------------------------------- +.SH "NAME" +unicharset \- character properties file used by tesseract(1) +.SH "DESCRIPTION" +.sp +Tesseract\(cqs unicharset file contains information on each symbol (unichar) the Tesseract OCR engine is trained to recognize\&. +.sp +A unicharset file (i\&.e\&. \fIeng\&.unicharset\fR) is distributed as part of a Tesseract language pack (i\&.e\&. \fIeng\&.traineddata\fR)\&. For information on extracting the unicharset file, see combine_tessdata(1)\&. +.sp +The first line of a unicharset file contains the number of unichars in the file\&. After this line, each subsequent line provides information for a single unichar\&. The first such line contains a placeholder reserved for the space character\&. Each unichar is referred to within Tesseract by its Unichar ID, which is the line number (minus 1) within the unicharset file\&. Therefore, space gets unichar 0\&. +.sp +Each unichar line in the unicharset file (v2+) may have four space\-separated fields: +.sp +.if n \{\ +.RS 4 +.\} +.nf +\*(Aqcharacter\*(Aq \*(Aqproperties\*(Aq \*(Aqscript\*(Aq \*(Aqid\*(Aq +.fi +.if n \{\ +.RE +.\} +.sp +Starting with Tesseract v3\&.02, more information may be given for each unichar: +.sp +.if n \{\ +.RS 4 +.\} +.nf +\*(Aqcharacter\*(Aq \*(Aqproperties\*(Aq \*(Aqglyph_metrics\*(Aq \*(Aqscript\*(Aq \*(Aqother_case\*(Aq \*(Aqdirection\*(Aq \*(Aqmirror\*(Aq \*(Aqnormed_form\*(Aq +.fi +.if n \{\ +.RE +.\} +.sp +Entries: +.PP +\fIcharacter\fR +.RS 4 +The UTF\-8 encoded string to be produced for this unichar\&. +.RE +.PP +\fIproperties\fR +.RS 4 +An integer mask of character properties, one per bit\&. From least to most significant bit, these are: isalpha, islower, isupper, isdigit, ispunctuation\&. +.RE +.PP +\fIglyph_metrics\fR +.RS 4 +Ten comma\-separated integers representing various standards for where this glyph is to be found within a baseline\-normalized coordinate system where 128 is normalized to x\-height\&. +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +min_bottom, max_bottom: the ranges where the bottom of the character can be found\&. +.RE +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +min_top, max_top: the ranges where the top of the character may be found\&. +.RE +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +min_width, max_width: horizontal width of the character\&. +.RE +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +min_bearing, max_bearing: how far from the usual start position does the leftmost part of the character begin\&. +.RE +.sp +.RS 4 +.ie n \{\ +\h'-04'\(bu\h'+03'\c +.\} +.el \{\ +.sp -1 +.IP \(bu 2.3 +.\} +min_advance, max_advance: how far from the printer\(cqs cell left do we advance to begin the next character\&. +.RE +.RE +.PP +\fIscript\fR +.RS 4 +Name of the script (Latin, Common, Greek, Cyrillic, Han, null)\&. +.RE +.PP +\fIother_case\fR +.RS 4 +The Unichar ID of the other case version of this character (upper or lower)\&. +.RE +.PP +\fIdirection\fR +.RS 4 +The Unicode BiDi direction of this character, as defined by ICU\(cqs enum UCharDirection\&. (0 = Left to Right, 1 = Right to Left, 2 = European Number\&...) +.RE +.PP +\fImirror\fR +.RS 4 +The Unichar ID of the BiDirectional mirror of this character\&. For example the mirror of open paren is close paren, but Latin Capital C has no mirror, so it remains a Latin Capital C\&. +.RE +.PP +\fInormed_form\fR +.RS 4 +The UTF\-8 representation of a "normalized form" of this unichar for the purpose of blaming a module for errors given ground truth text\&. For instance, a left or right single quote may normalize to an ASCII quote\&. +.RE +.SH "EXAMPLE (V2)" +.sp +.if n \{\ +.RS 4 +.\} +.nf +; 10 Common 46 +b 3 Latin 59 +W 5 Latin 40 +7 8 Common 66 += 0 Common 93 +.fi +.if n \{\ +.RE +.\} +.sp +";" is a punctuation character\&. Its properties are thus represented by the binary number 10000 (10 in hexadecimal)\&. +.sp +"b" is an alphabetic character and a lower case character\&. Its properties are thus represented by the binary number 00011 (3 in hexadecimal)\&. +.sp +"W" is an alphabetic character and an upper case character\&. Its properties are thus represented by the binary number 00101 (5 in hexadecimal)\&. +.sp +"7" is just a digit\&. Its properties are thus represented by the binary number 01000 (8 in hexadecimal)\&. +.sp +"=" is not punctuation nor a digit nor an alphabetic character\&. Its properties are thus represented by the binary number 00000 (0 in hexadecimal)\&. +.sp +Japanese or Chinese alphabetic character properties are represented by the binary number 00001 (1 in hexadecimal): they are alphabetic, but neither upper nor lower case\&. +.SH "EXAMPLE (V3.02)" +.sp +.if n \{\ +.RS 4 +.\} +.nf +110 +NULL 0 NULL 0 +N 5 59,68,216,255,87,236,0,27,104,227 Latin 11 0 1 N +Y 5 59,68,216,255,91,205,0,47,91,223 Latin 33 0 2 Y +1 8 59,69,203,255,45,128,0,66,74,173 Common 3 2 3 1 +9 8 18,66,203,255,89,156,0,39,104,173 Common 4 2 4 9 +a 3 58,65,186,198,85,164,0,26,97,185 Latin 56 0 5 a +\&. \&. \&. +.fi +.if n \{\ +.RE +.\} +.SH "CAVEATS" +.sp +Although the unicharset reader maintains the ability to read unicharsets of older formats and will assign default values to missing fields, the accuracy will be degraded\&. +.sp +Further, most other data files are indexed by the unicharset file, so changing it without re\-generating the others is likely to have dire consequences\&. +.SH "HISTORY" +.sp +The unicharset format first appeared with Tesseract 2\&.00, which was the first version to support languages other than English\&. The unicharset file contained only the first two fields, and the "ispunctuation" property was absent (punctuation was regarded as "0", as "=" is in the above example\&. +.SH "SEE ALSO" +.sp +tesseract(1), combine_tessdata(1), unicharset_extractor(1) +.sp +\m[blue]\fBhttp://code\&.google\&.com/p/tesseract\-ocr/wiki/TrainingTesseract3\fR\m[] +.SH "AUTHOR" +.sp +The Tesseract OCR engine was written by Ray Smith and his research groups at Hewlett Packard (1985\-1995) and Google (2006\-present)\&. diff --git a/Tesseract/share/tessdata/configs/ambigs.train b/Tesseract/share/tessdata/configs/ambigs.train new file mode 100644 index 0000000..23035a1 --- /dev/null +++ b/Tesseract/share/tessdata/configs/ambigs.train @@ -0,0 +1,7 @@ +tessedit_ambigs_training 1 +load_freq_dawg 0 +load_punc_dawg 0 +load_system_dawg 0 +load_number_dawg 0 +ambigs_debug_level 3 +load_fixed_length_dawgs 0 diff --git a/Tesseract/share/tessdata/configs/api_config b/Tesseract/share/tessdata/configs/api_config new file mode 100644 index 0000000..5cd6ec0 --- /dev/null +++ b/Tesseract/share/tessdata/configs/api_config @@ -0,0 +1 @@ +tessedit_zero_rejection T diff --git a/Tesseract/share/tessdata/configs/box.train b/Tesseract/share/tessdata/configs/box.train new file mode 100644 index 0000000..03cf563 --- /dev/null +++ b/Tesseract/share/tessdata/configs/box.train @@ -0,0 +1,14 @@ +disable_character_fragments T +file_type .bl +textord_fast_pitch_test T +tessedit_single_match 0 +tessedit_zero_rejection T +tessedit_minimal_rejection F +tessedit_write_rep_codes F +il1_adaption_test 1 +edges_children_fix F +edges_childarea 0.65 +edges_boxarea 0.9 +tessedit_resegment_from_boxes T +tessedit_train_from_boxes T +textord_no_rejects T diff --git a/Tesseract/share/tessdata/configs/box.train.stderr b/Tesseract/share/tessdata/configs/box.train.stderr new file mode 100644 index 0000000..6fc51fd --- /dev/null +++ b/Tesseract/share/tessdata/configs/box.train.stderr @@ -0,0 +1,15 @@ +file_type .bl +#tessedit_use_nn F +textord_fast_pitch_test T +tessedit_single_match 0 +tessedit_zero_rejection T +tessedit_minimal_rejection F +tessedit_write_rep_codes F +il1_adaption_test 1 +edges_children_fix F +edges_childarea 0.65 +edges_boxarea 0.9 +tessedit_resegment_from_boxes T +tessedit_train_from_boxes T +#textord_repeat_extraction F +textord_no_rejects T diff --git a/Tesseract/share/tessdata/configs/digits b/Tesseract/share/tessdata/configs/digits new file mode 100644 index 0000000..6a329f8 --- /dev/null +++ b/Tesseract/share/tessdata/configs/digits @@ -0,0 +1 @@ +tessedit_char_whitelist 0123456789-. diff --git a/Tesseract/share/tessdata/configs/hocr b/Tesseract/share/tessdata/configs/hocr new file mode 100644 index 0000000..72f83e8 --- /dev/null +++ b/Tesseract/share/tessdata/configs/hocr @@ -0,0 +1 @@ +tessedit_create_hocr 1 \ No newline at end of file diff --git a/Tesseract/share/tessdata/configs/inter b/Tesseract/share/tessdata/configs/inter new file mode 100644 index 0000000..252f1a1 --- /dev/null +++ b/Tesseract/share/tessdata/configs/inter @@ -0,0 +1,2 @@ +interactive_display_mode T +tessedit_display_outwords T diff --git a/Tesseract/share/tessdata/configs/kannada b/Tesseract/share/tessdata/configs/kannada new file mode 100644 index 0000000..c6ac105 --- /dev/null +++ b/Tesseract/share/tessdata/configs/kannada @@ -0,0 +1,4 @@ +textord_skewsmooth_offset 8 +textord_skewsmooth_offset2 8 +textord_merge_desc 0.5 +textord_no_rejects 1 diff --git a/Tesseract/share/tessdata/configs/linebox b/Tesseract/share/tessdata/configs/linebox new file mode 100644 index 0000000..bd9c114 --- /dev/null +++ b/Tesseract/share/tessdata/configs/linebox @@ -0,0 +1,2 @@ +tessedit_resegment_from_line_boxes 1 +tessedit_make_boxes_from_boxes 1 diff --git a/Tesseract/share/tessdata/configs/logfile b/Tesseract/share/tessdata/configs/logfile new file mode 100644 index 0000000..a160f9b --- /dev/null +++ b/Tesseract/share/tessdata/configs/logfile @@ -0,0 +1 @@ +debug_file tesseract.log diff --git a/Tesseract/share/tessdata/configs/makebox b/Tesseract/share/tessdata/configs/makebox new file mode 100644 index 0000000..3d90ac2 --- /dev/null +++ b/Tesseract/share/tessdata/configs/makebox @@ -0,0 +1 @@ +tessedit_create_boxfile 1 diff --git a/Tesseract/share/tessdata/configs/quiet b/Tesseract/share/tessdata/configs/quiet new file mode 100644 index 0000000..35b59a9 --- /dev/null +++ b/Tesseract/share/tessdata/configs/quiet @@ -0,0 +1 @@ +debug_file /dev/null diff --git a/Tesseract/share/tessdata/configs/rebox b/Tesseract/share/tessdata/configs/rebox new file mode 100644 index 0000000..f8342b4 --- /dev/null +++ b/Tesseract/share/tessdata/configs/rebox @@ -0,0 +1,2 @@ +tessedit_resegment_from_boxes 1 +tessedit_make_boxes_from_boxes 1 diff --git a/Tesseract/share/tessdata/configs/strokewidth b/Tesseract/share/tessdata/configs/strokewidth new file mode 100644 index 0000000..e95b592 --- /dev/null +++ b/Tesseract/share/tessdata/configs/strokewidth @@ -0,0 +1,12 @@ +textord_show_blobs 0 +textord_debug_tabfind 3 +textord_tabfind_show_partitions 1 +textord_tabfind_show_initial_partitions 1 +textord_tabfind_show_columns 1 +textord_tabfind_show_blocks 1 +textord_tabfind_show_initialtabs 1 +textord_tabfind_show_finaltabs 1 +textord_tabfind_show_strokewidths 1 +textord_tabfind_show_vlines 0 +textord_tabfind_show_images 1 +tessedit_dump_pageseg_images 0 diff --git a/Tesseract/share/tessdata/configs/unlv b/Tesseract/share/tessdata/configs/unlv new file mode 100644 index 0000000..87c111b --- /dev/null +++ b/Tesseract/share/tessdata/configs/unlv @@ -0,0 +1,2 @@ +tessedit_write_unlv 1 +tessedit_pageseg_mode 6 diff --git a/Tesseract/share/tessdata/eng.traineddata b/Tesseract/share/tessdata/eng.traineddata new file mode 100644 index 0000000..64ae74e Binary files /dev/null and b/Tesseract/share/tessdata/eng.traineddata differ diff --git a/Tesseract/share/tessdata/tessconfigs/batch b/Tesseract/share/tessdata/tessconfigs/batch new file mode 100644 index 0000000..619b646 --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/batch @@ -0,0 +1,2 @@ +# No content needed as all defaults are correct. + diff --git a/Tesseract/share/tessdata/tessconfigs/batch.nochop b/Tesseract/share/tessdata/tessconfigs/batch.nochop new file mode 100644 index 0000000..ebaab94 --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/batch.nochop @@ -0,0 +1,2 @@ +chop_enable 0 +wordrec_enable_assoc 0 diff --git a/Tesseract/share/tessdata/tessconfigs/matdemo b/Tesseract/share/tessdata/tessconfigs/matdemo new file mode 100644 index 0000000..c34567b --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/matdemo @@ -0,0 +1,7 @@ +################################################# +# Adaptive Matcher Using PreAdapted Templates +################################################# + +classify_enable_adaptive_debugger 1 +matcher_debug_flags 6 +matcher_debug_level 1 diff --git a/Tesseract/share/tessdata/tessconfigs/msdemo b/Tesseract/share/tessdata/tessconfigs/msdemo new file mode 100644 index 0000000..a1af21f --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/msdemo @@ -0,0 +1,13 @@ +################################################# +# Adaptive Matcher Using PreAdapted Templates +################################################# + +classify_enable_adaptive_debugger 1 +matcher_debug_flags 6 +matcher_debug_level 1 + +wordrec_display_splits 0 +wordrec_display_all_words 1 +wordrec_display_all_blobs 1 +wordrec_display_segmentations 2 +classify_debug_level 1 diff --git a/Tesseract/share/tessdata/tessconfigs/nobatch b/Tesseract/share/tessdata/tessconfigs/nobatch new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/nobatch @@ -0,0 +1 @@ + diff --git a/Tesseract/share/tessdata/tessconfigs/segdemo b/Tesseract/share/tessdata/tessconfigs/segdemo new file mode 100644 index 0000000..d7d90ae --- /dev/null +++ b/Tesseract/share/tessdata/tessconfigs/segdemo @@ -0,0 +1,10 @@ +################################################# +# Adaptive Matcher Using PreAdapted Templates +################################################# + +wordrec_display_splits 0 +wordrec_display_all_words 1 +wordrec_display_all_blobs 1 +wordrec_display_segmentations 2 +classify_debug_level 1 +stopper_debug_level 1