code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/********************************************************************** * File: tess_lang_model.h * Description: Declaration of the Tesseract Language Model Class * Author: Ahmad Abdulkader * Created: 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 TESS_LANG_MODEL_H #define TESS_LANG_MODEL_H #include <string> #include "char_altlist.h" #include "cube_reco_context.h" #include "cube_tuning_params.h" #include "dict.h" #include "lang_model.h" #include "tessdatamanager.h" #include "tess_lang_mod_edge.h" namespace tesseract { const int kStateCnt = 4; const int kNumLiteralCnt = 5; class TessLangModel : public LangModel { public: TessLangModel(const string &lm_params, const string &data_file_path, bool load_system_dawg, TessdataManager *tessdata_manager, CubeRecoContext *cntxt); ~TessLangModel() { if (word_dawgs_ != NULL) { word_dawgs_->delete_data_pointers(); delete word_dawgs_; } } // returns a pointer to the root of the language model inline TessLangModEdge *Root() { return NULL; } // The general fan-out generation function. Returns the list of edges // fanning-out of the specified edge and their count. If an AltList is // specified, only the class-ids with a minimum cost are considered LangModEdge **GetEdges(CharAltList *alt_list, LangModEdge *edge, int *edge_cnt); // Determines if a sequence of 32-bit chars is valid in this language model // starting from the root. If the eow_flag is ON, also checks for // a valid EndOfWord. If final_edge is not NULL, returns a pointer to the last // edge bool IsValidSequence(const char_32 *sequence, bool eow_flag, LangModEdge **final_edge = NULL); bool IsLeadingPunc(char_32 ch); bool IsTrailingPunc(char_32 ch); bool IsDigit(char_32 ch); void RemoveInvalidCharacters(string *lm_str); private: // static LM state machines static const Dawg *ood_dawg_; static const Dawg *number_dawg_; static const int num_state_machine_[kStateCnt][kNumLiteralCnt]; static const int num_max_repeat_[kStateCnt]; // word_dawgs_ should only be loaded if cube has its own version of the // unicharset (different from the one used by tesseract) and therefore // can not use the dawgs loaded for tesseract (since the unichar ids // encoded in the dawgs differ). DawgVector *word_dawgs_; static int max_edge_; static int max_ood_shape_cost_; // remaining language model elements needed by cube. These get loaded from // the .lm file string lead_punc_; string trail_punc_; string num_lead_punc_; string num_trail_punc_; string operators_; string digits_; string alphas_; // String of characters in RHS of each line of <lang>.cube.lm // Each element is hard-coded to correspond to a specific token type // (see LoadLangModelElements) string *literal_str_[kNumLiteralCnt]; // Recognition context needed to access language properties // (case, cursive,..) CubeRecoContext *cntxt_; bool has_case_; // computes and returns the edges that fan out of an edge ref int FanOut(CharAltList *alt_list, const Dawg *dawg, EDGE_REF edge_ref, EDGE_REF edge_ref_mask, const char_32 *str, bool root_flag, LangModEdge **edge_array); // generate edges from an NULL terminated string // (used for punctuation, operators and digits) int Edges(const char *strng, const Dawg *dawg, EDGE_REF edge_ref, EDGE_REF edge_ref_mask, LangModEdge **edge_array); // Generate the edges fanning-out from an edge in the number state machine int NumberEdges(EDGE_REF edge_ref, LangModEdge **edge_array); // Generate OOD edges int OODEdges(CharAltList *alt_list, EDGE_REF edge_ref, EDGE_REF edge_ref_mask, LangModEdge **edge_array); // Cleanup an edge array void FreeEdges(int edge_cnt, LangModEdge **edge_array); // Determines if a sequence of 32-bit chars is valid in this language model // starting from the specified edge. If the eow_flag is ON, also checks for // a valid EndOfWord. If final_edge is not NULL, returns a pointer to the last // edge bool IsValidSequence(LangModEdge *edge, const char_32 *sequence, bool eow_flag, LangModEdge **final_edge); // Parse language model elements from the given string, which should // have been loaded from <lang>.cube.lm file, e.g. in CubeRecoContext bool LoadLangModelElements(const string &lm_params); // Returns the number of word Dawgs in the language model. int NumDawgs() const; // Returns the dawgs with the given index from either the dawgs // stored by the Tesseract object, or the word_dawgs_. const Dawg *GetDawg(int index) const; }; } // tesseract #endif // TESS_LANG_MODEL_H
1080228-arabicocr11
cube/tess_lang_model.h
C++
asf20
5,489
/********************************************************************** * File: cube_utils.h * Description: Declaration of the Cube Utilities Class * Author: Ahmad Abdulkader * Created: 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. * **********************************************************************/ // The CubeUtils class provides miscellaneous utility and helper functions // to the rest of the Cube Engine #ifndef CUBE_UTILS_H #define CUBE_UTILS_H #include <vector> #include <string> #include "allheaders.h" #include "const.h" #include "char_set.h" #include "char_samp.h" namespace tesseract { class CubeUtils { public: CubeUtils(); ~CubeUtils(); // Converts a probability value to a cost by getting the -log() of the // probability value to a known base static int Prob2Cost(double prob_val); // Converts a cost to probability by getting the exp(-normalized cost) static double Cost2Prob(int cost); // Computes the length of a 32-bit char buffer static int StrLen(const char_32 *str); // Compares two 32-bit char buffers static int StrCmp(const char_32 *str1, const char_32 *str2); // Duplicates a 32-bit char buffer static char_32 *StrDup(const char_32 *str); // Creates a CharSamp from an Pix and a bounding box static CharSamp *CharSampleFromPix(Pix *pix, int left, int top, int wid, int hgt); // Creates a Pix from a CharSamp static Pix *PixFromCharSample(CharSamp *char_samp); // read the contents of a file to a string static bool ReadFileToString(const string &file_name, string *str); // split a string into vectors using any of the specified delimiters static void SplitStringUsing(const string &str, const string &delims, vector<string> *str_vec); // UTF-8 to UTF-32 convesion functions static void UTF8ToUTF32(const char *utf8_str, string_32 *str32); static void UTF32ToUTF8(const char_32 *utf32_str, string *str); // Returns true if input word has either 1) all-one-case, or 2) // first character upper-case, and remaining characters lower-case. // If char_set is not NULL, uses tesseract's unicharset functions // to determine case properties. Otherwise, uses C-locale-dependent // functions, which may be unreliable on non-ASCII characters. static bool IsCaseInvariant(const char_32 *str32, CharSet *char_set); // Returns char_32 pointer to the lower-case-transformed version of // the input string or NULL on error. If char_set is NULL returns NULL. // Return array must be freed by caller. static char_32 *ToLower(const char_32 *str32, CharSet *char_set); // Returns char_32 pointer to the upper-case-transformed version of // the input string or NULL on error. If char_set is NULL returns NULL. // Return array must be freed by caller. static char_32 *ToUpper(const char_32 *str32, CharSet *char_set); private: static unsigned char *GetImageData(Pix *pix, int left, int top, int wid, int hgt); }; } // namespace tesseract #endif // CUBE_UTILS_H
1080228-arabicocr11
cube/cube_utils.h
C++
asf20
3,632
/////////////////////////////////////////////////////////////////////// // 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__
1080228-arabicocr11
api/apitypes.h
C
asf20
1,359
/////////////////////////////////////////////////////////////////////// // 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__ #define TESSERACT_VERSION_STR "3.04.00" #define TESSERACT_VERSION 0x030400 #define MAKE_VERSION(major, minor, patch) (((major) << 16) | ((minor) << 8) | \ (patch)) #include <stdio.h> // To avoid collision with other typenames include the ABSOLUTE MINIMUM // complexity of includes here. Use forward declarations wherever possible // and hide includes of complex types in baseapi.cpp. #include "platform.h" #include "apitypes.h" #include "thresholder.h" #include "unichar.h" #include "tesscallback.h" #include "publictypes.h" #include "pageiterator.h" #include "resultiterator.h" template <typename T> class GenericVector; class PAGE_RES; class PAGE_RES_IT; class ParagraphModel; struct BlamerBundle; class BLOCK_LIST; class DENORM; class MATRIX; class ROW; class STRING; class WERD; struct Pix; struct Box; struct Pixa; struct Boxa; class ETEXT_DESC; struct OSResults; class TBOX; class UNICHARSET; class WERD_CHOICE_LIST; struct INT_FEATURE_STRUCT; typedef INT_FEATURE_STRUCT *INT_FEATURE; struct TBLOB; namespace tesseract { class CubeRecoContext; class Dawg; class Dict; class EquationDetect; class PageIterator; class LTRResultIterator; class ResultIterator; class MutableIterator; class TessResultRenderer; class Tesseract; class Trie; class Wordrec; typedef int (Dict::*DictFunc)(void* void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const; typedef double (Dict::*ProbabilityInContextFunc)(const char* lang, const char* context, int context_bytes, const char* character, int character_bytes); typedef float (Dict::*ParamsModelClassifyFunc)( const char *lang, void *path); typedef void (Wordrec::*FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle); typedef TessCallback4<const UNICHARSET &, int, PageIterator *, Pix *> TruthCallback; /** * 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(); /** * If compiled with OpenCL AND an available OpenCL * device is deemed faster than serial code, then * "device" is populated with the cl_device_id * and returns sizeof(cl_device_id) * otherwise *device=NULL and returns 0. */ static size_t getOpenCLDevice(void **device); /** * Writes the thresholded image to stderr as a PBM file on receipt of a * SIGSEGV, SIGFPE, or SIGBUS signal. (Linux/Unix only). */ static void CatchSignals(); /** * Set the name of the input file. Needed for training and * reading a UNLV zone file, and for searchable PDF output. */ void SetInputName(const char* name); /** * These functions are required for searchable PDF output. * We need our hands on the input file so that we can include * it in the PDF without transcoding. If that is not possible, * we need the original image. Finally, resolution metadata * is stored in the PDF so we need that as well. */ const char* GetInputName(); void SetInputImage(Pix *pix); Pix* GetInputImage(); int GetSourceYResolution(); const char* GetDatapath(); /** Set the name of the bonus output files. Needed only for debugging. */ void SetOutputName(const char* name); /** * 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(). * * 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 [~]<lang>[+[~]<lang>]* 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<STRING> *vars_vec, const GenericVector<STRING> *vars_values, bool set_only_non_debug_params); int Init(const char* datapath, const char* language, OcrEngineMode oem) { return Init(datapath, language, oem, NULL, 0, NULL, NULL, false); } 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<STRING>* langs) const; /** * Returns the available languages in the vector of STRINGs. */ void GetAvailableLanguagesAsVector(GenericVector<STRING>* langs) const; /** * Init only the lang model component of Tesseract. The only functions * that work after this init are SetVariable and IsValidWord. * WARNING: temporary! This function will be removed from here and placed * in a separate API at some future time. */ int InitLangMod(const char* datapath, const char* language); /** * 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(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 raw_image is true, then extract from the original image instead of the * thresholded image and pad by raw_padding pixels. * If blockids is not NULL, the block-id of each line is also returned as an * array of one element per line. delete [] after use. * If paraids is not NULL, the paragraph-id of each line within its block is * also returned as an array of one element per line. delete [] after use. */ Boxa* GetTextlines(const bool raw_image, const int raw_padding, Pixa** pixa, int** blockids, int** paraids); /* Helper method to extract from the thresholded image. (most common usage) */ Boxa* GetTextlines(Pixa** pixa, int** blockids) { return GetTextlines(false, 0, pixa, blockids, NULL); } /** * 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 blockids is not NULL, the paragraph-id of each component with its block * is also returned as an array of one element per component. delete [] after * use. * If raw_image is true, then portions of the original image are extracted * instead of the thresholded image and padded with raw_padding. * If text_only is true, then only text components are returned. */ Boxa* GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa** pixa, int** blockids, int** paraids); // Helper function to get binary images with no padding (most common usage). Boxa* GetComponentImages(const PageIteratorLevel level, const bool text_only, Pixa** pixa, int** blockids) { return GetComponentImages(level, text_only, false, 0, pixa, blockids, NULL); } /** * 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. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns NULL on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * 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() { return AnalyseLayout(false); } PageIterator* AnalyseLayout(bool merge_similar_words); /** * 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); /** * Turns images into symbolic text. * * filename can point to a single image, a multi-page TIFF, * or a plain text list of image filenames. * * retry_config is useful for debugging. If not NULL, you can fall * back to an alternate configuration if a page fails for some * reason. * * timeout_millisec terminates processing if any single page * takes too long. Set to 0 for unlimited time. * * renderer is responible for creating the output. For example, * use the TessTextRenderer if you want plaintext output, or * the TessPDFRender to produce searchable PDF. * * If tessedit_page_number is non-negative, will only process that * single page. Works for multi-page tiff file, or filelist. * * Returns true if successful, false on error. */ bool ProcessPages(const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer); /** * Turn a single image into symbolic text. * * The pix is the image processed. filename and page_index are * metadata used by side-effect processes, such as reading a box * file or formatting as hOCR. * * See ProcessPages for desciptions of other parameters. */ bool ProcessPage(Pix* pix, int page_index, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer); /** * 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(); /** * Clear any library-level memory caches. * There are a variety of expensive-to-load constant data structures (mostly * language dictionaries) that are cached globally -- surviving the Init() * and End() of individual TessBaseAPI's. This function allows the clearing * of these caches. **/ static void ClearPersistentCache(); /** * Check whether a word is valid according to Tesseract's language model * @return 0 if the word is invalid, non-zero if valid. * @warning temporary! This function will be removed from here and placed * in a separate API at some future time. */ int IsValidWord(const char *word); // Returns true if utf8_character is defined in the UniCharset. bool IsValidCharacter(const char *utf8_character); bool GetTextDirection(int* out_offset, float* out_slope); /** 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, INT_FEATURE_STRUCT* int_features, int* num_features, int* feature_outline_index); /** * This method returns the row to which a box of specified dimensions would * belong. If no good match is found, it returns 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, 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); 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. */ 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_; ///<The equation detector. ImageThresholder* thresholder_; ///< Image thresholding module. GenericVector<ParagraphModel *>* paragraph_models_; BLOCK_LIST* block_list_; ///< The page layout. PAGE_RES* page_res_; ///< The page-level data. STRING* input_file_; ///< Name used by training code. Pix* input_image_; ///< Image used for searchable PDF 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_; /* @} */ private: // A list of image filenames gets special consideration bool ProcessPagesFileList(FILE *fp, STRING *buf, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer, int tessedit_page_number); // TIFF supports multipage so gets special consideration bool ProcessPagesMultipageTiff(const unsigned char *data, size_t size, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer, int tessedit_page_number); }; // class TessBaseAPI. /** Escape a char string - remove &<>"' with HTML codes. */ STRING HOcrEscape(const char* text); } // namespace tesseract. #endif // TESSERACT_API_BASEAPI_H__
1080228-arabicocr11
api/baseapi.h
C++
asf20
34,731
#ifndef TESS_CAPI_INCLUDE_BASEAPI # define TESS_CAPI_INCLUDE_BASEAPI #endif #include "capi.h" #include "genericvector.h" #include "strngs.h" TESS_API const char* TESS_CALL TessVersion() { return TessBaseAPI::Version(); } TESS_API void TESS_CALL TessDeleteText(char* text) { delete [] text; } TESS_API void TESS_CALL TessDeleteTextArray(char** arr) { for (char** pos = arr; *pos != NULL; ++pos) delete [] *pos; delete [] arr; } TESS_API void TESS_CALL TessDeleteIntArray(int* arr) { delete [] arr; } TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list) { TessBaseAPI::DeleteBlockList(block_list); } TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase) { return new TessTextRenderer(outputbase); } TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate(const char* outputbase) { return new TessHOcrRenderer(outputbase); } TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate2(const char* outputbase, BOOL font_info) { return new TessHOcrRenderer(outputbase, font_info); } TESS_API TessResultRenderer* TESS_CALL TessPDFRendererCreate(const char* outputbase, const char* datadir) { return new TessPDFRenderer(outputbase, datadir); } TESS_API TessResultRenderer* TESS_CALL TessUnlvRendererCreate(const char* outputbase) { return new TessUnlvRenderer(outputbase); } TESS_API TessResultRenderer* TESS_CALL TessBoxTextRendererCreate(const char* outputbase) { return new TessBoxTextRenderer(outputbase); } TESS_API void TESS_CALL TessDeleteResultRenderer(TessResultRenderer* renderer) { delete [] renderer; } TESS_API void TESS_CALL TessResultRendererInsert(TessResultRenderer* renderer, TessResultRenderer* next) { renderer->insert(next); } TESS_API TessResultRenderer* TESS_CALL TessResultRendererNext(TessResultRenderer* renderer) { return renderer->next(); } TESS_API BOOL TESS_CALL TessResultRendererBeginDocument(TessResultRenderer* renderer, const char* title) { return renderer->BeginDocument(title); } TESS_API BOOL TESS_CALL TessResultRendererAddImage(TessResultRenderer* renderer, TessBaseAPI* api) { return renderer->AddImage(api); } TESS_API BOOL TESS_CALL TessResultRendererEndDocument(TessResultRenderer* renderer) { return renderer->EndDocument(); } TESS_API const char* TESS_CALL TessResultRendererExtention(TessResultRenderer* renderer) { return renderer->file_extension(); } TESS_API const char* TESS_CALL TessResultRendererTitle(TessResultRenderer* renderer) { return renderer->title(); } TESS_API int TESS_CALL TessResultRendererImageNum(TessResultRenderer* renderer) { return renderer->imagenum(); } TESS_API TessBaseAPI* TESS_CALL TessBaseAPICreate() { return new TessBaseAPI; } TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle) { delete handle; } TESS_API size_t TESS_CALL TessBaseAPIGetOpenCLDevice(TessBaseAPI* handle, void **device) { return handle->getOpenCLDevice(device); } TESS_API void TESS_CALL TessBaseAPISetInputName(TessBaseAPI* handle, const char* name) { handle->SetInputName(name); } TESS_API const char* TESS_CALL TessBaseAPIGetInputName(TessBaseAPI* handle) { return handle->GetInputName(); } TESS_API void TESS_CALL TessBaseAPISetInputImage(TessBaseAPI* handle, Pix* pix) { handle->SetInputImage(pix); } TESS_API Pix* TESS_CALL TessBaseAPIGetInputImage(TessBaseAPI* handle) { return handle->GetInputImage(); } TESS_API int TESS_CALL TessBaseAPIGetSourceYResolution(TessBaseAPI* handle) { return handle->GetSourceYResolution(); } TESS_API const char* TESS_CALL TessBaseAPIGetDatapath(TessBaseAPI* handle) { return handle->GetDatapath(); } TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name) { handle->SetOutputName(name); } TESS_API BOOL TESS_CALL TessBaseAPISetVariable(TessBaseAPI* handle, const char* name, const char* value) { return handle->SetVariable(name, value) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessBaseAPISetDebugVariable(TessBaseAPI* handle, const char* name, const char* value) { return handle->SetVariable(name, value) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable(const TessBaseAPI* handle, const char* name, int* value) { return handle->GetIntVariable(name, value) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable(const TessBaseAPI* handle, const char* name, BOOL* value) { bool boolValue; if (handle->GetBoolVariable(name, &boolValue)) { *value = boolValue ? TRUE : FALSE; return TRUE; } else { return FALSE; } } TESS_API BOOL TESS_CALL TessBaseAPIGetDoubleVariable(const TessBaseAPI* handle, const char* name, double* value) { return handle->GetDoubleVariable(name, value) ? TRUE : FALSE; } TESS_API const char* TESS_CALL TessBaseAPIGetStringVariable(const TessBaseAPI* handle, const char* name) { return handle->GetStringVariable(name); } TESS_API void TESS_CALL TessBaseAPIPrintVariables(const TessBaseAPI* handle, FILE* fp) { handle->PrintVariables(fp); } TESS_API BOOL TESS_CALL TessBaseAPIPrintVariablesToFile(const TessBaseAPI* handle, const char* filename) { FILE* fp = fopen(filename, "w"); if (fp != NULL) { handle->PrintVariables(fp); fclose(fp); return TRUE; } return FALSE; } TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val) { return handle->GetVariableAsString(name, val) ? TRUE : FALSE; } TESS_API int TESS_CALL TessBaseAPIInit4(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode mode, char** configs, int configs_size, char** vars_vec, char** vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params) { GenericVector<STRING> varNames; GenericVector<STRING> varValues; if (vars_vec != NULL && vars_values != NULL) { for (size_t i = 0; i < vars_vec_size; i++) { varNames.push_back(STRING(vars_vec[i])); varValues.push_back(STRING(vars_values[i])); } } return handle->Init(datapath, language, mode, configs, configs_size, &varNames, &varValues, set_only_non_debug_params); } TESS_API int TESS_CALL TessBaseAPIInit1(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem, char** configs, int configs_size) { return handle->Init(datapath, language, oem, configs, configs_size, NULL, NULL, false); } TESS_API int TESS_CALL TessBaseAPIInit2(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem) { return handle->Init(datapath, language, oem); } TESS_API int TESS_CALL TessBaseAPIInit3(TessBaseAPI* handle, const char* datapath, const char* language) { return handle->Init(datapath, language); } TESS_API const char* TESS_CALL TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI* handle) { return handle->GetInitLanguagesAsString(); } TESS_API char** TESS_CALL TessBaseAPIGetLoadedLanguagesAsVector(const TessBaseAPI* handle) { GenericVector<STRING> languages; handle->GetLoadedLanguagesAsVector(&languages); char** arr = new char*[languages.size() + 1]; for (int index = 0; index < languages.size(); ++index) arr[index] = languages[index].strdup(); arr[languages.size()] = NULL; return arr; } TESS_API char** TESS_CALL TessBaseAPIGetAvailableLanguagesAsVector(const TessBaseAPI* handle) { GenericVector<STRING> languages; handle->GetAvailableLanguagesAsVector(&languages); char** arr = new char*[languages.size() + 1]; for (int index = 0; index < languages.size(); ++index) arr[index] = languages[index].strdup(); arr[languages.size()] = NULL; return arr; } TESS_API int TESS_CALL TessBaseAPIInitLangMod(TessBaseAPI* handle, const char* datapath, const char* language) { return handle->InitLangMod(datapath, language); } TESS_API void TESS_CALL TessBaseAPIInitForAnalysePage(TessBaseAPI* handle) { handle->InitForAnalysePage(); } TESS_API void TESS_CALL TessBaseAPIReadConfigFile(TessBaseAPI* handle, const char* filename) { handle->ReadConfigFile(filename); } TESS_API void TESS_CALL TessBaseAPIReadDebugConfigFile(TessBaseAPI* handle, const char* filename) { handle->ReadDebugConfigFile(filename); } TESS_API void TESS_CALL TessBaseAPISetPageSegMode(TessBaseAPI* handle, TessPageSegMode mode) { handle->SetPageSegMode(mode); } TESS_API TessPageSegMode TESS_CALL TessBaseAPIGetPageSegMode(const TessBaseAPI* handle) { return handle->GetPageSegMode(); } 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) { return handle->TesseractRect(imagedata, bytes_per_pixel, bytes_per_line, left, top, width, height); } TESS_API void TESS_CALL TessBaseAPIClearAdaptiveClassifier(TessBaseAPI* handle) { handle->ClearAdaptiveClassifier(); } TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line) { handle->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line); } TESS_API void TESS_CALL TessBaseAPISetImage2(TessBaseAPI* handle, struct Pix* pix) { return handle->SetImage(pix); } TESS_API void TESS_CALL TessBaseAPISetSourceResolution(TessBaseAPI* handle, int ppi) { handle->SetSourceResolution(ppi); } TESS_API void TESS_CALL TessBaseAPISetRectangle(TessBaseAPI* handle, int left, int top, int width, int height) { handle->SetRectangle(left, top, width, height); } TESS_API void TESS_CALL TessBaseAPISetThresholder(TessBaseAPI* handle, TessImageThresholder* thresholder) { handle->SetThresholder(thresholder); } TESS_API struct Pix* TESS_CALL TessBaseAPIGetThresholdedImage(TessBaseAPI* handle) { return handle->GetThresholdedImage(); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetRegions(TessBaseAPI* handle, struct Pixa** pixa) { return handle->GetRegions(pixa); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines(TessBaseAPI* handle, struct Pixa** pixa, int** blockids) { return handle->GetTextlines(pixa, blockids); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines1(TessBaseAPI* handle, const BOOL raw_image, const int raw_padding, struct Pixa** pixa, int** blockids, int** paraids) { return handle->GetTextlines(raw_image, raw_padding, pixa, blockids, paraids); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetStrips(TessBaseAPI* handle, struct Pixa** pixa, int** blockids) { return handle->GetStrips(pixa, blockids); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetWords(TessBaseAPI* handle, struct Pixa** pixa) { return handle->GetWords(pixa); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, struct Pixa** cc) { return handle->GetConnectedComponents(cc); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetComponentImages(TessBaseAPI* handle, TessPageIteratorLevel level, BOOL text_only, struct Pixa** pixa, int** blockids) { return handle->GetComponentImages(level, text_only != FALSE, pixa, blockids); } TESS_API struct Boxa* TESS_CALL TessBaseAPIGetComponentImages1( TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only, const BOOL raw_image, const int raw_padding, struct Pixa** pixa, int** blockids, int** paraids) { return handle->GetComponentImages(level, text_only != FALSE, raw_image, raw_padding, pixa, blockids, paraids); } TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle) { return handle->GetThresholdedImageScaleFactor(); } TESS_API void TESS_CALL TessBaseAPIDumpPGM(TessBaseAPI* handle, const char* filename) { handle->DumpPGM(filename); } TESS_API TessPageIterator* TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle) { return handle->AnalyseLayout(); } TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor) { return handle->Recognize(monitor); } TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor) { return handle->RecognizeForChopTest(monitor); } TESS_API BOOL TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer) { if (handle->ProcessPages(filename, retry_config, timeout_millisec, renderer)) return TRUE; else return FALSE; } TESS_API BOOL TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, struct Pix* pix, int page_index, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer) { if (handle->ProcessPage(pix, page_index, filename, retry_config, timeout_millisec, renderer)) return TRUE; else return FALSE; } TESS_API TessResultIterator* TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle) { return handle->GetIterator(); } TESS_API TessMutableIterator* TESS_CALL TessBaseAPIGetMutableIterator(TessBaseAPI* handle) { return handle->GetMutableIterator(); } TESS_API char* TESS_CALL TessBaseAPIGetUTF8Text(TessBaseAPI* handle) { return handle->GetUTF8Text(); } TESS_API char* TESS_CALL TessBaseAPIGetHOCRText(TessBaseAPI* handle, int page_number) { return handle->GetHOCRText(page_number); } TESS_API char* TESS_CALL TessBaseAPIGetBoxText(TessBaseAPI* handle, int page_number) { return handle->GetBoxText(page_number); } TESS_API char* TESS_CALL TessBaseAPIGetUNLVText(TessBaseAPI* handle) { return handle->GetUNLVText(); } TESS_API int TESS_CALL TessBaseAPIMeanTextConf(TessBaseAPI* handle) { return handle->MeanTextConf(); } TESS_API int* TESS_CALL TessBaseAPIAllWordConfidences(TessBaseAPI* handle) { return handle->AllWordConfidences(); } TESS_API BOOL TESS_CALL TessBaseAPIAdaptToWordStr(TessBaseAPI* handle, TessPageSegMode mode, const char* wordstr) { return handle->AdaptToWordStr(mode, wordstr) ? TRUE : FALSE; } TESS_API void TESS_CALL TessBaseAPIClear(TessBaseAPI* handle) { handle->Clear(); } TESS_API void TESS_CALL TessBaseAPIEnd(TessBaseAPI* handle) { handle->End(); } TESS_API int TESS_CALL TessBaseAPIIsValidWord(TessBaseAPI* handle, const char* word) { return handle->IsValidWord(word); } TESS_API BOOL TESS_CALL TessBaseAPIGetTextDirection(TessBaseAPI* handle, int* out_offset, float* out_slope) { return handle->GetTextDirection(out_offset, out_slope) ? TRUE : FALSE; } TESS_API void TESS_CALL TessBaseAPISetDictFunc(TessBaseAPI* handle, TessDictFunc f) { handle->SetDictFunc(f); } TESS_API void TESS_CALL TessBaseAPIClearPersistentCache(TessBaseAPI* handle) { handle->ClearPersistentCache(); } TESS_API void TESS_CALL TessBaseAPISetProbabilityInContextFunc(TessBaseAPI* handle, TessProbabilityInContextFunc f) { handle->SetProbabilityInContextFunc(f); } TESS_API BOOL TESS_CALL TessBaseAPIDetectOS(TessBaseAPI* handle, OSResults* results) { return handle->DetectOS(results) ? TRUE : FALSE; } TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, INT_FEATURE_STRUCT* int_features, int* num_features, int* FeatureOutlineIndex) { handle->GetFeaturesForBlob(blob, int_features, num_features, FeatureOutlineIndex); } TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom) { return TessBaseAPI::FindRowForBox(blocks, left, top, right, bottom); } TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, int num_max_matches, int* unichar_ids, float* ratings, int* num_matches_returned) { handle->RunAdaptiveClassifier(blob, num_max_matches, unichar_ids, ratings, num_matches_returned); } TESS_API const char* TESS_CALL TessBaseAPIGetUnichar(TessBaseAPI* handle, int unichar_id) { return handle->GetUnichar(unichar_id); } TESS_API const TessDawg* TESS_CALL TessBaseAPIGetDawg(const TessBaseAPI* handle, int i) { return handle->GetDawg(i); } TESS_API int TESS_CALL TessBaseAPINumDawgs(const TessBaseAPI* handle) { return handle->NumDawgs(); } TESS_API ROW* TESS_CALL TessMakeTessOCRRow(float baseline, float xheight, float descender, float ascender) { return TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender); } TESS_API TBLOB* TESS_CALL TessMakeTBLOB(struct Pix* pix) { return TessBaseAPI::MakeTBLOB(pix); } TESS_API void TESS_CALL TessNormalizeTBLOB(TBLOB* tblob, ROW* row, BOOL numeric_mode) { TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode != FALSE); } TESS_API TessOcrEngineMode TESS_CALL TessBaseAPIOem(const TessBaseAPI* handle) { return handle->oem(); } TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback* cb) { handle->InitTruthCallback(cb); } TESS_API TessCubeRecoContext* TESS_CALL TessBaseAPIGetCubeRecoContext(const TessBaseAPI* handle) { return handle->GetCubeRecoContext(); } TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin) { handle->set_min_orientation_margin(margin); } TESS_API void TESS_CALL TessBaseGetBlockTextOrientations(TessBaseAPI* handle, int** block_orientation, bool** vertical_writing) { handle->GetBlockTextOrientations(block_orientation, vertical_writing); } TESS_API BLOCK_LIST* TESS_CALL TessBaseAPIFindLinesCreateBlockList(TessBaseAPI* handle) { return handle->FindLinesCreateBlockList(); } TESS_API void TESS_CALL TessPageIteratorDelete(TessPageIterator* handle) { delete handle; } TESS_API TessPageIterator* TESS_CALL TessPageIteratorCopy(const TessPageIterator* handle) { return new TessPageIterator(*handle); } TESS_API void TESS_CALL TessPageIteratorBegin(TessPageIterator* handle) { handle->Begin(); } TESS_API BOOL TESS_CALL TessPageIteratorNext(TessPageIterator* handle, TessPageIteratorLevel level) { return handle->Next(level) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessPageIteratorIsAtBeginningOf(const TessPageIterator* handle, TessPageIteratorLevel level) { return handle->IsAtBeginningOf(level) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessPageIteratorIsAtFinalElement(const TessPageIterator* handle, TessPageIteratorLevel level, TessPageIteratorLevel element) { return handle->IsAtFinalElement(level, element) ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessPageIteratorBoundingBox(const TessPageIterator* handle, TessPageIteratorLevel level, int* left, int* top, int* right, int* bottom) { return handle->BoundingBox(level, left, top, right, bottom) ? TRUE : FALSE; } TESS_API TessPolyBlockType TESS_CALL TessPageIteratorBlockType(const TessPageIterator* handle) { return handle->BlockType(); } TESS_API struct Pix* TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level) { return handle->GetBinaryImage(level); } TESS_API struct Pix* TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding, struct Pix* original_image, int* left, int* top) { return handle->GetImage(level, padding, original_image, left, top); } TESS_API BOOL TESS_CALL TessPageIteratorBaseline(const TessPageIterator* handle, TessPageIteratorLevel level, int* x1, int* y1, int* x2, int* y2) { return handle->Baseline(level, x1, y1, x2, y2) ? TRUE : FALSE; } TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation* orientation, TessWritingDirection* writing_direction, TessTextlineOrder* textline_order, float* deskew_angle) { handle->Orientation(orientation, writing_direction, textline_order, deskew_angle); } TESS_API void TESS_CALL TessResultIteratorDelete(TessResultIterator* handle) { delete handle; } TESS_API TessResultIterator* TESS_CALL TessResultIteratorCopy(const TessResultIterator* handle) { return new TessResultIterator(*handle); } TESS_API TessPageIterator* TESS_CALL TessResultIteratorGetPageIterator(TessResultIterator* handle) { return handle; } TESS_API const TessPageIterator* TESS_CALL TessResultIteratorGetPageIteratorConst(const TessResultIterator* handle) { return handle; } TESS_API const TessChoiceIterator* TESS_CALL TessResultIteratorGetChoiceIterator(const TessResultIterator* handle) { return new TessChoiceIterator(*handle); } TESS_API BOOL TESS_CALL TessResultIteratorNext(TessResultIterator* handle, TessPageIteratorLevel level) { return handle->Next(level); } TESS_API char* TESS_CALL TessResultIteratorGetUTF8Text(const TessResultIterator* handle, TessPageIteratorLevel level) { return handle->GetUTF8Text(level); } TESS_API float TESS_CALL TessResultIteratorConfidence(const TessResultIterator* handle, TessPageIteratorLevel level) { return handle->Confidence(level); } TESS_API const char* TESS_CALL TessResultIteratorWordRecognitionLanguage(const TessResultIterator* handle) { return handle->WordRecognitionLanguage(); } 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) { bool bool_is_bold, bool_is_italic, bool_is_underlined, bool_is_monospace, bool_is_serif, bool_is_smallcaps; const char* ret = handle->WordFontAttributes(&bool_is_bold, &bool_is_italic, &bool_is_underlined, &bool_is_monospace, &bool_is_serif, &bool_is_smallcaps, pointsize, font_id); if (is_bold) *is_bold = bool_is_bold ? TRUE : FALSE; if (is_italic) *is_italic = bool_is_italic ? TRUE : FALSE; if (is_underlined) *is_underlined = bool_is_underlined ? TRUE : FALSE; if (is_monospace) *is_monospace = bool_is_monospace ? TRUE : FALSE; if (is_serif) *is_serif = bool_is_serif ? TRUE : FALSE; if (is_smallcaps) *is_smallcaps = bool_is_smallcaps ? TRUE : FALSE; return ret; } TESS_API BOOL TESS_CALL TessResultIteratorWordIsFromDictionary(const TessResultIterator* handle) { return handle->WordIsFromDictionary() ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessResultIteratorWordIsNumeric(const TessResultIterator* handle) { return handle->WordIsNumeric() ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSuperscript(const TessResultIterator* handle) { return handle->SymbolIsSuperscript() ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSubscript(const TessResultIterator* handle) { return handle->SymbolIsSubscript() ? TRUE : FALSE; } TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsDropcap(const TessResultIterator* handle) { return handle->SymbolIsDropcap() ? TRUE : FALSE; } TESS_API void TESS_CALL TessChoiceIteratorDelete(TessChoiceIterator* handle) { delete handle; } TESS_API BOOL TESS_CALL TessChoiceIteratorNext(TessChoiceIterator* handle) { return handle->Next(); } TESS_API const char* TESS_CALL TessChoiceIteratorGetUTF8Text(const TessChoiceIterator* handle) { return handle->GetUTF8Text(); } TESS_API float TESS_CALL TessChoiceIteratorConfidence(const TessChoiceIterator* handle) { return handle->Confidence(); }
1080228-arabicocr11
api/capi.cpp
C++
asf20
24,460
/********************************************************************** * File: tessedit.cpp (Formerly tessedit.c) * Description: Main program for merge of tess and editor. * Author: Ray Smith * Created: Tue Jan 07 15:21:46 GMT 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ // Include automatically generated configuration file if running autoconf #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include <iostream> #include "allheaders.h" #include "baseapi.h" #include "basedir.h" #include "renderer.h" #include "strngs.h" #include "tprintf.h" #include "openclwrapper.h" #include "osdetect.h" /********************************************************************** * main() * **********************************************************************/ int main(int argc, char **argv) { if ((argc == 2 && strcmp(argv[1], "-v") == 0) || (argc == 2 && strcmp(argv[1], "--version") == 0)) { char *versionStrP; fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version()); versionStrP = getLeptonicaVersion(); fprintf(stderr, " %s\n", versionStrP); lept_free(versionStrP); versionStrP = getImagelibVersions(); fprintf(stderr, " %s\n", versionStrP); lept_free(versionStrP); #ifdef USE_OPENCL cl_platform_id platform; cl_uint num_platforms; cl_device_id devices[2]; cl_uint num_devices; char info[256]; int i; fprintf(stderr, " OpenCL info:\n"); clGetPlatformIDs(1, &platform, &num_platforms); fprintf(stderr, " Found %d platforms.\n", num_platforms); clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0); fprintf(stderr, " Platform name: %s.\n", info); clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0); fprintf(stderr, " Version: %s.\n", info); clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices); fprintf(stderr, " Found %d devices.\n", num_devices); for (i = 0; i < num_devices; ++i) { clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0); fprintf(stderr, " Device %d name: %s.\n", i+1, info); } #endif exit(0); } // Make the order of args a bit more forgiving than it used to be. const char* lang = "eng"; const char* image = NULL; const char* outputbase = NULL; const char* datapath = NULL; bool noocr = false; bool list_langs = false; bool print_parameters = false; GenericVector<STRING> vars_vec, vars_values; tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO; int arg = 1; while (arg < argc && (outputbase == NULL || argv[arg][0] == '-')) { if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) { lang = argv[arg + 1]; ++arg; } else if (strcmp(argv[arg], "--tessdata-dir") == 0 && arg + 1 < argc) { datapath = argv[arg + 1]; ++arg; } else if (strcmp(argv[arg], "--user-words") == 0 && arg + 1 < argc) { vars_vec.push_back("user_words_file"); vars_values.push_back(argv[arg + 1]); ++arg; } else if (strcmp(argv[arg], "--user-patterns") == 0 && arg + 1 < argc) { vars_vec.push_back("user_patterns_file"); vars_values.push_back(argv[arg + 1]); ++arg; } else if (strcmp(argv[arg], "--list-langs") == 0) { noocr = true; list_langs = true; } else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) { pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1])); ++arg; } else if (strcmp(argv[arg], "--print-parameters") == 0) { noocr = true; print_parameters = true; } else if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) { // handled properly after api init ++arg; } else if (image == NULL) { image = argv[arg]; } else if (outputbase == NULL) { outputbase = argv[arg]; } ++arg; } if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) { list_langs = true; noocr = true; } if (outputbase == NULL && noocr == false) { fprintf(stderr, "Usage:\n %s imagename|stdin outputbase|stdout " "[options...] [configfile...]\n\n", argv[0]); fprintf(stderr, "OCR options:\n"); fprintf(stderr, " --tessdata-dir /path\tspecify the location of tessdata" " path\n"); fprintf(stderr, " --user-words /path/to/file\tspecify the location of user" " words file\n"); fprintf(stderr, " --user-patterns /path/to/file\tspecify the location of" " user patterns file\n"); fprintf(stderr, " -l lang[+lang]\tspecify language(s) used for OCR\n"); fprintf(stderr, " -c configvar=value\tset value for control parameter.\n" "\t\t\tMultiple -c arguments are allowed.\n"); fprintf(stderr, " -psm pagesegmode\tspecify page segmentation mode.\n"); fprintf(stderr, "These options must occur before any configfile.\n\n"); fprintf(stderr, "pagesegmode values are:\n" " 0 = Orientation and script detection (OSD) only.\n" " 1 = Automatic page segmentation with OSD.\n" " 2 = Automatic page segmentation, but no OSD, or OCR\n" " 3 = Fully automatic page segmentation, but no OSD. (Default)\n" " 4 = Assume a single column of text of variable sizes.\n" " 5 = Assume a single uniform block of vertically aligned text.\n" " 6 = Assume a single uniform block of text.\n" " 7 = Treat the image as a single text line.\n" " 8 = Treat the image as a single word.\n" " 9 = Treat the image as a single word in a circle.\n" " 10 = Treat the image as a single character.\n\n"); fprintf(stderr, "Single options:\n"); fprintf(stderr, " -v --version: version info\n"); fprintf(stderr, " --list-langs: list available languages for tesseract " "engine. Can be used with --tessdata-dir.\n"); fprintf(stderr, " --print-parameters: print tesseract parameters to the " "stdout.\n"); exit(1); } if (outputbase != NULL && strcmp(outputbase, "-") && strcmp(outputbase, "stdout")) { tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n", tesseract::TessBaseAPI::Version()); } PERF_COUNT_START("Tesseract:main") tesseract::TessBaseAPI api; api.SetOutputName(outputbase); int rc = api.Init(datapath, lang, tesseract::OEM_DEFAULT, &(argv[arg]), argc - arg, &vars_vec, &vars_values, false); if (rc) { fprintf(stderr, "Could not initialize tesseract.\n"); exit(1); } char opt1[255], opt2[255]; for (arg = 0; arg < argc; arg++) { if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) { strncpy(opt1, argv[arg + 1], 255); char *p = strchr(opt1, '='); if (!p) { fprintf(stderr, "Missing = in configvar assignment\n"); exit(1); } *p = 0; strncpy(opt2, strchr(argv[arg + 1], '=') + 1, 255); opt2[254] = 0; ++arg; if (!api.SetVariable(opt1, opt2)) { fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2); } } } if (list_langs) { GenericVector<STRING> languages; api.GetAvailableLanguagesAsVector(&languages); fprintf(stderr, "List of available languages (%d):\n", languages.size()); for (int index = 0; index < languages.size(); ++index) { STRING& string = languages[index]; fprintf(stderr, "%s\n", string.string()); } api.End(); exit(0); } if (print_parameters) { FILE* fout = stdout; fprintf(stdout, "Tesseract parameters:\n"); api.PrintVariables(fout); api.End(); exit(0); } // We have 2 possible sources of pagesegmode: a config file and // the command line. For backwards compatability reasons, the // default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the // default for this program is tesseract::PSM_AUTO. We will let // the config file take priority, so the command-line default // can take priority over the tesseract default, so we use the // value from the command line only if the retrieved mode // is still tesseract::PSM_SINGLE_BLOCK, indicating no change // in any config file. Therefore the only way to force // tesseract::PSM_SINGLE_BLOCK is from the command line. // It would be simpler if we could set the value before Init, // but that doesn't work. if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK) api.SetPageSegMode(pagesegmode); if (pagesegmode == tesseract::PSM_AUTO_ONLY || pagesegmode == tesseract::PSM_OSD_ONLY) { int ret_val = 0; Pix* pixs = pixRead(image); if (!pixs) { fprintf(stderr, "Cannot open input file: %s\n", image); exit(2); } api.SetImage(pixs); if (pagesegmode == tesseract::PSM_OSD_ONLY) { OSResults osr; if (api.DetectOS(&osr)) { int orient = osr.best_result.orientation_id; int script_id = osr.get_best_script(orient); float orient_oco = osr.best_result.oconfidence; float orient_sco = osr.best_result.sconfidence; tprintf("Orientation: %d\nOrientation in degrees: %d\n" \ "Orientation confidence: %.2f\n" \ "Script: %d\nScript confidence: %.2f\n", orient, OrientationIdToValue(orient), orient_oco, script_id, orient_sco); } else { ret_val = 1; } } else { tesseract::Orientation orientation; tesseract::WritingDirection direction; tesseract::TextlineOrder order; float deskew_angle; tesseract::PageIterator* it = api.AnalyseLayout(); if (it) { it->Orientation(&orientation, &direction, &order, &deskew_angle); tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \ "Deskew angle: %.4f\n", orientation, direction, order, deskew_angle); } else { ret_val = 1; } delete it; } pixDestroy(&pixs); exit(ret_val); } bool b; tesseract::PointerVector<tesseract::TessResultRenderer> renderers; api.GetBoolVariable("tessedit_create_hocr", &b); if (b) { bool font_info; api.GetBoolVariable("hocr_font_info", &font_info); renderers.push_back(new tesseract::TessHOcrRenderer(outputbase, font_info)); } api.GetBoolVariable("tessedit_create_pdf", &b); if (b) { renderers.push_back(new tesseract::TessPDFRenderer(outputbase, api.GetDatapath())); } api.GetBoolVariable("tessedit_write_unlv", &b); if (b) renderers.push_back(new tesseract::TessUnlvRenderer(outputbase)); api.GetBoolVariable("tessedit_create_boxfile", &b); if (b) renderers.push_back(new tesseract::TessBoxTextRenderer(outputbase)); api.GetBoolVariable("tessedit_create_txt", &b); if (b) renderers.push_back(new tesseract::TessTextRenderer(outputbase)); if (!renderers.empty()) { // Since the PointerVector auto-deletes, null-out the renderers that are // added to the root, and leave the root in the vector. for (int r = 1; r < renderers.size(); ++r) { renderers[0]->insert(renderers[r]); renderers[r] = NULL; } if (!api.ProcessPages(image, NULL, 0, renderers[0])) { fprintf(stderr, "Error during processing.\n"); exit(1); } } PERF_COUNT_END return 0; // Normal exit }
1080228-arabicocr11
api/tesseractmain.cpp
C++
asf20
12,085
#ifndef TESSERACT_API_CAPI_H__ #define TESSERACT_API_CAPI_H__ #ifdef TESS_CAPI_INCLUDE_BASEAPI # include "baseapi.h" # include "pageiterator.h" # include "resultiterator.h" # include "renderer.h" #else # include "platform.h" # include <stdio.h> #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::TessResultRenderer TessResultRenderer; typedef tesseract::TessTextRenderer TessTextRenderer; typedef tesseract::TessHOcrRenderer TessHOcrRenderer; typedef tesseract::TessPDFRenderer TessPDFRenderer; typedef tesseract::TessUnlvRenderer TessUnlvRenderer; typedef tesseract::TessBoxTextRenderer TessBoxTextRenderer; typedef tesseract::TessBaseAPI TessBaseAPI; typedef tesseract::PageIterator TessPageIterator; typedef tesseract::ResultIterator TessResultIterator; typedef tesseract::MutableIterator TessMutableIterator; typedef tesseract::ChoiceIterator TessChoiceIterator; typedef tesseract::OcrEngineMode TessOcrEngineMode; typedef tesseract::PageSegMode TessPageSegMode; typedef tesseract::ImageThresholder TessImageThresholder; typedef tesseract::PageIteratorLevel TessPageIteratorLevel; typedef tesseract::DictFunc TessDictFunc; typedef tesseract::ProbabilityInContextFunc TessProbabilityInContextFunc; // typedef tesseract::ParamsModelClassifyFunc TessParamsModelClassifyFunc; typedef tesseract::FillLatticeFunc TessFillLatticeFunc; typedef tesseract::Dawg TessDawg; typedef tesseract::TruthCallback TessTruthCallback; typedef tesseract::CubeRecoContext TessCubeRecoContext; typedef tesseract::Orientation TessOrientation; typedef tesseract::WritingDirection TessWritingDirection; typedef tesseract::TextlineOrder TessTextlineOrder; typedef PolyBlockType TessPolyBlockType; #else typedef struct TessResultRenderer TessResultRenderer; typedef struct TessTextRenderer TessTextRenderer; typedef struct TessHOcrRenderer TessHOcrRenderer; typedef struct TessPDFRenderer TessPDFRenderer; typedef struct TessUnlvRenderer TessUnlvRenderer; typedef struct TessBoxTextRenderer TessBoxTextRenderer; typedef struct TessBaseAPI TessBaseAPI; typedef struct TessPageIterator TessPageIterator; typedef struct TessResultIterator TessResultIterator; typedef struct TessMutableIterator TessMutableIterator; typedef struct TessChoiceIterator TessChoiceIterator; typedef enum TessOcrEngineMode { OEM_TESSERACT_ONLY, OEM_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_SPARSE_TEXT, PSM_SPARSE_TEXT_OSD, PSM_COUNT } TessPageSegMode; typedef enum TessPageIteratorLevel { RIL_BLOCK, RIL_PARA, RIL_TEXTLINE, RIL_WORD, RIL_SYMBOL} TessPageIteratorLevel; typedef enum TessPolyBlockType { PT_UNKNOWN, PT_FLOWING_TEXT, PT_HEADING_TEXT, PT_PULLOUT_TEXT, PT_EQUATION, PT_INLINE_EQUATION, PT_TABLE, PT_VERTICAL_TEXT, PT_CAPTION_TEXT, PT_FLOWING_IMAGE, PT_HEADING_IMAGE, PT_PULLOUT_IMAGE, PT_HORZ_LINE, PT_VERT_LINE, PT_NOISE, PT_COUNT } TessPolyBlockType; typedef enum TessOrientation { ORIENTATION_PAGE_UP, ORIENTATION_PAGE_RIGHT, ORIENTATION_PAGE_DOWN, ORIENTATION_PAGE_LEFT } TessOrientation; typedef enum TessWritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT, WRITING_DIRECTION_RIGHT_TO_LEFT, WRITING_DIRECTION_TOP_TO_BOTTOM } TessWritingDirection; typedef enum TessTextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT, TEXTLINE_ORDER_RIGHT_TO_LEFT, TEXTLINE_ORDER_TOP_TO_BOTTOM } TessTextlineOrder; typedef struct ETEXT_DESC ETEXT_DESC; #endif struct Pix; struct Boxa; struct Pixa; /* General free functions */ TESS_API const char* TESS_CALL TessVersion(); TESS_API void TESS_CALL TessDeleteText(char* text); TESS_API void TESS_CALL TessDeleteTextArray(char** arr); TESS_API void TESS_CALL TessDeleteIntArray(int* arr); #ifdef TESS_CAPI_INCLUDE_BASEAPI TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list); #endif /* Renderer API */ TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase); TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate(const char* outputbase); TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate2(const char* outputbase, BOOL font_info); TESS_API TessResultRenderer* TESS_CALL TessPDFRendererCreate(const char* outputbase, const char* datadir); TESS_API TessResultRenderer* TESS_CALL TessUnlvRendererCreate(const char* outputbase); TESS_API TessResultRenderer* TESS_CALL TessBoxTextRendererCreate(const char* outputbase); TESS_API void TESS_CALL TessDeleteResultRenderer(TessResultRenderer* renderer); TESS_API void TESS_CALL TessResultRendererInsert(TessResultRenderer* renderer, TessResultRenderer* next); TESS_API TessResultRenderer* TESS_CALL TessResultRendererNext(TessResultRenderer* renderer); TESS_API BOOL TESS_CALL TessResultRendererBeginDocument(TessResultRenderer* renderer, const char* title); TESS_API BOOL TESS_CALL TessResultRendererAddImage(TessResultRenderer* renderer, TessBaseAPI* api); TESS_API BOOL TESS_CALL TessResultRendererEndDocument(TessResultRenderer* renderer); TESS_API const char* TESS_CALL TessResultRendererExtention(TessResultRenderer* renderer); TESS_API const char* TESS_CALL TessResultRendererTitle(TessResultRenderer* renderer); TESS_API int TESS_CALL TessResultRendererImageNum(TessResultRenderer* renderer); /* Base API */ TESS_API TessBaseAPI* TESS_CALL TessBaseAPICreate(); TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle); TESS_API size_t TESS_CALL TessBaseAPIGetOpenCLDevice(TessBaseAPI* handle, void **device); TESS_API void TESS_CALL TessBaseAPISetInputName( TessBaseAPI* handle, const char* name); TESS_API const char* TESS_CALL TessBaseAPIGetInputName(TessBaseAPI* handle); TESS_API void TESS_CALL TessBaseAPISetInputImage(TessBaseAPI* handle, struct Pix* pix); TESS_API struct Pix* TESS_CALL TessBaseAPIGetInputImage(TessBaseAPI* handle); TESS_API int TESS_CALL TessBaseAPIGetSourceYResolution(TessBaseAPI* handle); TESS_API const char* TESS_CALL TessBaseAPIGetDatapath(TessBaseAPI* handle); TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name); TESS_API BOOL TESS_CALL TessBaseAPISetVariable(TessBaseAPI* handle, const char* name, const char* value); TESS_API BOOL TESS_CALL TessBaseAPISetDebugVariable(TessBaseAPI* handle, const char* name, const char* value); TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable( const TessBaseAPI* handle, const char* name, int* value); TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable( const TessBaseAPI* handle, const char* name, BOOL* value); TESS_API BOOL TESS_CALL 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 int TESS_CALL TessBaseAPIInit4(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode mode, char** configs, int configs_size, char** vars_vec, char** vars_values, size_t vars_vec_size, BOOL set_only_non_debug_params); TESS_API const char* TESS_CALL TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI* handle); TESS_API char** 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, struct 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 struct Pix* TESS_CALL TessBaseAPIGetThresholdedImage( TessBaseAPI* handle); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetRegions( TessBaseAPI* handle, struct Pixa** pixa); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines( TessBaseAPI* handle, struct Pixa** pixa, int** blockids); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines1( TessBaseAPI* handle, const BOOL raw_image, const int raw_padding, struct Pixa** pixa, int** blockids, int** paraids); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetStrips( TessBaseAPI* handle, struct Pixa** pixa, int** blockids); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetWords( TessBaseAPI* handle, struct Pixa** pixa); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, struct Pixa** cc); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetComponentImages( TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only, struct Pixa** pixa, int** blockids); TESS_API struct Boxa* TESS_CALL TessBaseAPIGetComponentImages1( TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only, const BOOL raw_image, const int raw_padding, struct Pixa** pixa, int** blockids, int** paraids); TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle); TESS_API void TESS_CALL TessBaseAPIDumpPGM(TessBaseAPI* handle, const char* filename); TESS_API TessPageIterator* TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle); TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor); TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor); TESS_API BOOL TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer); TESS_API BOOL TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, struct Pix* pix, int page_index, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer); TESS_API TessResultIterator* TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle); 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 TessBaseAPIClearPersistentCache(TessBaseAPI* handle); TESS_API void TESS_CALL TessBaseAPISetProbabilityInContextFunc(TessBaseAPI* handle, TessProbabilityInContextFunc f); TESS_API void TESS_CALL TessBaseAPISetFillLatticeFunc(TessBaseAPI* handle, TessFillLatticeFunc f); TESS_API BOOL TESS_CALL TessBaseAPIDetectOS(TessBaseAPI* handle, OSResults* results); TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, INT_FEATURE_STRUCT* int_features, int* num_features, int* FeatureOutlineIndex); TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom); TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, int num_max_matches, int* unichar_ids, float* ratings, int* num_matches_returned); #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); 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 struct Pix* TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level); TESS_API struct Pix* TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding, struct Pix* original_image, int* left, int* top); TESS_API BOOL TESS_CALL TessPageIteratorBaseline(const TessPageIterator* handle, TessPageIteratorLevel level, int* x1, int* y1, int* x2, int* y2); TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation* orientation, TessWritingDirection* writing_direction, TessTextlineOrder* textline_order, float* deskew_angle); /* 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 const TessChoiceIterator* TESS_CALL TessResultIteratorGetChoiceIterator(const TessResultIterator* handle); TESS_API BOOL TESS_CALL TessResultIteratorNext(TessResultIterator* handle, TessPageIteratorLevel level); TESS_API char* TESS_CALL TessResultIteratorGetUTF8Text(const TessResultIterator* handle, TessPageIteratorLevel level); TESS_API float TESS_CALL TessResultIteratorConfidence(const TessResultIterator* handle, TessPageIteratorLevel level); TESS_API const char* TESS_CALL TessResultIteratorWordRecognitionLanguage(const TessResultIterator* handle); TESS_API const char* TESS_CALL TessResultIteratorWordFontAttributes(const TessResultIterator* handle, BOOL* is_bold, BOOL* is_italic, BOOL* is_underlined, BOOL* is_monospace, BOOL* is_serif, BOOL* is_smallcaps, int* pointsize, int* font_id); TESS_API BOOL TESS_CALL TessResultIteratorWordIsFromDictionary(const TessResultIterator* handle); TESS_API BOOL TESS_CALL TessResultIteratorWordIsNumeric(const TessResultIterator* handle); TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSuperscript(const TessResultIterator* handle); TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSubscript(const TessResultIterator* handle); TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsDropcap(const TessResultIterator* handle); TESS_API void TESS_CALL TessChoiceIteratorDelete(TessChoiceIterator* handle); TESS_API BOOL TESS_CALL TessChoiceIteratorNext(TessChoiceIterator* handle); TESS_API const char* TESS_CALL TessChoiceIteratorGetUTF8Text(const TessChoiceIterator* handle); TESS_API float TESS_CALL TessChoiceIteratorConfidence(const TessChoiceIterator* handle); #ifdef __cplusplus } #endif #endif /* TESSERACT_API_CAPI_H__ */
1080228-arabicocr11
api/capi.h
C
asf20
21,117
// Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "baseapi.h" #include "renderer.h" #include "math.h" #include "strngs.h" #include "cube_utils.h" #include "allheaders.h" #ifdef _MSC_VER #include "mathfix.h" #endif namespace tesseract { // Use for PDF object fragments. Must be large enough // to hold a colormap with 256 colors in the verbose // PDF representation. const int kBasicBufSize = 2048; // If the font is 10 pts, nominal character width is 5 pts const int kCharWidth = 2; /********************************************************************** * PDF Renderer interface implementation **********************************************************************/ TessPDFRenderer::TessPDFRenderer(const char* outputbase, const char *datadir) : TessResultRenderer(outputbase, "pdf") { obj_ = 0; datadir_ = datadir; offsets_.push_back(0); } void TessPDFRenderer::AppendPDFObjectDIY(size_t objectsize) { offsets_.push_back(objectsize + offsets_.back()); obj_++; } void TessPDFRenderer::AppendPDFObject(const char *data) { AppendPDFObjectDIY(strlen(data)); AppendString((const char *)data); } // Helper function to prevent us from accidentaly writing // scientific notation to an HOCR or PDF file. Besides, three // decimal points are all you really need. double prec(double x) { double kPrecision = 1000.0; double a = round(x * kPrecision) / kPrecision; if (a == -0) return 0; return a; } long dist2(int x1, int y1, int x2, int y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } // Viewers like evince can get really confused during copy-paste when // the baseline wanders around. So I've decided to project every word // onto the (straight) line baseline. All numbers are in the native // PDF coordinate system, which has the origin in the bottom left and // the unit is points, which is 1/72 inch. Tesseract reports baselines // left-to-right no matter what the reading order is. We need the // word baseline in reading order, so we do that conversion here. Returns // the word's baseline origin and length. void GetWordBaseline(int writing_direction, int ppi, int height, int word_x1, int word_y1, int word_x2, int word_y2, int line_x1, int line_y1, int line_x2, int line_y2, double *x0, double *y0, double *length) { if (writing_direction == WRITING_DIRECTION_RIGHT_TO_LEFT) { Swap(&word_x1, &word_x2); Swap(&word_y1, &word_y2); } double word_length; double x, y; { int px = word_x1; int py = word_y1; double l2 = dist2(line_x1, line_y1, line_x2, line_y2); if (l2 == 0) { x = line_x1; y = line_y1; } else { double t = ((px - line_x2) * (line_x2 - line_x1) + (py - line_y2) * (line_y2 - line_y1)) / l2; x = line_x2 + t * (line_x2 - line_x1); y = line_y2 + t * (line_y2 - line_y1); } word_length = sqrt(static_cast<double>(dist2(word_x1, word_y1, word_x2, word_y2))); word_length = word_length * 72.0 / ppi; x = x * 72 / ppi; y = height - (y * 72.0 / ppi); } *x0 = x; *y0 = y; *length = word_length; } // Compute coefficients for an affine matrix describing the rotation // of the text. If the text is right-to-left such as Arabic or Hebrew, // we reflect over the Y-axis. This matrix will set the coordinate // system for placing text in the PDF file. // // RTL // [ x' ] = [ a b ][ x ] = [-1 0 ] [ cos sin ][ x ] // [ y' ] [ c d ][ y ] [ 0 1 ] [-sin cos ][ y ] void AffineMatrix(int writing_direction, int line_x1, int line_y1, int line_x2, int line_y2, double *a, double *b, double *c, double *d) { double theta = atan2(static_cast<double>(line_y1 - line_y2), static_cast<double>(line_x2 - line_x1)); *a = cos(theta); *b = sin(theta); *c = -sin(theta); *d = cos(theta); switch(writing_direction) { case WRITING_DIRECTION_RIGHT_TO_LEFT: *a = -*a; *b = -*b; break; case WRITING_DIRECTION_TOP_TO_BOTTOM: // TODO(jbreiden) Consider using the vertical PDF writing mode. break; default: break; } } // There are some really stupid PDF viewers in the wild, such as // 'Preview' which ships with the Mac. They do a better job with text // selection and highlighting when given perfectly flat baseline // instead of very slightly tilted. We clip small tilts to appease // these viewers. I chose this threshold large enough to absorb noise, // but small enough that lines probably won't cross each other if the // whole page is tilted at almost exactly the clipping threshold. void ClipBaseline(int ppi, int x1, int y1, int x2, int y2, int *line_x1, int *line_y1, int *line_x2, int *line_y2) { *line_x1 = x1; *line_y1 = y1; *line_x2 = x2; *line_y2 = y2; double rise = abs(y2 - y1) * 72 / ppi; double run = abs(x2 - x1) * 72 / ppi; if (rise < 2.0 && 2.0 < run) *line_y1 = *line_y2 = (y1 + y2) / 2; } char* TessPDFRenderer::GetPDFTextObjects(TessBaseAPI* api, double width, double height) { STRING pdf_str(""); double ppi = api->GetSourceYResolution(); // These initial conditions are all arbitrary and will be overwritten double old_x = 0.0, old_y = 0.0; int old_fontsize = 0; tesseract::WritingDirection old_writing_direction = WRITING_DIRECTION_LEFT_TO_RIGHT; bool new_block = true; int fontsize = 0; double a = 1; double b = 0; double c = 0; double d = 1; // TODO(jbreiden) This marries the text and image together. // Slightly cleaner from an abstraction standpoint if this were to // live inside a separate text object. pdf_str += "q "; pdf_str.add_str_double("", prec(width)); pdf_str += " 0 0 "; pdf_str.add_str_double("", prec(height)); pdf_str += " 0 0 cm /Im1 Do Q\n"; ResultIterator *res_it = api->GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->IsAtBeginningOf(RIL_BLOCK)) { pdf_str += "BT\n3 Tr"; // Begin text object, use invisible ink old_fontsize = 0; // Every block will declare its fontsize new_block = true; // Every block will declare its affine matrix } int line_x1, line_y1, line_x2, line_y2; if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { int x1, y1, x2, y2; res_it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2); ClipBaseline(ppi, x1, y1, x2, y2, &line_x1, &line_y1, &line_x2, &line_y2); } if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Writing direction changes at a per-word granularity tesseract::WritingDirection writing_direction; { tesseract::Orientation orientation; tesseract::TextlineOrder textline_order; float deskew_angle; res_it->Orientation(&orientation, &writing_direction, &textline_order, &deskew_angle); if (writing_direction != WRITING_DIRECTION_TOP_TO_BOTTOM) { switch (res_it->WordDirection()) { case DIR_LEFT_TO_RIGHT: writing_direction = WRITING_DIRECTION_LEFT_TO_RIGHT; break; case DIR_RIGHT_TO_LEFT: writing_direction = WRITING_DIRECTION_RIGHT_TO_LEFT; break; default: writing_direction = old_writing_direction; } } } // Where is word origin and how long is it? double x, y, word_length; { int word_x1, word_y1, word_x2, word_y2; res_it->Baseline(RIL_WORD, &word_x1, &word_y1, &word_x2, &word_y2); GetWordBaseline(writing_direction, ppi, height, word_x1, word_y1, word_x2, word_y2, line_x1, line_y1, line_x2, line_y2, &x, &y, &word_length); } if (writing_direction != old_writing_direction || new_block) { AffineMatrix(writing_direction, line_x1, line_y1, line_x2, line_y2, &a, &b, &c, &d); pdf_str.add_str_double(" ", prec(a)); // . This affine matrix pdf_str.add_str_double(" ", prec(b)); // . sets the coordinate pdf_str.add_str_double(" ", prec(c)); // . system for all pdf_str.add_str_double(" ", prec(d)); // . text that follows. pdf_str.add_str_double(" ", prec(x)); // . pdf_str.add_str_double(" ", prec(y)); // . pdf_str += (" Tm "); // Place cursor absolutely new_block = false; } else { double dx = x - old_x; double dy = y - old_y; pdf_str.add_str_double(" ", prec(dx * a + dy * b)); pdf_str.add_str_double(" ", prec(dx * c + dy * d)); pdf_str += (" Td "); // Relative moveto } old_x = x; old_y = y; old_writing_direction = writing_direction; // Adjust font size on a per word granularity. Pay attention to // fontsize, old_fontsize, and pdf_str. We've found that for // in Arabic, Tesseract will happily return a fontsize of zero, // so we make up a default number to protect ourselves. { bool bold, italic, underlined, monospace, serif, smallcaps; int font_id; res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps, &fontsize, &font_id); const int kDefaultFontsize = 8; if (fontsize <= 0) fontsize = kDefaultFontsize; if (fontsize != old_fontsize) { char textfont[20]; snprintf(textfont, sizeof(textfont), "/f-0-0 %d Tf ", fontsize); pdf_str += textfont; old_fontsize = fontsize; } } bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); STRING pdf_word(""); int pdf_word_len = 0; do { const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL); if (grapheme && grapheme[0] != '\0') { // TODO(jbreiden) Do a real UTF-16BE conversion // http://en.wikipedia.org/wiki/UTF-16#Example_UTF-16_encoding_procedure string_32 utf32; CubeUtils::UTF8ToUTF32(grapheme, &utf32); char utf16[20]; for (int i = 0; i < static_cast<int>(utf32.length()); i++) { snprintf(utf16, sizeof(utf16), "<%04X>", utf32[i]); pdf_word += utf16; pdf_word_len++; } } delete []grapheme; res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); if (word_length > 0 && pdf_word_len > 0 && fontsize > 0) { double h_stretch = kCharWidth * prec(100.0 * word_length / (fontsize * pdf_word_len)); pdf_str.add_str_double("", h_stretch); pdf_str += " Tz"; // horizontal stretch pdf_str += " [ "; pdf_str += pdf_word; // UTF-16BE representation pdf_str += " ] TJ"; // show the text } if (last_word_in_line) { pdf_str += " \n"; } if (last_word_in_block) { pdf_str += "ET\n"; // end the text object } } char *ret = new char[pdf_str.length() + 1]; strcpy(ret, pdf_str.string()); delete res_it; return ret; } bool TessPDFRenderer::BeginDocumentHandler() { char buf[kBasicBufSize]; size_t n; n = snprintf(buf, sizeof(buf), "%%PDF-1.5\n" "%%%c%c%c%c\n", 0xDE, 0xAD, 0xBE, 0xEB); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); // CATALOG n = snprintf(buf, sizeof(buf), "1 0 obj\n" "<<\n" " /Type /Catalog\n" " /Pages %ld 0 R\n" ">>\n" "endobj\n", 2L); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); // We are reserving object #2 for the /Pages // object, which I am going to create and write // at the end of the PDF file. AppendPDFObject(""); // TYPE0 FONT n = snprintf(buf, sizeof(buf), "3 0 obj\n" "<<\n" " /BaseFont /GlyphLessFont\n" " /DescendantFonts [ %ld 0 R ]\n" " /Encoding /Identity-H\n" " /Subtype /Type0\n" " /ToUnicode %ld 0 R\n" " /Type /Font\n" ">>\n" "endobj\n", 4L, // CIDFontType2 font 5L // ToUnicode ); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); // CIDFONTTYPE2 n = snprintf(buf, sizeof(buf), "4 0 obj\n" "<<\n" " /BaseFont /GlyphLessFont\n" " /CIDToGIDMap /Identity\n" " /CIDSystemInfo\n" " <<\n" " /Ordering (Identity)\n" " /Registry (Adobe)\n" " /Supplement 0\n" " >>\n" " /FontDescriptor %ld 0 R\n" " /Subtype /CIDFontType2\n" " /Type /Font\n" " /DW %d\n" ">>\n" "endobj\n", 6L, // Font descriptor 1000 / kCharWidth); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); const char *stream = "/CIDInit /ProcSet findresource begin\n" "12 dict begin\n" "begincmap\n" "/CIDSystemInfo\n" "<<\n" " /Registry (Adobe)\n" " /Ordering (UCS)\n" " /Supplement 0\n" ">> def\n" "/CMapName /Adobe-Identify-UCS def\n" "/CMapType 2 def\n" "1 begincodespacerange\n" "<0000> <FFFF>\n" "endcodespacerange\n" "1 beginbfrange\n" "<0000> <FFFF> <0000>\n" "endbfrange\n" "endcmap\n" "CMapName currentdict /CMap defineresource pop\n" "end\n" "end\n"; // TOUNICODE n = snprintf(buf, sizeof(buf), "5 0 obj\n" "<< /Length %lu >>\n" "stream\n" "%s" "endstream\n" "endobj\n", (unsigned long) strlen(stream), stream); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); // FONT DESCRIPTOR const int kCharHeight = 2; // Effect: highlights are half height n = snprintf(buf, sizeof(buf), "6 0 obj\n" "<<\n" " /Ascent %d\n" " /CapHeight %d\n" " /Descent -1\n" // Spec says must be negative " /Flags 5\n" // FixedPitch + Symbolic " /FontBBox [ 0 0 %d %d ]\n" " /FontFile2 %ld 0 R\n" " /FontName /GlyphLessFont\n" " /ItalicAngle 0\n" " /StemV 80\n" " /Type /FontDescriptor\n" ">>\n" "endobj\n", 1000 / kCharHeight, 1000 / kCharHeight, 1000 / kCharWidth, 1000 / kCharHeight, 7L // Font data ); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); n = snprintf(buf, sizeof(buf), "%s/pdf.ttf", datadir_); if (n >= sizeof(buf)) return false; FILE *fp = fopen(buf, "rb"); if (!fp) return false; fseek(fp, 0, SEEK_END); long int size = ftell(fp); fseek(fp, 0, SEEK_SET); char *buffer = new char[size]; if (fread(buffer, 1, size, fp) != size) { fclose(fp); delete[] buffer; return false; } fclose(fp); // FONTFILE2 n = snprintf(buf, sizeof(buf), "7 0 obj\n" "<<\n" " /Length %ld\n" " /Length1 %ld\n" ">>\n" "stream\n", size, size); if (n >= sizeof(buf)) return false; AppendString(buf); size_t objsize = strlen(buf); AppendData(buffer, size); delete[] buffer; objsize += size; const char *b2 = "endstream\n" "endobj\n"; AppendString(b2); objsize += strlen(b2); AppendPDFObjectDIY(objsize); return true; } bool TessPDFRenderer::imageToPDFObj(Pix *pix, char *filename, long int objnum, char **pdf_object, long int *pdf_object_size) { size_t n; char b0[kBasicBufSize]; char b1[kBasicBufSize]; char b2[kBasicBufSize]; if (!pdf_object_size || !pdf_object) return false; *pdf_object = NULL; *pdf_object_size = 0; if (!filename) return false; L_COMP_DATA *cid = NULL; const int kJpegQuality = 85; // TODO(jbreiden) Leptonica 1.71 doesn't correctly handle certain // types of PNG files, especially if there are 2 samples per pixel. // We can get rid of this logic after Leptonica 1.72 is released and // has propagated everywhere. Bug discussion as follows. // https://code.google.com/p/tesseract-ocr/issues/detail?id=1300 int format, sad; findFileFormat(filename, &format); if (pixGetSpp(pix) == 4 && format == IFF_PNG) { pixSetSpp(pix, 3); sad = pixGenerateCIData(pix, L_FLATE_ENCODE, 0, 0, &cid); } else { sad = l_generateCIDataForPdf(filename, pix, kJpegQuality, &cid); } if (sad || !cid) { l_CIDataDestroy(&cid); return false; } const char *group4 = ""; const char *filter; switch(cid->type) { case L_FLATE_ENCODE: filter = "/FlateDecode"; break; case L_JPEG_ENCODE: filter = "/DCTDecode"; break; case L_G4_ENCODE: filter = "/CCITTFaxDecode"; group4 = " /K -1\n"; break; case L_JP2K_ENCODE: filter = "/JPXDecode"; break; default: l_CIDataDestroy(&cid); return false; } // Maybe someday we will accept RGBA but today is not that day. // It requires creating an /SMask for the alpha channel. // http://stackoverflow.com/questions/14220221 const char *colorspace; if (cid->ncolors > 0) { n = snprintf(b0, sizeof(b0), " /ColorSpace [ /Indexed /DeviceRGB %d %s ]\n", cid->ncolors - 1, cid->cmapdatahex); if (n >= sizeof(b0)) { l_CIDataDestroy(&cid); return false; } colorspace = b0; } else { switch (cid->spp) { case 1: colorspace = " /ColorSpace /DeviceGray\n"; break; case 3: colorspace = " /ColorSpace /DeviceRGB\n"; break; default: l_CIDataDestroy(&cid); return false; } } int predictor = (cid->predictor) ? 14 : 1; // IMAGE n = snprintf(b1, sizeof(b1), "%ld 0 obj\n" "<<\n" " /Length %ld\n" " /Subtype /Image\n", objnum, (unsigned long) cid->nbytescomp); if (n >= sizeof(b1)) { l_CIDataDestroy(&cid); return false; } n = snprintf(b2, sizeof(b2), " /Width %d\n" " /Height %d\n" " /BitsPerComponent %d\n" " /Filter %s\n" " /DecodeParms\n" " <<\n" " /Predictor %d\n" " /Colors %d\n" "%s" " /Columns %d\n" " /BitsPerComponent %d\n" " >>\n" ">>\n" "stream\n", cid->w, cid->h, cid->bps, filter, predictor, cid->spp, group4, cid->w, cid->bps); if (n >= sizeof(b2)) { l_CIDataDestroy(&cid); return false; } const char *b3 = "endstream\n" "endobj\n"; size_t b1_len = strlen(b1); size_t b2_len = strlen(b2); size_t b3_len = strlen(b3); size_t colorspace_len = strlen(colorspace); *pdf_object_size = b1_len + colorspace_len + b2_len + cid->nbytescomp + b3_len; *pdf_object = new char[*pdf_object_size]; if (!pdf_object) { l_CIDataDestroy(&cid); return false; } char *p = *pdf_object; memcpy(p, b1, b1_len); p += b1_len; memcpy(p, colorspace, colorspace_len); p += colorspace_len; memcpy(p, b2, b2_len); p += b2_len; memcpy(p, cid->datacomp, cid->nbytescomp); p += cid->nbytescomp; memcpy(p, b3, b3_len); l_CIDataDestroy(&cid); return true; } bool TessPDFRenderer::AddImageHandler(TessBaseAPI* api) { size_t n; char buf[kBasicBufSize]; Pix *pix = api->GetInputImage(); char *filename = (char *)api->GetInputName(); int ppi = api->GetSourceYResolution(); if (!pix || ppi <= 0) return false; double width = pixGetWidth(pix) * 72.0 / ppi; double height = pixGetHeight(pix) * 72.0 / ppi; // PAGE n = snprintf(buf, sizeof(buf), "%ld 0 obj\n" "<<\n" " /Type /Page\n" " /Parent %ld 0 R\n" " /MediaBox [0 0 %.2f %.2f]\n" " /Contents %ld 0 R\n" " /Resources\n" " <<\n" " /XObject << /Im1 %ld 0 R >>\n" " /ProcSet [ /PDF /Text /ImageB /ImageI /ImageC ]\n" " /Font << /f-0-0 %ld 0 R >>\n" " >>\n" ">>\n" "endobj\n", obj_, 2L, // Pages object width, height, obj_ + 1, // Contents object obj_ + 2, // Image object 3L); // Type0 Font if (n >= sizeof(buf)) return false; pages_.push_back(obj_); AppendPDFObject(buf); // CONTENTS char* pdftext = GetPDFTextObjects(api, width, height); long pdftext_len = strlen(pdftext); unsigned char *pdftext_casted = reinterpret_cast<unsigned char *>(pdftext); size_t len; unsigned char *comp_pdftext = zlibCompress(pdftext_casted, pdftext_len, &len); long comp_pdftext_len = len; n = snprintf(buf, sizeof(buf), "%ld 0 obj\n" "<<\n" " /Length %ld /Filter /FlateDecode\n" ">>\n" "stream\n", obj_, comp_pdftext_len); if (n >= sizeof(buf)) { delete[] pdftext; lept_free(comp_pdftext); return false; } AppendString(buf); long objsize = strlen(buf); AppendData(reinterpret_cast<char *>(comp_pdftext), comp_pdftext_len); objsize += comp_pdftext_len; lept_free(comp_pdftext); delete[] pdftext; const char *b2 = "endstream\n" "endobj\n"; AppendString(b2); objsize += strlen(b2); AppendPDFObjectDIY(objsize); char *pdf_object; if (!imageToPDFObj(pix, filename, obj_, &pdf_object, &objsize)) { return false; } AppendData(pdf_object, objsize); AppendPDFObjectDIY(objsize); delete[] pdf_object; return true; } bool TessPDFRenderer::EndDocumentHandler() { size_t n; char buf[kBasicBufSize]; // We reserved the /Pages object number early, so that the /Page // objects could refer to their parent. We finally have enough // information to go fill it in. Using lower level calls to manipulate // the offset record in two spots, because we are placing objects // out of order in the file. // PAGES const long int kPagesObjectNumber = 2; offsets_[kPagesObjectNumber] = offsets_.back(); // manipulation #1 n = snprintf(buf, sizeof(buf), "%ld 0 obj\n" "<<\n" " /Type /Pages\n" " /Kids [ ", kPagesObjectNumber); if (n >= sizeof(buf)) return false; AppendString(buf); size_t pages_objsize = strlen(buf); for (size_t i = 0; i < pages_.size(); i++) { n = snprintf(buf, sizeof(buf), "%ld 0 R ", pages_[i]); if (n >= sizeof(buf)) return false; AppendString(buf); pages_objsize += strlen(buf); } n = snprintf(buf, sizeof(buf), "]\n" " /Count %d\n" ">>\n" "endobj\n", pages_.size()); if (n >= sizeof(buf)) return false; AppendString(buf); pages_objsize += strlen(buf); offsets_.back() += pages_objsize; // manipulation #2 // INFO char* datestr = l_getFormattedDate(); n = snprintf(buf, sizeof(buf), "%ld 0 obj\n" "<<\n" " /Producer (Tesseract %s)\n" " /CreationDate (D:%s)\n" " /Title (%s)" ">>\n" "endobj\n", obj_, TESSERACT_VERSION_STR, datestr, title()); lept_free(datestr); if (n >= sizeof(buf)) return false; AppendPDFObject(buf); n = snprintf(buf, sizeof(buf), "xref\n" "0 %ld\n" "0000000000 65535 f \n", obj_); if (n >= sizeof(buf)) return false; AppendString(buf); for (int i = 1; i < obj_; i++) { n = snprintf(buf, sizeof(buf), "%010ld 00000 n \n", offsets_[i]); if (n >= sizeof(buf)) return false; AppendString(buf); } n = snprintf(buf, sizeof(buf), "trailer\n" "<<\n" " /Size %ld\n" " /Root %ld 0 R\n" " /Info %ld 0 R\n" ">>\n" "startxref\n" "%ld\n" "%%%%EOF\n", obj_, 1L, // catalog obj_ - 1, // info offsets_.back()); if (n >= sizeof(buf)) return false; AppendString(buf); return true; } } // namespace tesseract
1080228-arabicocr11
api/pdfrenderer.cpp
C++
asf20
25,359
// Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include <string.h> #include "baseapi.h" #include "genericvector.h" #include "renderer.h" namespace tesseract { /********************************************************************** * Base Renderer interface implementation **********************************************************************/ TessResultRenderer::TessResultRenderer(const char *outputbase, const char* extension) : file_extension_(extension), title_(""), imagenum_(-1), fout_(stdout), next_(NULL), happy_(true) { if (strcmp(outputbase, "-") && strcmp(outputbase, "stdout")) { STRING outfile = STRING(outputbase) + STRING(".") + STRING(file_extension_); fout_ = fopen(outfile.string(), "wb"); if (fout_ == NULL) { happy_ = false; } } } TessResultRenderer::~TessResultRenderer() { if (fout_ != stdout) fclose(fout_); else clearerr(fout_); delete next_; } void TessResultRenderer::insert(TessResultRenderer* next) { if (next == NULL) return; TessResultRenderer* remainder = next_; next_ = next; if (remainder) { while (next->next_ != NULL) { next = next->next_; } next->next_ = remainder; } } bool TessResultRenderer::BeginDocument(const char* title) { if (!happy_) return false; title_ = title; imagenum_ = -1; bool ok = BeginDocumentHandler(); if (next_) { ok = next_->BeginDocument(title) && ok; } return ok; } bool TessResultRenderer::AddImage(TessBaseAPI* api) { if (!happy_) return false; ++imagenum_; bool ok = AddImageHandler(api); if (next_) { ok = next_->AddImage(api) && ok; } return ok; } bool TessResultRenderer::EndDocument() { if (!happy_) return false; bool ok = EndDocumentHandler(); if (next_) { ok = next_->EndDocument() && ok; } return ok; } void TessResultRenderer::AppendString(const char* s) { AppendData(s, strlen(s)); } void TessResultRenderer::AppendData(const char* s, int len) { int n = fwrite(s, 1, len, fout_); if (n != len) happy_ = false; } bool TessResultRenderer::BeginDocumentHandler() { return happy_; } bool TessResultRenderer::EndDocumentHandler() { return happy_; } /********************************************************************** * UTF8 Text Renderer interface implementation **********************************************************************/ TessTextRenderer::TessTextRenderer(const char *outputbase) : TessResultRenderer(outputbase, "txt") { } bool TessTextRenderer::AddImageHandler(TessBaseAPI* api) { char* utf8 = api->GetUTF8Text(); if (utf8 == NULL) { return false; } AppendString(utf8); delete[] utf8; return true; } /********************************************************************** * HOcr Text Renderer interface implementation **********************************************************************/ TessHOcrRenderer::TessHOcrRenderer(const char *outputbase) : TessResultRenderer(outputbase, "hocr") { font_info_ = false; } TessHOcrRenderer::TessHOcrRenderer(const char *outputbase, bool font_info) : TessResultRenderer(outputbase, "hocr") { font_info_ = font_info; } bool TessHOcrRenderer::BeginDocumentHandler() { AppendString( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" " "lang=\"en\">\n <head>\n <title>\n"); AppendString(title()); AppendString( "</title>\n" "<meta http-equiv=\"Content-Type\" content=\"text/html;" "charset=utf-8\" />\n" " <meta name='ocr-system' content='tesseract " TESSERACT_VERSION_STR "' />\n" " <meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par" " ocr_line ocrx_word"); if (font_info_) AppendString( " ocrp_lang ocrp_dir ocrp_font ocrp_fsize ocrp_wconf"); AppendString( "'/>\n" "</head>\n<body>\n"); return true; } bool TessHOcrRenderer::EndDocumentHandler() { AppendString(" </body>\n</html>\n"); return true; } bool TessHOcrRenderer::AddImageHandler(TessBaseAPI* api) { char* hocr = api->GetHOCRText(imagenum()); if (hocr == NULL) return false; AppendString(hocr); delete[] hocr; return true; } /********************************************************************** * UNLV Text Renderer interface implementation **********************************************************************/ TessUnlvRenderer::TessUnlvRenderer(const char *outputbase) : TessResultRenderer(outputbase, "unlv") { } bool TessUnlvRenderer::AddImageHandler(TessBaseAPI* api) { char* unlv = api->GetUNLVText(); if (unlv == NULL) return false; AppendString(unlv); delete[] unlv; return true; } /********************************************************************** * BoxText Renderer interface implementation **********************************************************************/ TessBoxTextRenderer::TessBoxTextRenderer(const char *outputbase) : TessResultRenderer(outputbase, "box") { } bool TessBoxTextRenderer::AddImageHandler(TessBaseAPI* api) { char* text = api->GetBoxText(imagenum()); if (text == NULL) return false; AppendString(text); delete[] text; return true; } } // namespace tesseract
1080228-arabicocr11
api/renderer.cpp
C++
asf20
5,526
AM_CPPFLAGS += -DLOCALEDIR=\"$(localedir)\"\ -DUSE_STD_NAMESPACE \ -I$(top_srcdir)/ccutil -I$(top_srcdir)/ccstruct -I$(top_srcdir)/cube \ -I$(top_srcdir)/viewer \ -I$(top_srcdir)/textord -I$(top_srcdir)/dict \ -I$(top_srcdir)/classify -I$(top_srcdir)/ccmain \ -I$(top_srcdir)/wordrec -I$(top_srcdir)/cutil \ -I$(top_srcdir)/opencl if USE_OPENCL AM_CPPFLAGS += -I$(OPENCL_HDR_PATH) endif if VISIBILITY AM_CPPFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden endif include_HEADERS = apitypes.h baseapi.h capi.h renderer.h lib_LTLIBRARIES = if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_api.la else lib_LTLIBRARIES += libtesseract_api.la libtesseract_api_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_api_la_LIBADD = \ ../ccmain/libtesseract_main.la \ ../cube/libtesseract_cube.la \ ../neural_networks/runtime/libtesseract_neural.la \ ../textord/libtesseract_textord.la \ ../wordrec/libtesseract_wordrec.la \ ../classify/libtesseract_classify.la \ ../dict/libtesseract_dict.la \ ../ccstruct/libtesseract_ccstruct.la \ ../cutil/libtesseract_cutil.la \ ../viewer/libtesseract_viewer.la \ ../ccutil/libtesseract_ccutil.la \ ../opencl/libtesseract_opencl.la endif libtesseract_api_la_CPPFLAGS = $(AM_CPPFLAGS) if VISIBILITY libtesseract_api_la_CPPFLAGS += -DTESS_EXPORTS endif libtesseract_api_la_SOURCES = baseapi.cpp capi.cpp pdfrenderer.cpp renderer.cpp lib_LTLIBRARIES += libtesseract.la libtesseract_la_LDFLAGS = libtesseract_la_SOURCES = # Dummy C++ source to cause C++ linking. # see http://www.gnu.org/s/hello/manual/automake/Libtool-Convenience-Libraries.html#Libtool-Convenience-Libraries nodist_EXTRA_libtesseract_la_SOURCES = dummy.cxx libtesseract_la_LIBADD = \ libtesseract_api.la \ ../ccmain/libtesseract_main.la \ ../cube/libtesseract_cube.la \ ../neural_networks/runtime/libtesseract_neural.la \ ../textord/libtesseract_textord.la \ ../wordrec/libtesseract_wordrec.la \ ../classify/libtesseract_classify.la \ ../dict/libtesseract_dict.la \ ../ccstruct/libtesseract_ccstruct.la \ ../cutil/libtesseract_cutil.la \ ../viewer/libtesseract_viewer.la \ ../ccutil/libtesseract_ccutil.la \ ../opencl/libtesseract_opencl.la libtesseract_la_LDFLAGS += -version-info $(GENERIC_LIBRARY_VERSION) bin_PROGRAMS = tesseract tesseract_SOURCES = tesseractmain.cpp tesseract_CPPFLAGS = $(AM_CPPFLAGS) if VISIBILITY tesseract_CPPFLAGS += -DTESS_IMPORTS endif tesseract_LDADD = libtesseract.la if USE_OPENCL tesseract_LDADD += $(OPENCL_LIB) endif if T_WIN tesseract_LDADD += -lws2_32 libtesseract_la_LDFLAGS += -no-undefined -Wl,--as-needed -lws2_32 endif if ADD_RT tesseract_LDADD += -lrt endif
1080228-arabicocr11
api/Makefile.am
Makefile
asf20
2,766
/********************************************************************** * File: baseapi.cpp * 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. * **********************************************************************/ // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #ifdef __linux__ #include <signal.h> #endif #if defined(_WIN32) #ifdef _MSC_VER #include "mathfix.h" #elif MINGW // workaround for stdlib.h with -std=c++11 for _splitpath and _MAX_FNAME #undef __STRICT_ANSI__ #endif // _MSC_VER #include <stdlib.h> #include <windows.h> #include <fcntl.h> #include <io.h> #else #include <dirent.h> #include <libgen.h> #include <string.h> #endif // _WIN32 #include <iostream> #include <string> #include <iterator> #include <fstream> #include "allheaders.h" #include "baseapi.h" #include "resultiterator.h" #include "mutableiterator.h" #include "thresholder.h" #include "tesseractclass.h" #include "pageres.h" #include "paragraphs.h" #include "tessvars.h" #include "control.h" #include "dict.h" #include "pgedit.h" #include "paramsd.h" #include "output.h" #include "globaloc.h" #include "globals.h" #include "edgblob.h" #include "equationdetect.h" #include "tessbox.h" #include "makerow.h" #include "otsuthr.h" #include "osdetect.h" #include "params.h" #include "renderer.h" #include "strngs.h" #include "openclwrapper.h" BOOL_VAR(stream_filelist, FALSE, "Stream a filelist from stdin"); namespace tesseract { /** Minimum sensible image size to be worth running tesseract. */ const int kMinRectSize = 10; /** Character returned when Tesseract couldn't recognize as anything. */ const char kTesseractReject = '~'; /** Character used by UNLV error counter as a reject. */ const char kUNLVReject = '~'; /** Character used by UNLV as a suspect marker. */ const char kUNLVSuspect = '^'; /** * Filename used for input image file, from which to derive a name to search * for a possible UNLV zone file, if none is specified by SetInputName. */ const char* kInputFile = "noname.tif"; /** * Temp file used for storing current parameters before applying retry values. */ const char* kOldVarsFile = "failed_vars.txt"; /** Max string length of an int. */ const int kMaxIntSize = 22; /** * Minimum believable resolution. Used as a default if there is no other * information, as it is safer to under-estimate than over-estimate. */ const int kMinCredibleResolution = 70; /** Maximum believable resolution. */ const int kMaxCredibleResolution = 2400; TessBaseAPI::TessBaseAPI() : tesseract_(NULL), osd_tesseract_(NULL), equ_detect_(NULL), // Thresholder is initialized to NULL here, but will be set before use by: // A constructor of a derived API, SetThresholder(), or // created implicitly when used in InternalSetImage. thresholder_(NULL), paragraph_models_(NULL), block_list_(NULL), page_res_(NULL), input_file_(NULL), input_image_(NULL), output_file_(NULL), datapath_(NULL), language_(NULL), last_oem_requested_(OEM_DEFAULT), recognition_done_(false), truth_cb_(NULL), rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0), image_width_(0), image_height_(0) { } TessBaseAPI::~TessBaseAPI() { End(); } /** * Returns the version identifier as a static string. Do not delete. */ const char* TessBaseAPI::Version() { return TESSERACT_VERSION_STR; } /** * If compiled with OpenCL AND an available OpenCL * device is deemed faster than serial code, then * "device" is populated with the cl_device_id * and returns sizeof(cl_device_id) * otherwise *device=NULL and returns 0. */ #ifdef USE_OPENCL #if USE_DEVICE_SELECTION #include "opencl_device_selection.h" #endif #endif size_t TessBaseAPI::getOpenCLDevice(void **data) { #ifdef USE_OPENCL #if USE_DEVICE_SELECTION ds_device device = OpenclDevice::getDeviceSelection(); if (device.type == DS_DEVICE_OPENCL_DEVICE) { *data = reinterpret_cast<void*>(new cl_device_id); memcpy(*data, &device.oclDeviceID, sizeof(cl_device_id)); return sizeof(cl_device_id); } #endif #endif *data = NULL; return 0; } /** * Writes the thresholded image to stderr as a PBM file on receipt of a * SIGSEGV, SIGFPE, or SIGBUS signal. (Linux/Unix only). */ void TessBaseAPI::CatchSignals() { #ifdef __linux__ struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = &signal_exit; action.sa_flags = SA_RESETHAND; sigaction(SIGSEGV, &action, NULL); sigaction(SIGFPE, &action, NULL); sigaction(SIGBUS, &action, NULL); #else // Warn API users that an implementation is needed. tprintf("CatchSignals has no non-linux implementation!\n"); #endif } /** * Set the name of the input file. Needed only for training and * loading a UNLV zone file. */ void TessBaseAPI::SetInputName(const char* name) { if (input_file_ == NULL) input_file_ = new STRING(name); else *input_file_ = name; } /** Set the name of the output files. Needed only for debugging. */ void TessBaseAPI::SetOutputName(const char* name) { if (output_file_ == NULL) output_file_ = new STRING(name); else *output_file_ = name; } bool TessBaseAPI::SetVariable(const char* name, const char* value) { if (tesseract_ == NULL) tesseract_ = new Tesseract; return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_NON_INIT_ONLY, tesseract_->params()); } bool TessBaseAPI::SetDebugVariable(const char* name, const char* value) { if (tesseract_ == NULL) tesseract_ = new Tesseract; return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_DEBUG_ONLY, tesseract_->params()); } bool TessBaseAPI::GetIntVariable(const char *name, int *value) const { IntParam *p = ParamUtils::FindParam<IntParam>( name, GlobalParams()->int_params, tesseract_->params()->int_params); if (p == NULL) return false; *value = (inT32)(*p); return true; } bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const { BoolParam *p = ParamUtils::FindParam<BoolParam>( name, GlobalParams()->bool_params, tesseract_->params()->bool_params); if (p == NULL) return false; *value = (BOOL8)(*p); return true; } const char *TessBaseAPI::GetStringVariable(const char *name) const { StringParam *p = ParamUtils::FindParam<StringParam>( name, GlobalParams()->string_params, tesseract_->params()->string_params); return (p != NULL) ? p->string() : NULL; } bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const { DoubleParam *p = ParamUtils::FindParam<DoubleParam>( name, GlobalParams()->double_params, tesseract_->params()->double_params); if (p == NULL) return false; *value = (double)(*p); return true; } /** Get value of named variable as a string, if it exists. */ bool TessBaseAPI::GetVariableAsString(const char *name, STRING *val) { return ParamUtils::GetParamAsString(name, tesseract_->params(), val); } /** Print Tesseract parameters to the given file. */ void TessBaseAPI::PrintVariables(FILE *fp) const { ParamUtils::PrintParams(fp, tesseract_->params()); } /** * The datapath must be the name of the data directory (no ending /) or * some other file in which the data directory resides (for instance argv[0].) * The language is (usually) an ISO 639-3 string or NULL will default to eng. * If numeric_mode is true, then only digits and Roman numerals will * be returned. * @return: 0 on success and -1 on initialization failure. */ int TessBaseAPI::Init(const char* datapath, const char* language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector<STRING> *vars_vec, const GenericVector<STRING> *vars_values, bool set_only_non_debug_params) { PERF_COUNT_START("TessBaseAPI::Init") // Default language is "eng". if (language == NULL) language = "eng"; // If the datapath, OcrEngineMode or the language have changed - start again. // Note that the language_ field stores the last requested language that was // initialized successfully, while tesseract_->lang stores the language // actually used. They differ only if the requested language was NULL, in // which case tesseract_->lang is set to the Tesseract default ("eng"). if (tesseract_ != NULL && (datapath_ == NULL || language_ == NULL || *datapath_ != datapath || last_oem_requested_ != oem || (*language_ != language && tesseract_->lang != language))) { delete tesseract_; tesseract_ = NULL; } // PERF_COUNT_SUB("delete tesseract_") #ifdef USE_OPENCL OpenclDevice od; od.InitEnv(); #endif PERF_COUNT_SUB("OD::InitEnv()") bool reset_classifier = true; if (tesseract_ == NULL) { reset_classifier = false; tesseract_ = new Tesseract; if (tesseract_->init_tesseract( datapath, output_file_ != NULL ? output_file_->string() : NULL, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params) != 0) { return -1; } } PERF_COUNT_SUB("update tesseract_") // Update datapath and language requested for the last valid initialization. if (datapath_ == NULL) datapath_ = new STRING(datapath); else *datapath_ = datapath; if ((strcmp(datapath_->string(), "") == 0) && (strcmp(tesseract_->datadir.string(), "") != 0)) *datapath_ = tesseract_->datadir; if (language_ == NULL) language_ = new STRING(language); else *language_ = language; last_oem_requested_ = oem; // PERF_COUNT_SUB("update last_oem_requested_") // For same language and datapath, just reset the adaptive classifier. if (reset_classifier) { tesseract_->ResetAdaptiveClassifier(); PERF_COUNT_SUB("tesseract_->ResetAdaptiveClassifier()") } PERF_COUNT_END return 0; } /** * 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* TessBaseAPI::GetInitLanguagesAsString() const { return (language_ == NULL || language_->string() == NULL) ? "" : language_->string(); } /** * 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 TessBaseAPI::GetLoadedLanguagesAsVector( GenericVector<STRING>* langs) const { langs->clear(); if (tesseract_ != NULL) { langs->push_back(tesseract_->lang); int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) langs->push_back(tesseract_->get_sub_lang(i)->lang); } } /** * Returns the available languages in the vector of STRINGs. */ void TessBaseAPI::GetAvailableLanguagesAsVector( GenericVector<STRING>* langs) const { langs->clear(); if (tesseract_ != NULL) { #ifdef _WIN32 STRING pattern = tesseract_->datadir + "/*." + kTrainedDataSuffix; char fname[_MAX_FNAME]; WIN32_FIND_DATA data; BOOL result = TRUE; HANDLE handle = FindFirstFile(pattern.string(), &data); if (handle != INVALID_HANDLE_VALUE) { for (; result; result = FindNextFile(handle, &data)) { _splitpath(data.cFileName, NULL, NULL, fname, NULL); langs->push_back(STRING(fname)); } FindClose(handle); } #else // _WIN32 DIR *dir; struct dirent *dirent; char *dot; STRING extension = STRING(".") + kTrainedDataSuffix; dir = opendir(tesseract_->datadir.string()); if (dir != NULL) { while ((dirent = readdir(dir))) { // Skip '.', '..', and hidden files if (dirent->d_name[0] != '.') { if (strstr(dirent->d_name, extension.string()) != NULL) { dot = strrchr(dirent->d_name, '.'); // This ensures that .traineddata is at the end of the file name if (strncmp(dot, extension.string(), strlen(extension.string())) == 0) { *dot = '\0'; langs->push_back(STRING(dirent->d_name)); } } } } closedir(dir); } #endif } } /** * 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 TessBaseAPI::InitLangMod(const char* datapath, const char* language) { if (tesseract_ == NULL) tesseract_ = new Tesseract; else ParamUtils::ResetToDefaults(tesseract_->params()); return tesseract_->init_tesseract_lm(datapath, NULL, language); } /** * Init only for page layout analysis. Use only for calls to SetImage and * AnalysePage. Calls that attempt recognition will generate an error. */ void TessBaseAPI::InitForAnalysePage() { if (tesseract_ == NULL) { tesseract_ = new Tesseract; tesseract_->InitAdaptiveClassifier(false); } } /** * Read a "config" file containing a set of parameter name, value pairs. * Searches the standard places: tessdata/configs, tessdata/tessconfigs * and also accepts a relative or absolute path name. */ void TessBaseAPI::ReadConfigFile(const char* filename) { tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_NON_INIT_ONLY); } /** Same as above, but only set debug params from the given config file. */ void TessBaseAPI::ReadDebugConfigFile(const char* filename) { tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_DEBUG_ONLY); } /** * Set the current page segmentation mode. Defaults to PSM_AUTO. * The mode is stored as an IntParam so it can also be modified by * ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string). */ void TessBaseAPI::SetPageSegMode(PageSegMode mode) { if (tesseract_ == NULL) tesseract_ = new Tesseract; tesseract_->tessedit_pageseg_mode.set_value(mode); } /** Return the current page segmentation mode. */ PageSegMode TessBaseAPI::GetPageSegMode() const { if (tesseract_ == NULL) return PSM_SINGLE_BLOCK; return static_cast<PageSegMode>( static_cast<int>(tesseract_->tessedit_pageseg_mode)); } /** * 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 * one pixel is 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. */ char* TessBaseAPI::TesseractRect(const unsigned char* imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height) { if (tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize) return NULL; // Nothing worth doing. // Since this original api didn't give the exact size of the image, // we have to invent a reasonable value. int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8; SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top, bytes_per_pixel, bytes_per_line); SetRectangle(left, top, width, height); return GetUTF8Text(); } /** * Call between pages or documents etc to free up memory and forget * adaptive data. */ void TessBaseAPI::ClearAdaptiveClassifier() { if (tesseract_ == NULL) return; tesseract_->ResetAdaptiveClassifier(); tesseract_->ResetDocumentDictionary(); } /** * 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 TessBaseAPI::SetImage(const unsigned char* imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line) { if (InternalSetImage()) thresholder_->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line); } void TessBaseAPI::SetSourceResolution(int ppi) { if (thresholder_) thresholder_->SetSourceYResolution(ppi); else tprintf("Please call SetImage before SetSourceResolution.\n"); } /** * 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 TessBaseAPI::SetImage(Pix* pix) { if (InternalSetImage()) thresholder_->SetImage(pix); SetInputImage(pix); } /** * 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 TessBaseAPI::SetRectangle(int left, int top, int width, int height) { if (thresholder_ == NULL) return; thresholder_->SetRectangle(left, top, width, height); ClearResults(); } /** * ONLY available after SetImage if you have Leptonica installed. * Get a copy of the internal thresholded image from Tesseract. */ Pix* TessBaseAPI::GetThresholdedImage() { if (tesseract_ == NULL || thresholder_ == NULL) return NULL; if (tesseract_->pix_binary() == NULL) Threshold(tesseract_->mutable_pix_binary()); return pixClone(tesseract_->pix_binary()); } /** * 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* TessBaseAPI::GetRegions(Pixa** pixa) { return GetComponentImages(RIL_BLOCK, false, pixa, NULL); } /** * Get the textlines as a leptonica-style Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. * If blockids is not NULL, the block-id of each line is also returned as an * array of one element per line. delete [] after use. * If paraids is not NULL, the paragraph-id of each line within its block is * also returned as an array of one element per line. delete [] after use. */ Boxa* TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding, Pixa** pixa, int** blockids, int** paraids) { return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding, pixa, blockids, paraids); } /** * 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* TessBaseAPI::GetStrips(Pixa** pixa, int** blockids) { return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids); } /** * Get the words as a leptonica-style * Boxa, Pixa pair, in reading order. * Can be called before or after Recognize. */ Boxa* TessBaseAPI::GetWords(Pixa** pixa) { return GetComponentImages(RIL_WORD, true, pixa, NULL); } /** * 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. */ Boxa* TessBaseAPI::GetConnectedComponents(Pixa** pixa) { return GetComponentImages(RIL_SYMBOL, true, pixa, NULL); } /** * 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* TessBaseAPI::GetComponentImages(PageIteratorLevel level, bool text_only, bool raw_image, const int raw_padding, Pixa** pixa, int** blockids, int** paraids) { PageIterator* page_it = GetIterator(); if (page_it == NULL) page_it = AnalyseLayout(); if (page_it == NULL) return NULL; // Failed. // Count the components to get a size for the arrays. int component_count = 0; int left, top, right, bottom; TessResultCallback<bool>* get_bbox = NULL; if (raw_image) { // Get bounding box in original raw image with padding. get_bbox = NewPermanentTessCallback(page_it, &PageIterator::BoundingBox, level, raw_padding, &left, &top, &right, &bottom); } else { // Get bounding box from binarized imaged. Note that this could be // differently scaled from the original image. get_bbox = NewPermanentTessCallback(page_it, &PageIterator::BoundingBoxInternal, level, &left, &top, &right, &bottom); } do { if (get_bbox->Run() && (!text_only || PTIsTextType(page_it->BlockType()))) ++component_count; } while (page_it->Next(level)); Boxa* boxa = boxaCreate(component_count); if (pixa != NULL) *pixa = pixaCreate(component_count); if (blockids != NULL) *blockids = new int[component_count]; if (paraids != NULL) *paraids = new int[component_count]; int blockid = 0; int paraid = 0; int component_index = 0; page_it->Begin(); do { if (get_bbox->Run() && (!text_only || PTIsTextType(page_it->BlockType()))) { Box* lbox = boxCreate(left, top, right - left, bottom - top); boxaAddBox(boxa, lbox, L_INSERT); if (pixa != NULL) { Pix* pix = NULL; if (raw_image) { pix = page_it->GetImage(level, raw_padding, input_image_, &left, &top); } else { pix = page_it->GetBinaryImage(level); } pixaAddPix(*pixa, pix, L_INSERT); pixaAddBox(*pixa, lbox, L_CLONE); } if (paraids != NULL) { (*paraids)[component_index] = paraid; if (page_it->IsAtFinalElement(RIL_PARA, level)) ++paraid; } if (blockids != NULL) { (*blockids)[component_index] = blockid; if (page_it->IsAtFinalElement(RIL_BLOCK, level)) { ++blockid; paraid = 0; } } ++component_index; } } while (page_it->Next(level)); delete page_it; delete get_bbox; return boxa; } int TessBaseAPI::GetThresholdedImageScaleFactor() const { if (thresholder_ == NULL) { return 0; } return thresholder_->GetScaleFactor(); } /** Dump the internal binary image to a PGM file. */ void TessBaseAPI::DumpPGM(const char* filename) { if (tesseract_ == NULL) return; FILE *fp = fopen(filename, "wb"); Pix* pix = tesseract_->pix_binary(); int width = pixGetWidth(pix); int height = pixGetHeight(pix); l_uint32* data = pixGetData(pix); fprintf(fp, "P5 %d %d 255\n", width, height); for (int y = 0; y < height; ++y, data += pixGetWpl(pix)) { for (int x = 0; x < width; ++x) { uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255; fwrite(&b, 1, 1, fp); } } fclose(fp); } /** * Placeholder for call to Cube and test that the input data is correct. * reskew is the direction of baselines in the skewed image in * normalized (cos theta, sin theta) form, so (0.866, 0.5) would represent * a 30 degree anticlockwise skew. */ int CubeAPITest(Boxa* boxa_blocks, Pixa* pixa_blocks, Boxa* boxa_words, Pixa* pixa_words, const FCOORD& reskew, Pix* page_pix, PAGE_RES* page_res) { int block_count = boxaGetCount(boxa_blocks); ASSERT_HOST(block_count == pixaGetCount(pixa_blocks)); // Write each block to the current directory as junk_write_display.nnn.png. for (int i = 0; i < block_count; ++i) { Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE); pixDisplayWrite(pix, 1); } int word_count = boxaGetCount(boxa_words); ASSERT_HOST(word_count == pixaGetCount(pixa_words)); int pr_word = 0; PAGE_RES_IT page_res_it(page_res); for (page_res_it.restart_page(); page_res_it.word () != NULL; page_res_it.forward(), ++pr_word) { WERD_RES *word = page_res_it.word(); WERD_CHOICE* choice = word->best_choice; // Write the first 100 words to files names wordims/<wordstring>.tif. if (pr_word < 100) { STRING filename("wordims/"); if (choice != NULL) { filename += choice->unichar_string(); } else { char numbuf[32]; filename += "unclassified"; snprintf(numbuf, 32, "%03d", pr_word); filename += numbuf; } filename += ".tif"; Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE); pixWrite(filename.string(), pix, IFF_TIFF_G4); } } ASSERT_HOST(pr_word == word_count); return 0; } /** * 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. * If merge_similar_words is true, words are combined where suitable for use * with a line recognizer. Use if you want to use AnalyseLayout to find the * textlines, and then want to process textline fragments with an external * line recognizer. * Returns NULL on error or an empty page. * The returned iterator must be deleted after use. * WARNING! This class points to data held within the TessBaseAPI class, and * therefore can only be used while the TessBaseAPI class still exists and * has not been subjected to a call of Init, SetImage, Recognize, Clear, End * DetectOS, or anything else that changes the internal PAGE_RES. */ PageIterator* TessBaseAPI::AnalyseLayout(bool merge_similar_words) { if (FindLines() == 0) { if (block_list_->empty()) return NULL; // The page was empty. page_res_ = new PAGE_RES(merge_similar_words, block_list_, NULL); DetectParagraphs(false); return new PageIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } return NULL; } /** * Recognize the tesseract global image and return the result as Tesseract * internal structures. */ int TessBaseAPI::Recognize(ETEXT_DESC* monitor) { if (tesseract_ == NULL) return -1; if (FindLines() != 0) return -1; if (page_res_ != NULL) delete page_res_; if (block_list_->empty()) { page_res_ = new PAGE_RES(false, block_list_, &tesseract_->prev_word_best_choice_); return 0; // Empty page. } tesseract_->SetBlackAndWhitelist(); recognition_done_ = true; if (tesseract_->tessedit_resegment_from_line_boxes) { page_res_ = tesseract_->ApplyBoxes(*input_file_, true, block_list_); } else if (tesseract_->tessedit_resegment_from_boxes) { page_res_ = tesseract_->ApplyBoxes(*input_file_, false, block_list_); } else { // TODO(rays) LSTM here. page_res_ = new PAGE_RES(false, block_list_, &tesseract_->prev_word_best_choice_); } if (tesseract_->tessedit_make_boxes_from_boxes) { tesseract_->CorrectClassifyWords(page_res_); return 0; } if (truth_cb_ != NULL) { tesseract_->wordrec_run_blamer.set_value(true); PageIterator *page_it = new PageIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); truth_cb_->Run(tesseract_->getDict().getUnicharset(), image_height_, page_it, this->tesseract()->pix_grey()); delete page_it; } int result = 0; if (tesseract_->interactive_display_mode) { #ifndef GRAPHICS_DISABLED tesseract_->pgeditor_main(rect_width_, rect_height_, page_res_); #endif // GRAPHICS_DISABLED // The page_res is invalid after an interactive session, so cleanup // in a way that lets us continue to the next page without crashing. delete page_res_; page_res_ = NULL; return -1; } else if (tesseract_->tessedit_train_from_boxes) { tesseract_->ApplyBoxTraining(*output_file_, page_res_); } else if (tesseract_->tessedit_ambigs_training) { FILE *training_output_file = tesseract_->init_recog_training(*input_file_); // OCR the page segmented into words by tesseract. tesseract_->recog_training_segmented( *input_file_, page_res_, monitor, training_output_file); fclose(training_output_file); } else { // Now run the main recognition. bool wait_for_text = true; GetBoolVariable("paragraph_text_based", &wait_for_text); if (!wait_for_text) DetectParagraphs(false); if (tesseract_->recog_all_words(page_res_, monitor, NULL, NULL, 0)) { if (wait_for_text) DetectParagraphs(true); } else { result = -1; } } return result; } /** Tests the chopper by exhaustively running chop_one_blob. */ int TessBaseAPI::RecognizeForChopTest(ETEXT_DESC* monitor) { if (tesseract_ == NULL) return -1; if (thresholder_ == NULL || thresholder_->IsEmpty()) { tprintf("Please call SetImage before attempting recognition."); return -1; } if (page_res_ != NULL) ClearResults(); if (FindLines() != 0) return -1; // Additional conditions under which chopper test cannot be run if (tesseract_->interactive_display_mode) return -1; recognition_done_ = true; page_res_ = new PAGE_RES(false, block_list_, &(tesseract_->prev_word_best_choice_)); PAGE_RES_IT page_res_it(page_res_); while (page_res_it.word() != NULL) { WERD_RES *word_res = page_res_it.word(); GenericVector<TBOX> boxes; tesseract_->MaximallyChopWord(boxes, page_res_it.block()->block, page_res_it.row()->row, word_res); page_res_it.forward(); } return 0; } void TessBaseAPI::SetInputImage(Pix *pix) { if (input_image_) pixDestroy(&input_image_); input_image_ = NULL; if (pix) input_image_ = pixCopy(NULL, pix); } Pix* TessBaseAPI::GetInputImage() { return input_image_; } const char * TessBaseAPI::GetInputName() { if (input_file_) return input_file_->c_str(); return NULL; } const char * TessBaseAPI::GetDatapath() { return tesseract_->datadir.c_str(); } int TessBaseAPI::GetSourceYResolution() { return thresholder_->GetSourceYResolution(); } // If flist exists, get data from there. Otherwise get data from buf. // Seems convoluted, but is the easiest way I know of to meet multiple // goals. Support streaming from stdin, and also work on platforms // lacking fmemopen. bool TessBaseAPI::ProcessPagesFileList(FILE *flist, STRING *buf, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer, int tessedit_page_number) { if (!flist && !buf) return false; int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; char pagename[MAX_PATH]; GenericVector<STRING> lines; if (!flist) { buf->split('\n', &lines); if (lines.empty()) return false; } // Skip to the requested page number. for (int i = 0; i < page; i++) { if (flist) { if (fgets(pagename, sizeof(pagename), flist) == NULL) break; } } // Begin producing output const char* kUnknownTitle = ""; if (renderer && !renderer->BeginDocument(kUnknownTitle)) { return false; } // Loop over all pages - or just the requested one while (true) { if (flist) { if (fgets(pagename, sizeof(pagename), flist) == NULL) break; } else { if (page >= lines.size()) break; snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str()); } chomp_string(pagename); Pix *pix = pixRead(pagename); if (pix == NULL) { tprintf("Image file %s cannot be read!\n", pagename); return false; } tprintf("Page %d : %s\n", page, pagename); bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer); pixDestroy(&pix); if (!r) return false; if (tessedit_page_number >= 0) break; ++page; } // Finish producing output if (renderer && !renderer->EndDocument()) { return false; } return true; } bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data, size_t size, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer, int tessedit_page_number) { Pix *pix = NULL; #ifdef USE_OPENCL OpenclDevice od; #endif int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0; for (; ; ++page) { if (tessedit_page_number >= 0) page = tessedit_page_number; #ifdef USE_OPENCL if ( od.selectedDeviceIsOpenCL() ) { // FIXME(jbreiden) Not implemented. pix = od.pixReadMemTiffCl(data, size, page); } else { #endif pix = pixReadMemTiff(data, size, page); #ifdef USE_OPENCL } #endif if (pix == NULL) break; tprintf("Page %d\n", page + 1); char page_str[kMaxIntSize]; snprintf(page_str, kMaxIntSize - 1, "%d", page); SetVariable("applybox_page", page_str); bool r = ProcessPage(pix, page, filename, retry_config, timeout_millisec, renderer); pixDestroy(&pix); if (!r) return false; if (tessedit_page_number >= 0) break; } return true; } // In the ideal scenario, Tesseract will start working on data as soon // as it can. For example, if you steam a filelist through stdin, we // should start the OCR process as soon as the first filename is // available. This is particularly useful when hooking Tesseract up to // slow hardware such as a book scanning machine. // // Unfortunately there are tradeoffs. You can't seek on stdin. That // makes automatic detection of datatype (TIFF? filelist? PNG?) // impractical. So we support a command line flag to explicitly // identify the scenario that really matters: filelists on // stdin. We'll still do our best if the user likes pipes. That means // piling up any data coming into stdin into a memory buffer. bool TessBaseAPI::ProcessPages(const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer) { PERF_COUNT_START("ProcessPages") bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-"); if (stdInput) { #ifdef WIN32 if (_setmode(_fileno(stdin), _O_BINARY) == -1) tprintf("ERROR: cin to binary: %s", strerror(errno)); #endif // WIN32 } if (stream_filelist) { return ProcessPagesFileList(stdin, NULL, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number); } // At this point we are officially in autodection territory. // That means we are going to buffer stdin so that it is // seekable. To keep code simple we will also buffer data // coming from a file. std::string buf; if (stdInput) { buf.assign((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>())); } else { std::ifstream ifs(filename, std::ios::binary); if (ifs) { buf.assign((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); } else { tprintf("ERROR: Can not open input file %s\n", filename); return false; } } // Here is our autodetection int format; const l_uint8 * data = reinterpret_cast<const l_uint8 *>(buf.c_str()); findFileFormatBuffer(data, &format); // Maybe we have a filelist if (format == IFF_UNKNOWN) { STRING s(buf.c_str()); return ProcessPagesFileList(NULL, &s, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number); } // Maybe we have a TIFF which is potentially multipage bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS || format == IFF_TIFF_RLE || format == IFF_TIFF_G3 || format == IFF_TIFF_G4 || format == IFF_TIFF_LZW || format == IFF_TIFF_ZIP); // Fail early if we can, before producing any output Pix *pix = NULL; if (!tiff) { pix = pixReadMem(data, buf.size()); if (pix == NULL) { return false; } } // Begin the output const char* kUnknownTitle = ""; if (renderer && !renderer->BeginDocument(kUnknownTitle)) { pixDestroy(&pix); return false; } // Produce output bool r = false; if (tiff) { r = ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config, timeout_millisec, renderer, tesseract_->tessedit_page_number); } else { r = ProcessPage(pix, 0, filename, retry_config, timeout_millisec, renderer); pixDestroy(&pix); } // End the output if (!r || (renderer && !renderer->EndDocument())) { return false; } PERF_COUNT_END return true; } bool TessBaseAPI::ProcessPage(Pix* pix, int page_index, const char* filename, const char* retry_config, int timeout_millisec, TessResultRenderer* renderer) { PERF_COUNT_START("ProcessPage") SetInputName(filename); SetImage(pix); bool failed = false; if (timeout_millisec > 0) { // Running with a timeout. ETEXT_DESC monitor; monitor.cancel = NULL; monitor.cancel_this = NULL; monitor.set_deadline_msecs(timeout_millisec); // Now run the main recognition. failed = Recognize(&monitor) < 0; } else if (tesseract_->tessedit_pageseg_mode == PSM_OSD_ONLY || tesseract_->tessedit_pageseg_mode == PSM_AUTO_ONLY) { // Disabled character recognition. PageIterator* it = AnalyseLayout(); if (it == NULL) { failed = true; } else { delete it; PERF_COUNT_END return true; } } else { // Normal layout and character recognition with no timeout. failed = Recognize(NULL) < 0; } if (tesseract_->tessedit_write_images) { Pix* page_pix = GetThresholdedImage(); pixWrite("tessinput.tif", page_pix, IFF_TIFF_G4); } if (failed && retry_config != NULL && retry_config[0] != '\0') { // Save current config variables before switching modes. FILE* fp = fopen(kOldVarsFile, "wb"); PrintVariables(fp); fclose(fp); // Switch to alternate mode for retry. ReadConfigFile(retry_config); SetImage(pix); Recognize(NULL); // Restore saved config variables. ReadConfigFile(kOldVarsFile); } if (renderer && !failed) { failed = !renderer->AddImage(this); } PERF_COUNT_END return !failed; } /** * Get a left-to-right iterator to the results of LayoutAnalysis and/or * Recognize. The returned iterator must be deleted after use. */ LTRResultIterator* TessBaseAPI::GetLTRIterator() { if (tesseract_ == NULL || page_res_ == NULL) return NULL; return new LTRResultIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** * 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* TessBaseAPI::GetIterator() { if (tesseract_ == NULL || page_res_ == NULL) return NULL; return ResultIterator::StartOfParagraph(LTRResultIterator( page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_)); } /** * 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* TessBaseAPI::GetMutableIterator() { if (tesseract_ == NULL || page_res_ == NULL) return NULL; return new MutableIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(), rect_left_, rect_top_, rect_width_, rect_height_); } /** Make a text string from the internal data structures. */ char* TessBaseAPI::GetUTF8Text() { if (tesseract_ == NULL || (!recognition_done_ && Recognize(NULL) < 0)) return NULL; STRING text(""); ResultIterator *it = GetIterator(); do { if (it->Empty(RIL_PARA)) continue; char *para_text = it->GetUTF8Text(RIL_PARA); text += para_text; delete []para_text; } while (it->Next(RIL_PARA)); char* result = new char[text.length() + 1]; strncpy(result, text.string(), text.length() + 1); delete it; return result; } /** * Gets the block orientation at the current iterator position. */ static tesseract::Orientation GetBlockTextOrientation(const PageIterator *it) { tesseract::Orientation orientation; tesseract::WritingDirection writing_direction; tesseract::TextlineOrder textline_order; float deskew_angle; it->Orientation(&orientation, &writing_direction, &textline_order, &deskew_angle); return orientation; } /** * Fits a line to the baseline at the given level, and appends its coefficients * to the hOCR string. * NOTE: The hOCR spec is unclear on how to specify baseline coefficients for * rotated textlines. For this reason, on textlines that are not upright, this * method currently only inserts a 'textangle' property to indicate the rotation * direction and does not add any baseline information to the hocr string. */ static void AddBaselineCoordsTohOCR(const PageIterator *it, PageIteratorLevel level, STRING* hocr_str) { tesseract::Orientation orientation = GetBlockTextOrientation(it); if (orientation != ORIENTATION_PAGE_UP) { hocr_str->add_str_int("; textangle ", 360 - orientation * 90); return; } int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); // Try to get the baseline coordinates at this level. int x1, y1, x2, y2; if (!it->Baseline(level, &x1, &y1, &x2, &y2)) return; // Following the description of this field of the hOCR spec, we convert the // baseline coordinates so that "the bottom left of the bounding box is the // origin". x1 -= left; x2 -= left; y1 -= bottom; y2 -= bottom; // Now fit a line through the points so we can extract coefficients for the // equation: y = p1 x + p0 double p1 = 0; double p0 = 0; if (x1 == x2) { // Problem computing the polynomial coefficients. return; } p1 = (y2 - y1) / static_cast<double>(x2 - x1); p0 = y1 - static_cast<double>(p1 * x1); hocr_str->add_str_double("; baseline ", round(p1 * 1000.0) / 1000.0); hocr_str->add_str_double(" ", round(p0 * 1000.0) / 1000.0); } static void AddBoxTohOCR(const PageIterator *it, PageIteratorLevel level, STRING* hocr_str) { int left, top, right, bottom; it->BoundingBox(level, &left, &top, &right, &bottom); hocr_str->add_str_int("' title=\"bbox ", left); hocr_str->add_str_int(" ", top); hocr_str->add_str_int(" ", right); hocr_str->add_str_int(" ", bottom); // Add baseline coordinates for textlines only. if (level == RIL_TEXTLINE) AddBaselineCoordsTohOCR(it, level, hocr_str); *hocr_str += "\">"; } /** * 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. * Image name/input_file_ can be set by SetInputName before calling * GetHOCRText * STL removed from original patch submission and refactored by rays. */ char* TessBaseAPI::GetHOCRText(int page_number) { if (tesseract_ == NULL || (page_res_ == NULL && Recognize(NULL) < 0)) return NULL; int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; int page_id = page_number + 1; // hOCR uses 1-based page numbers. bool font_info = false; GetBoolVariable("hocr_font_info", &font_info); STRING hocr_str(""); if (input_file_ == NULL) SetInputName(NULL); #ifdef _WIN32 // convert input name from ANSI encoding to utf-8 int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, NULL, NULL); wchar_t *uni16_str = new WCHAR[str16_len]; str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, uni16_str, str16_len); int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, NULL, NULL, NULL); char *utf8_str = new char[utf8_len]; WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str, utf8_len, NULL, NULL); *input_file_ = utf8_str; delete[] uni16_str; delete[] utf8_str; #endif hocr_str.add_str_int(" <div class='ocr_page' id='page_", page_id); hocr_str += "' title='image \""; if (input_file_) { hocr_str += HOcrEscape(input_file_->string()); } else { hocr_str += "unknown"; } hocr_str.add_str_int("\"; bbox ", rect_left_); hocr_str.add_str_int(" ", rect_top_); hocr_str.add_str_int(" ", rect_width_); hocr_str.add_str_int(" ", rect_height_); hocr_str.add_str_int("; ppageno ", page_number); hocr_str += "'>\n"; ResultIterator *res_it = GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Open any new block/paragraph/textline. if (res_it->IsAtBeginningOf(RIL_BLOCK)) { hocr_str.add_str_int(" <div class='ocr_carea' id='block_", page_id); hocr_str.add_str_int("_", bcnt); AddBoxTohOCR(res_it, RIL_BLOCK, &hocr_str); } if (res_it->IsAtBeginningOf(RIL_PARA)) { if (res_it->ParagraphIsLtr()) { hocr_str.add_str_int("\n <p class='ocr_par' dir='ltr' id='par_", page_id); hocr_str.add_str_int("_", pcnt); } else { hocr_str.add_str_int("\n <p class='ocr_par' dir='rtl' id='par_", page_id); hocr_str.add_str_int("_", pcnt); } AddBoxTohOCR(res_it, RIL_PARA, &hocr_str); } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { hocr_str.add_str_int("\n <span class='ocr_line' id='line_", page_id); hocr_str.add_str_int("_", lcnt); AddBoxTohOCR(res_it, RIL_TEXTLINE, &hocr_str); } // Now, process the word... hocr_str.add_str_int("<span class='ocrx_word' id='word_", page_id); hocr_str.add_str_int("_", wcnt); int left, top, right, bottom; bool bold, italic, underlined, monospace, serif, smallcaps; int pointsize, font_id; const char *font_name; res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom); font_name = res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps, &pointsize, &font_id); hocr_str.add_str_int("' title='bbox ", left); hocr_str.add_str_int(" ", top); hocr_str.add_str_int(" ", right); hocr_str.add_str_int(" ", bottom); hocr_str.add_str_int("; x_wconf ", res_it->Confidence(RIL_WORD)); if (font_info) { hocr_str += "; x_font "; hocr_str += HOcrEscape(font_name); hocr_str.add_str_int("; x_fsize ", pointsize); } hocr_str += "'"; if (res_it->WordRecognitionLanguage()) { hocr_str += " lang='"; hocr_str += res_it->WordRecognitionLanguage(); hocr_str += "'"; } switch (res_it->WordDirection()) { case DIR_LEFT_TO_RIGHT: hocr_str += " dir='ltr'"; break; case DIR_RIGHT_TO_LEFT: hocr_str += " dir='rtl'"; break; default: // Do nothing. break; } hocr_str += ">"; bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD); bool last_word_in_para = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD); bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD); if (bold) hocr_str += "<strong>"; if (italic) hocr_str += "<em>"; do { const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL); if (grapheme && grapheme[0] != 0) { if (grapheme[1] == 0) { hocr_str += HOcrEscape(grapheme); } else { hocr_str += grapheme; } } delete []grapheme; res_it->Next(RIL_SYMBOL); } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD)); if (italic) hocr_str += "</em>"; if (bold) hocr_str += "</strong>"; hocr_str += "</span> "; wcnt++; // Close any ending block/paragraph/textline. if (last_word_in_line) { hocr_str += "\n </span>"; lcnt++; } if (last_word_in_para) { hocr_str += "\n </p>\n"; pcnt++; } if (last_word_in_block) { hocr_str += " </div>\n"; bcnt++; } } hocr_str += " </div>\n"; char *ret = new char[hocr_str.length() + 1]; strcpy(ret, hocr_str.string()); delete res_it; return ret; } /** The 5 numbers output for each box (the usual 4 and a page number.) */ const int kNumbersPerBlob = 5; /** * The number of bytes taken by each number. Since we use inT16 for ICOORD, * assume only 5 digits max. */ const int kBytesPerNumber = 5; /** * Multiplier for max expected textlength assumes (kBytesPerNumber + space) * * kNumbersPerBlob plus the newline. Add to this the * original UTF8 characters, and one kMaxBytesPerLine for safety. */ const int kBytesPerBlob = kNumbersPerBlob * (kBytesPerNumber + 1) + 1; const int kBytesPerBoxFileLine = (kBytesPerNumber + 1) * kNumbersPerBlob + 1; /** Max bytes in the decimal representation of inT64. */ const int kBytesPer64BitNumber = 20; /** * A maximal single box could occupy kNumbersPerBlob numbers at * kBytesPer64BitNumber digits (if someone sneaks in a 64 bit value) and a * space plus the newline and the maximum length of a UNICHAR. * Test against this on each iteration for safety. */ const int kMaxBytesPerLine = kNumbersPerBlob * (kBytesPer64BitNumber + 1) + 1 + UNICHAR_LEN; /** * The recognized text is returned as a char* which is coded * as a UTF8 box file and must be freed with the delete [] operator. * page_number is a 0-base page index that will appear in the box file. */ char* TessBaseAPI::GetBoxText(int page_number) { if (tesseract_ == NULL || (!recognition_done_ && Recognize(NULL) < 0)) return NULL; int blob_count; int utf8_length = TextLength(&blob_count); int total_length = blob_count * kBytesPerBoxFileLine + utf8_length + kMaxBytesPerLine; char* result = new char[total_length]; strcpy(result, "\0"); int output_length = 0; LTRResultIterator* it = GetLTRIterator(); do { int left, top, right, bottom; if (it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom)) { char* text = it->GetUTF8Text(RIL_SYMBOL); // Tesseract uses space for recognition failure. Fix to a reject // character, kTesseractReject so we don't create illegal box files. for (int i = 0; text[i] != '\0'; ++i) { if (text[i] == ' ') text[i] = kTesseractReject; } snprintf(result + output_length, total_length - output_length, "%s %d %d %d %d %d\n", text, left, image_height_ - bottom, right, image_height_ - top, page_number); output_length += strlen(result + output_length); delete [] text; // Just in case... if (output_length + kMaxBytesPerLine > total_length) break; } } while (it->Next(RIL_SYMBOL)); delete it; return result; } /** * Conversion table for non-latin characters. * Maps characters out of the latin set into the latin set. * TODO(rays) incorporate this translation into unicharset. */ const int kUniChs[] = { 0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0 }; /** Latin chars corresponding to the unicode chars above. */ const int kLatinChs[] = { 0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0 }; /** * 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* TessBaseAPI::GetUNLVText() { if (tesseract_ == NULL || (!recognition_done_ && Recognize(NULL) < 0)) return NULL; bool tilde_crunch_written = false; bool last_char_was_newline = true; bool last_char_was_tilde = false; int total_length = TextLength(NULL); PAGE_RES_IT page_res_it(page_res_); char* result = new char[total_length]; char* ptr = result; for (page_res_it.restart_page(); page_res_it.word () != NULL; page_res_it.forward()) { WERD_RES *word = page_res_it.word(); // Process the current word. if (word->unlv_crunch_mode != CR_NONE) { if (word->unlv_crunch_mode != CR_DELETE && (!tilde_crunch_written || (word->unlv_crunch_mode == CR_KEEP_SPACE && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)))) { if (!word->word->flag(W_BOL) && word->word->space() > 0 && !word->word->flag(W_FUZZY_NON) && !word->word->flag(W_FUZZY_SP)) { /* Write a space to separate from preceeding good text */ *ptr++ = ' '; last_char_was_tilde = false; } if (!last_char_was_tilde) { // Write a reject char. last_char_was_tilde = true; *ptr++ = kUNLVReject; tilde_crunch_written = true; last_char_was_newline = false; } } } else { // NORMAL PROCESSING of non tilde crunched words. tilde_crunch_written = false; tesseract_->set_unlv_suspects(word); const char* wordstr = word->best_choice->unichar_string().string(); const STRING& lengths = word->best_choice->unichar_lengths(); int length = lengths.length(); int i = 0; int offset = 0; if (last_char_was_tilde && word->word->space() == 0 && wordstr[offset] == ' ') { // Prevent adjacent tilde across words - we know that adjacent tildes // within words have been removed. // Skip the first character. offset = lengths[i++]; } if (i < length && wordstr[offset] != 0) { if (!last_char_was_newline) *ptr++ = ' '; else last_char_was_newline = false; for (; i < length; offset += lengths[i++]) { if (wordstr[offset] == ' ' || wordstr[offset] == kTesseractReject) { *ptr++ = kUNLVReject; last_char_was_tilde = true; } else { if (word->reject_map[i].rejected()) *ptr++ = kUNLVSuspect; UNICHAR ch(wordstr + offset, lengths[i]); int uni_ch = ch.first_uni(); for (int j = 0; kUniChs[j] != 0; ++j) { if (kUniChs[j] == uni_ch) { uni_ch = kLatinChs[j]; break; } } if (uni_ch <= 0xff) { *ptr++ = static_cast<char>(uni_ch); last_char_was_tilde = false; } else { *ptr++ = kUNLVReject; last_char_was_tilde = true; } } } } } if (word->word->flag(W_EOL) && !last_char_was_newline) { /* Add a new line output */ *ptr++ = '\n'; tilde_crunch_written = false; last_char_was_newline = true; last_char_was_tilde = false; } } *ptr++ = '\n'; *ptr = '\0'; return result; } /** Returns the average word confidence for Tesseract page result. */ int TessBaseAPI::MeanTextConf() { int* conf = AllWordConfidences(); if (!conf) return 0; int sum = 0; int *pt = conf; while (*pt >= 0) sum += *pt++; if (pt != conf) sum /= pt - conf; delete [] conf; return sum; } /** Returns an array of all word confidences, terminated by -1. */ int* TessBaseAPI::AllWordConfidences() { if (tesseract_ == NULL || (!recognition_done_ && Recognize(NULL) < 0)) return NULL; int n_word = 0; PAGE_RES_IT res_it(page_res_); for (res_it.restart_page(); res_it.word() != NULL; res_it.forward()) n_word++; int* conf = new int[n_word+1]; n_word = 0; for (res_it.restart_page(); res_it.word() != NULL; res_it.forward()) { WERD_RES *word = res_it.word(); WERD_CHOICE* choice = word->best_choice; int w_conf = static_cast<int>(100 + 5 * choice->certainty()); // This is the eq for converting Tesseract confidence to 1..100 if (w_conf < 0) w_conf = 0; if (w_conf > 100) w_conf = 100; conf[n_word++] = w_conf; } conf[n_word] = -1; return conf; } /** * 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 TessBaseAPI::AdaptToWordStr(PageSegMode mode, const char* wordstr) { int debug = 0; GetIntVariable("applybox_debug", &debug); bool success = true; PageSegMode current_psm = GetPageSegMode(); SetPageSegMode(mode); SetVariable("classify_enable_learning", "0"); char* text = GetUTF8Text(); if (debug) { tprintf("Trying to adapt \"%s\" to \"%s\"\n", text, wordstr); } if (text != NULL) { PAGE_RES_IT it(page_res_); WERD_RES* word_res = it.word(); if (word_res != NULL) { word_res->word->set_text(wordstr); } else { success = false; } // Check to see if text matches wordstr. int w = 0; int t = 0; for (t = 0; text[t] != '\0'; ++t) { if (text[t] == '\n' || text[t] == ' ') continue; while (wordstr[w] != '\0' && wordstr[w] == ' ') ++w; if (text[t] != wordstr[w]) break; ++w; } if (text[t] != '\0' || wordstr[w] != '\0') { // No match. delete page_res_; GenericVector<TBOX> boxes; page_res_ = tesseract_->SetupApplyBoxes(boxes, block_list_); tesseract_->ReSegmentByClassification(page_res_); tesseract_->TidyUp(page_res_); PAGE_RES_IT pr_it(page_res_); if (pr_it.word() == NULL) success = false; else word_res = pr_it.word(); } else { word_res->BestChoiceToCorrectText(); } if (success) { tesseract_->EnableLearning = true; tesseract_->LearnWord(NULL, word_res); } delete [] text; } else { success = false; } SetPageSegMode(current_psm); return success; } /** * 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 TessBaseAPI::Clear() { if (thresholder_ != NULL) thresholder_->Clear(); ClearResults(); SetInputImage(NULL); } /** * 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 TessBaseAPI::End() { if (thresholder_ != NULL) { delete thresholder_; thresholder_ = NULL; } if (page_res_ != NULL) { delete page_res_; page_res_ = NULL; } if (block_list_ != NULL) { delete block_list_; block_list_ = NULL; } if (paragraph_models_ != NULL) { paragraph_models_->delete_data_pointers(); delete paragraph_models_; paragraph_models_ = NULL; } if (tesseract_ != NULL) { delete tesseract_; if (osd_tesseract_ == tesseract_) osd_tesseract_ = NULL; tesseract_ = NULL; } if (osd_tesseract_ != NULL) { delete osd_tesseract_; osd_tesseract_ = NULL; } if (equ_detect_ != NULL) { delete equ_detect_; equ_detect_ = NULL; } if (input_file_ != NULL) { delete input_file_; input_file_ = NULL; } if (input_image_ != NULL) { pixDestroy(&input_image_); input_image_ = NULL; } if (output_file_ != NULL) { delete output_file_; output_file_ = NULL; } if (datapath_ != NULL) { delete datapath_; datapath_ = NULL; } if (language_ != NULL) { delete language_; language_ = NULL; } } // Clear any library-level memory caches. // There are a variety of expensive-to-load constant data structures (mostly // language dictionaries) that are cached globally -- surviving the Init() // and End() of individual TessBaseAPI's. This function allows the clearing // of these caches. void TessBaseAPI::ClearPersistentCache() { Dict::GlobalDawgCache()->DeleteUnusedDawgs(); } /** * Check whether a word is valid according to Tesseract's language model * returns 0 if the word is invalid, non-zero if valid */ int TessBaseAPI::IsValidWord(const char *word) { return tesseract_->getDict().valid_word(word); } // Returns true if utf8_character is defined in the UniCharset. bool TessBaseAPI::IsValidCharacter(const char *utf8_character) { return tesseract_->unicharset.contains_unichar(utf8_character); } // TODO(rays) Obsolete this function and replace with a more aptly named // function that returns image coordinates rather than tesseract coordinates. bool TessBaseAPI::GetTextDirection(int* out_offset, float* out_slope) { PageIterator* it = AnalyseLayout(); if (it == NULL) { return false; } int x1, x2, y1, y2; it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2); // Calculate offset and slope (NOTE: Kind of ugly) if (x2 <= x1) x2 = x1 + 1; // Convert the point pair to slope/offset of the baseline (in image coords.) *out_slope = static_cast<float>(y2 - y1) / (x2 - x1); *out_offset = static_cast<int>(y1 - *out_slope * x1); // Get the y-coord of the baseline at the left and right edges of the // textline's bounding box. int left, top, right, bottom; if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) { delete it; return false; } int left_y = IntCastRounded(*out_slope * left + *out_offset); int right_y = IntCastRounded(*out_slope * right + *out_offset); // Shift the baseline down so it passes through the nearest bottom-corner // of the textline's bounding box. This is the difference between the y // at the lowest (max) edge of the box and the actual box bottom. *out_offset += bottom - MAX(left_y, right_y); // Switch back to bottom-up tesseract coordinates. Requires negation of // the slope and height - offset for the offset. *out_slope = -*out_slope; *out_offset = rect_height_ - *out_offset; delete it; return true; } /** Sets Dict::letter_is_okay_ function to point to the given function. */ void TessBaseAPI::SetDictFunc(DictFunc f) { if (tesseract_ != NULL) { tesseract_->getDict().letter_is_okay_ = f; } } /** * Sets Dict::probability_in_context_ function to point to the given * function. * * @param f A single function that returns the probability of the current * "character" (in general a utf-8 string), given the context of a previous * utf-8 string. */ void TessBaseAPI::SetProbabilityInContextFunc(ProbabilityInContextFunc f) { if (tesseract_ != NULL) { tesseract_->getDict().probability_in_context_ = f; // Set it for the sublangs too. int num_subs = tesseract_->num_sub_langs(); for (int i = 0; i < num_subs; ++i) { tesseract_->get_sub_lang(i)->getDict().probability_in_context_ = f; } } } /** Sets Wordrec::fill_lattice_ function to point to the given function. */ void TessBaseAPI::SetFillLatticeFunc(FillLatticeFunc f) { if (tesseract_ != NULL) tesseract_->fill_lattice_ = f; } /** Common code for setting the image. */ bool TessBaseAPI::InternalSetImage() { if (tesseract_ == NULL) { tprintf("Please call Init before attempting to set an image."); return false; } if (thresholder_ == NULL) thresholder_ = new ImageThresholder; ClearResults(); return true; } /** * Run the thresholder to make the thresholded image, returned in pix, * which must not be NULL. *pix must be initialized to NULL, or point * to an existing pixDestroyable Pix. * The usual argument to Threshold is Tesseract::mutable_pix_binary(). */ void TessBaseAPI::Threshold(Pix** pix) { ASSERT_HOST(pix != NULL); if (*pix != NULL) pixDestroy(pix); // Zero resolution messes up the algorithms, so make sure it is credible. int y_res = thresholder_->GetScaledYResolution(); if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) { // Use the minimum default resolution, as it is safer to under-estimate // than over-estimate resolution. thresholder_->SetSourceYResolution(kMinCredibleResolution); } PageSegMode pageseg_mode = static_cast<PageSegMode>( static_cast<int>(tesseract_->tessedit_pageseg_mode)); thresholder_->ThresholdToPix(pageseg_mode, pix); thresholder_->GetImageSizes(&rect_left_, &rect_top_, &rect_width_, &rect_height_, &image_width_, &image_height_); if (!thresholder_->IsBinary()) { tesseract_->set_pix_thresholds(thresholder_->GetPixRectThresholds()); tesseract_->set_pix_grey(thresholder_->GetPixRectGrey()); } else { tesseract_->set_pix_thresholds(NULL); tesseract_->set_pix_grey(NULL); } // Set the internal resolution that is used for layout parameters from the // estimated resolution, rather than the image resolution, which may be // fabricated, but we will use the image resolution, if there is one, to // report output point sizes. int estimated_res = ClipToRange(thresholder_->GetScaledEstimatedResolution(), kMinCredibleResolution, kMaxCredibleResolution); if (estimated_res != thresholder_->GetScaledEstimatedResolution()) { tprintf("Estimated resolution %d out of range! Corrected to %d\n", thresholder_->GetScaledEstimatedResolution(), estimated_res); } tesseract_->set_source_resolution(estimated_res); SavePixForCrash(estimated_res, *pix); } /** Find lines from the image making the BLOCK_LIST. */ int TessBaseAPI::FindLines() { if (thresholder_ == NULL || thresholder_->IsEmpty()) { tprintf("Please call SetImage before attempting recognition."); return -1; } if (recognition_done_) ClearResults(); if (!block_list_->empty()) { return 0; } if (tesseract_ == NULL) { tesseract_ = new Tesseract; tesseract_->InitAdaptiveClassifier(false); } if (tesseract_->pix_binary() == NULL) Threshold(tesseract_->mutable_pix_binary()); if (tesseract_->ImageWidth() > MAX_INT16 || tesseract_->ImageHeight() > MAX_INT16) { tprintf("Image too large: (%d, %d)\n", tesseract_->ImageWidth(), tesseract_->ImageHeight()); return -1; } tesseract_->PrepareForPageseg(); if (tesseract_->textord_equation_detect) { if (equ_detect_ == NULL && datapath_ != NULL) { equ_detect_ = new EquationDetect(datapath_->string(), NULL); } tesseract_->SetEquationDetect(equ_detect_); } Tesseract* osd_tess = osd_tesseract_; OSResults osr; if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == NULL) { if (strcmp(language_->string(), "osd") == 0) { osd_tess = tesseract_; } else { osd_tesseract_ = new Tesseract; if (osd_tesseract_->init_tesseract( datapath_->string(), NULL, "osd", OEM_TESSERACT_ONLY, NULL, 0, NULL, NULL, false) == 0) { osd_tess = osd_tesseract_; osd_tesseract_->set_source_resolution( thresholder_->GetSourceYResolution()); } else { tprintf("Warning: Auto orientation and script detection requested," " but osd language failed to load\n"); delete osd_tesseract_; osd_tesseract_ = NULL; } } } if (tesseract_->SegmentPage(input_file_, block_list_, osd_tess, &osr) < 0) return -1; // If Devanagari is being recognized, we use different images for page seg // and for OCR. tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr); return 0; } /** Delete the pageres and clear the block list ready for a new page. */ void TessBaseAPI::ClearResults() { if (tesseract_ != NULL) { tesseract_->Clear(); } if (page_res_ != NULL) { delete page_res_; page_res_ = NULL; } recognition_done_ = false; if (block_list_ == NULL) block_list_ = new BLOCK_LIST; else block_list_->clear(); if (paragraph_models_ != NULL) { paragraph_models_->delete_data_pointers(); delete paragraph_models_; paragraph_models_ = NULL; } SavePixForCrash(0, NULL); } /** * Return the length of the output text string, as UTF8, assuming * liberally two spacing marks after each word (as paragraphs end with two * newlines), and assuming a single character reject marker for each rejected * character. * Also return the number of recognized blobs in blob_count. */ int TessBaseAPI::TextLength(int* blob_count) { if (tesseract_ == NULL || page_res_ == NULL) return 0; PAGE_RES_IT page_res_it(page_res_); int total_length = 2; int total_blobs = 0; // Iterate over the data structures to extract the recognition result. for (page_res_it.restart_page(); page_res_it.word () != NULL; page_res_it.forward()) { WERD_RES *word = page_res_it.word(); WERD_CHOICE* choice = word->best_choice; if (choice != NULL) { total_blobs += choice->length() + 2; total_length += choice->unichar_string().length() + 2; for (int i = 0; i < word->reject_map.length(); ++i) { if (word->reject_map[i].rejected()) ++total_length; } } } if (blob_count != NULL) *blob_count = total_blobs; return total_length; } /** * Estimates the Orientation And Script of the image. * Returns true if the image was processed successfully. */ bool TessBaseAPI::DetectOS(OSResults* osr) { if (tesseract_ == NULL) return false; ClearResults(); if (tesseract_->pix_binary() == NULL) Threshold(tesseract_->mutable_pix_binary()); if (input_file_ == NULL) input_file_ = new STRING(kInputFile); return orientation_and_script_detection(*input_file_, osr, tesseract_); } void TessBaseAPI::set_min_orientation_margin(double margin) { tesseract_->min_orientation_margin.set_value(margin); } /** * Return text orientation of each block as determined in an earlier page layout * analysis operation. Orientation is returned as the number of ccw 90-degree * rotations (in [0..3]) required to make the text in the block upright * (readable). Note that this may not necessary be the block orientation * preferred for recognition (such as the case of vertical CJK text). * * Also returns whether the text in the block is believed to have vertical * writing direction (when in an upright page orientation). * * The returned array is of length equal to the number of text blocks, which may * be less than the total number of blocks. The ordering is intended to be * consistent with GetTextLines(). */ void TessBaseAPI::GetBlockTextOrientations(int** block_orientation, bool** vertical_writing) { delete[] *block_orientation; *block_orientation = NULL; delete[] *vertical_writing; *vertical_writing = NULL; BLOCK_IT block_it(block_list_); block_it.move_to_first(); int num_blocks = 0; for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { if (!block_it.data()->poly_block()->IsText()) { continue; } ++num_blocks; } if (!num_blocks) { tprintf("WARNING: Found no blocks\n"); return; } *block_orientation = new int[num_blocks]; *vertical_writing = new bool[num_blocks]; block_it.move_to_first(); int i = 0; for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { if (!block_it.data()->poly_block()->IsText()) { continue; } FCOORD re_rotation = block_it.data()->re_rotation(); float re_theta = re_rotation.angle(); FCOORD classify_rotation = block_it.data()->classify_rotation(); float classify_theta = classify_rotation.angle(); double rot_theta = - (re_theta - classify_theta) * 2.0 / PI; if (rot_theta < 0) rot_theta += 4; int num_rotations = static_cast<int>(rot_theta + 0.5); (*block_orientation)[i] = num_rotations; // The classify_rotation is non-zero only if the text has vertical // writing direction. (*vertical_writing)[i] = classify_rotation.y() != 0.0f; ++i; } } // ____________________________________________________________________________ // Ocropus add-ons. /** Find lines from the image making the BLOCK_LIST. */ BLOCK_LIST* TessBaseAPI::FindLinesCreateBlockList() { FindLines(); BLOCK_LIST* result = block_list_; block_list_ = NULL; return result; } /** * Delete a block list. * This is to keep BLOCK_LIST pointer opaque * and let go of including the other headers. */ void TessBaseAPI::DeleteBlockList(BLOCK_LIST *block_list) { delete block_list; } ROW *TessBaseAPI::MakeTessOCRRow(float baseline, float xheight, float descender, float ascender) { inT32 xstarts[] = {-32000}; double quad_coeffs[] = {0, 0, baseline}; return new ROW(1, xstarts, quad_coeffs, xheight, ascender - (baseline + xheight), descender - baseline, 0, 0); } /** Creates a TBLOB* from the whole pix. */ TBLOB *TessBaseAPI::MakeTBLOB(Pix *pix) { int width = pixGetWidth(pix); int height = pixGetHeight(pix); BLOCK block("a character", TRUE, 0, 0, 0, 0, width, height); // Create C_BLOBs from the page extract_edges(pix, &block); // Merge all C_BLOBs C_BLOB_LIST *list = block.blob_list(); C_BLOB_IT c_blob_it(list); if (c_blob_it.empty()) return NULL; // Move all the outlines to the first blob. C_OUTLINE_IT ol_it(c_blob_it.data()->out_list()); for (c_blob_it.forward(); !c_blob_it.at_first(); c_blob_it.forward()) { C_BLOB *c_blob = c_blob_it.data(); ol_it.add_list_after(c_blob->out_list()); } // Convert the first blob to the output TBLOB. return TBLOB::PolygonalCopy(false, c_blob_it.data()); } /** * 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. */ void TessBaseAPI::NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode) { TBOX box = tblob->bounding_box(); float x_center = (box.left() + box.right()) / 2.0f; float baseline = row->base_line(x_center); float scale = kBlnXHeight / row->x_height(); tblob->Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale, 0.0f, static_cast<float>(kBlnBaselineOffset), false, NULL); } /** * Return a TBLOB * from the whole pix. * To be freed later with delete. */ TBLOB *make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix* pix) { TBLOB *tblob = TessBaseAPI::MakeTBLOB(pix); // Normalize TBLOB ROW *row = TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender); TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode); delete row; return tblob; } /** * Adapt to recognize the current image as the given character. * The image must be preloaded into pix_binary_ and be just an image * of a single character. */ void TessBaseAPI::AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender) { UNICHAR_ID id = tesseract_->unicharset.unichar_to_id(unichar_repr, length); TBLOB *blob = make_tesseract_blob(baseline, xheight, descender, ascender, tesseract_->classify_bln_numeric_mode, tesseract_->pix_binary()); float threshold; float best_rating = -100; // Classify to get a raw choice. BLOB_CHOICE_LIST choices; tesseract_->AdaptiveClassifier(blob, &choices); BLOB_CHOICE_IT choice_it; choice_it.set_to_list(&choices); for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) { if (choice_it.data()->rating() > best_rating) { best_rating = choice_it.data()->rating(); } } threshold = tesseract_->matcher_good_threshold; if (blob->outlines) tesseract_->AdaptToChar(blob, id, kUnknownFontinfoId, threshold); delete blob; } PAGE_RES* TessBaseAPI::RecognitionPass1(BLOCK_LIST* block_list) { PAGE_RES *page_res = new PAGE_RES(false, block_list, &(tesseract_->prev_word_best_choice_)); tesseract_->recog_all_words(page_res, NULL, NULL, NULL, 1); return page_res; } PAGE_RES* TessBaseAPI::RecognitionPass2(BLOCK_LIST* block_list, PAGE_RES* pass1_result) { if (!pass1_result) pass1_result = new PAGE_RES(false, block_list, &(tesseract_->prev_word_best_choice_)); tesseract_->recog_all_words(pass1_result, NULL, NULL, NULL, 2); return pass1_result; } void TessBaseAPI::DetectParagraphs(bool after_text_recognition) { int debug_level = 0; GetIntVariable("paragraph_debug_level", &debug_level); if (paragraph_models_ == NULL) paragraph_models_ = new GenericVector<ParagraphModel*>; MutableIterator *result_it = GetMutableIterator(); do { // Detect paragraphs for this block GenericVector<ParagraphModel *> models; ::tesseract::DetectParagraphs(debug_level, after_text_recognition, result_it, &models); *paragraph_models_ += models; } while (result_it->Next(RIL_BLOCK)); delete result_it; } struct TESS_CHAR : ELIST_LINK { char *unicode_repr; int length; // of unicode_repr float cost; TBOX box; TESS_CHAR(float _cost, const char *repr, int len = -1) : cost(_cost) { length = (len == -1 ? strlen(repr) : len); unicode_repr = new char[length + 1]; strncpy(unicode_repr, repr, length); } TESS_CHAR() { // Satisfies ELISTIZE. } ~TESS_CHAR() { delete [] unicode_repr; } }; ELISTIZEH(TESS_CHAR) ELISTIZE(TESS_CHAR) static void add_space(TESS_CHAR_IT* it) { TESS_CHAR *t = new TESS_CHAR(0, " "); it->add_after_then_move(t); } static float rating_to_cost(float rating) { rating = 100 + rating; // cuddled that to save from coverage profiler // (I have never seen ratings worse than -100, // but the check won't hurt) if (rating < 0) rating = 0; return rating; } /** * Extract the OCR results, costs (penalty points for uncertainty), * and the bounding boxes of the characters. */ static void extract_result(TESS_CHAR_IT* out, PAGE_RES* page_res) { PAGE_RES_IT page_res_it(page_res); int word_count = 0; while (page_res_it.word() != NULL) { WERD_RES *word = page_res_it.word(); const char *str = word->best_choice->unichar_string().string(); const char *len = word->best_choice->unichar_lengths().string(); TBOX real_rect = word->word->bounding_box(); if (word_count) add_space(out); int n = strlen(len); for (int i = 0; i < n; i++) { TESS_CHAR *tc = new TESS_CHAR(rating_to_cost(word->best_choice->rating()), str, *len); tc->box = real_rect.intersection(word->box_word->BlobBox(i)); out->add_after_then_move(tc); str += *len; len++; } page_res_it.forward(); word_count++; } } /** * Extract the OCR results, costs (penalty points for uncertainty), * and the bounding boxes of the characters. */ int TessBaseAPI::TesseractExtractResult(char** text, int** lengths, float** costs, int** x0, int** y0, int** x1, int** y1, PAGE_RES* page_res) { TESS_CHAR_LIST tess_chars; TESS_CHAR_IT tess_chars_it(&tess_chars); extract_result(&tess_chars_it, page_res); tess_chars_it.move_to_first(); int n = tess_chars.length(); int text_len = 0; *lengths = new int[n]; *costs = new float[n]; *x0 = new int[n]; *y0 = new int[n]; *x1 = new int[n]; *y1 = new int[n]; int i = 0; for (tess_chars_it.mark_cycle_pt(); !tess_chars_it.cycled_list(); tess_chars_it.forward(), i++) { TESS_CHAR *tc = tess_chars_it.data(); text_len += (*lengths)[i] = tc->length; (*costs)[i] = tc->cost; (*x0)[i] = tc->box.left(); (*y0)[i] = tc->box.bottom(); (*x1)[i] = tc->box.right(); (*y1)[i] = tc->box.top(); } char *p = *text = new char[text_len]; tess_chars_it.move_to_first(); for (tess_chars_it.mark_cycle_pt(); !tess_chars_it.cycled_list(); tess_chars_it.forward()) { TESS_CHAR *tc = tess_chars_it.data(); strncpy(p, tc->unicode_repr, tc->length); p += tc->length; } return n; } /** This method returns the features associated with the input blob. */ // The resulting features are returned in int_features, which must be // of size MAX_NUM_INT_FEATURES. The number of features is returned in // num_features (or 0 if there was a failure). // On return feature_outline_index is filled with an index of the outline // corresponding to each feature in int_features. // TODO(rays) Fix the caller to out outline_counts instead. void TessBaseAPI::GetFeaturesForBlob(TBLOB* blob, INT_FEATURE_STRUCT* int_features, int* num_features, int* feature_outline_index) { GenericVector<int> outline_counts; GenericVector<INT_FEATURE_STRUCT> bl_features; GenericVector<INT_FEATURE_STRUCT> cn_features; INT_FX_RESULT_STRUCT fx_info; tesseract_->ExtractFeatures(*blob, false, &bl_features, &cn_features, &fx_info, &outline_counts); if (cn_features.size() == 0 || cn_features.size() > MAX_NUM_INT_FEATURES) { *num_features = 0; return; // Feature extraction failed. } *num_features = cn_features.size(); memcpy(int_features, &cn_features[0], *num_features * sizeof(cn_features[0])); // TODO(rays) Pass outline_counts back and simplify the calling code. if (feature_outline_index != NULL) { int f = 0; for (int i = 0; i < outline_counts.size(); ++i) { while (f < outline_counts[i]) feature_outline_index[f++] = i; } } } // This method returns the row to which a box of specified dimensions would // belong. If no good match is found, it returns NULL. ROW* TessBaseAPI::FindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom) { TBOX box(left, bottom, right, top); BLOCK_IT b_it(blocks); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { BLOCK* block = b_it.data(); if (!box.major_overlap(block->bounding_box())) continue; ROW_IT r_it(block->row_list()); for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) { ROW* row = r_it.data(); if (!box.major_overlap(row->bounding_box())) continue; WERD_IT w_it(row->word_list()); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD* word = w_it.data(); if (box.major_overlap(word->bounding_box())) return row; } } } return NULL; } /** Method to run adaptive classifier on a blob. */ void TessBaseAPI::RunAdaptiveClassifier(TBLOB* blob, int num_max_matches, int* unichar_ids, float* ratings, int* num_matches_returned) { BLOB_CHOICE_LIST* choices = new BLOB_CHOICE_LIST; tesseract_->AdaptiveClassifier(blob, choices); BLOB_CHOICE_IT choices_it(choices); int& index = *num_matches_returned; index = 0; for (choices_it.mark_cycle_pt(); !choices_it.cycled_list() && index < num_max_matches; choices_it.forward()) { BLOB_CHOICE* choice = choices_it.data(); unichar_ids[index] = choice->unichar_id(); ratings[index] = choice->rating(); ++index; } *num_matches_returned = index; delete choices; } /** This method returns the string form of the specified unichar. */ const char* TessBaseAPI::GetUnichar(int unichar_id) { return tesseract_->unicharset.id_to_unichar(unichar_id); } /** Return the pointer to the i-th dawg loaded into tesseract_ object. */ const Dawg *TessBaseAPI::GetDawg(int i) const { if (tesseract_ == NULL || i >= NumDawgs()) return NULL; return tesseract_->getDict().GetDawg(i); } /** Return the number of dawgs loaded into tesseract_ object. */ int TessBaseAPI::NumDawgs() const { return tesseract_ == NULL ? 0 : tesseract_->getDict().NumDawgs(); } /** Return a pointer to underlying CubeRecoContext object if present. */ CubeRecoContext *TessBaseAPI::GetCubeRecoContext() const { return (tesseract_ == NULL) ? NULL : tesseract_->GetCubeRecoContext(); } /** Escape a char string - remove <>&"' with HTML codes. */ STRING HOcrEscape(const char* text) { STRING ret; const char *ptr; for (ptr = text; *ptr; ptr++) { switch (*ptr) { case '<': ret += "&lt;"; break; case '>': ret += "&gt;"; break; case '&': ret += "&amp;"; break; case '"': ret += "&quot;"; break; case '\'': ret += "&#39;"; break; default: ret += *ptr; } } return ret; } } // namespace tesseract.
1080228-arabicocr11
api/baseapi.cpp
C++
asf20
89,424
/////////////////////////////////////////////////////////////////////// // File: renderer.h // Description: Rendering interface to inject into TessBaseAPI // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_API_RENDERER_H__ #define TESSERACT_API_RENDERER_H__ // To avoid collision with other typenames include the ABSOLUTE MINIMUM // complexity of includes here. Use forward declarations wherever possible // and hide includes of complex types in baseapi.cpp. #include "genericvector.h" #include "platform.h" #include "publictypes.h" namespace tesseract { class TessBaseAPI; /** * Interface for rendering tesseract results into a document, such as text, * HOCR or pdf. This class is abstract. Specific classes handle individual * formats. This interface is then used to inject the renderer class into * tesseract when processing images. * * For simplicity implementing this with tesesract version 3.01, * the renderer contains document state that is cleared from document * to document just as the TessBaseAPI is. This way the base API can just * delegate its rendering functionality to injected renderers, and the * renderers can manage the associated state needed for the specific formats * in addition to the heuristics for producing it. */ class TESS_API TessResultRenderer { public: virtual ~TessResultRenderer(); // Takes ownership of pointer so must be new'd instance. // Renderers aren't ordered, but appends the sequences of next parameter // and existing next(). The renderers should be unique across both lists. void insert(TessResultRenderer* next); // Returns the next renderer or NULL. TessResultRenderer* next() { return next_; } /** * Starts a new document with the given title. * This clears the contents of the output data. */ bool BeginDocument(const char* title); /** * Adds the recognized text from the source image to the current document. * Invalid if BeginDocument not yet called. * * Note that this API is a bit weird but is designed to fit into the * current TessBaseAPI implementation where the api has lots of state * information that we might want to add in. */ bool AddImage(TessBaseAPI* api); /** * Finishes the document and finalizes the output data * Invalid if BeginDocument not yet called. */ bool EndDocument(); const char* file_extension() const { return file_extension_; } const char* title() const { return title_; } /** * Returns the index of the last image given to AddImage * (i.e. images are incremented whether the image succeeded or not) * * This is always defined. It means either the number of the * current image, the last image ended, or in the completed document * depending on when in the document lifecycle you are looking at it. * Will return -1 if a document was never started. */ int imagenum() const { return imagenum_; } protected: /** * Called by concrete classes. * * outputbase is the name of the output file excluding * extension. For example, "/path/to/chocolate-chip-cookie-recipe" * * extension indicates the file extension to be used for output * files. For example "pdf" will produce a .pdf file, and "hocr" * will produce .hocr files. */ TessResultRenderer(const char *outputbase, const char* extension); // Hook for specialized handling in BeginDocument() virtual bool BeginDocumentHandler(); // This must be overriden to render the OCR'd results virtual bool AddImageHandler(TessBaseAPI* api) = 0; // Hook for specialized handling in EndDocument() virtual bool EndDocumentHandler(); // Renderers can call this to append '\0' terminated strings into // the output string returned by GetOutput. // This method will grow the output buffer if needed. void AppendString(const char* s); // Renderers can call this to append binary byte sequences into // the output string returned by GetOutput. Note that s is not necessarily // '\0' terminated (and can contain '\0' within it). // This method will grow the output buffer if needed. void AppendData(const char* s, int len); private: const char* file_extension_; // standard extension for generated output const char* title_; // title of document being renderered int imagenum_; // index of last image added FILE* fout_; // output file pointer TessResultRenderer* next_; // Can link multiple renderers together bool happy_; // I get grumpy when the disk fills up, etc. }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessTextRenderer : public TessResultRenderer { public: explicit TessTextRenderer(const char *outputbase); protected: virtual bool AddImageHandler(TessBaseAPI* api); }; /** * Renders tesseract output into an hocr text string */ class TESS_API TessHOcrRenderer : public TessResultRenderer { public: explicit TessHOcrRenderer(const char *outputbase, bool font_info); explicit TessHOcrRenderer(const char *outputbase); protected: virtual bool BeginDocumentHandler(); virtual bool AddImageHandler(TessBaseAPI* api); virtual bool EndDocumentHandler(); private: bool font_info_; // whether to print font information }; /** * Renders tesseract output into searchable PDF */ class TESS_API TessPDFRenderer : public TessResultRenderer { public: // datadir is the location of the TESSDATA. We need it because // we load a custom PDF font from this location. TessPDFRenderer(const char *outputbase, const char *datadir); protected: virtual bool BeginDocumentHandler(); virtual bool AddImageHandler(TessBaseAPI* api); virtual bool EndDocumentHandler(); private: // We don't want to have every image in memory at once, // so we store some metadata as we go along producing // PDFs one page at a time. At the end that metadata is // used to make everything that isn't easily handled in a // streaming fashion. long int obj_; // counter for PDF objects GenericVector<long int> offsets_; // offset of every PDF object in bytes GenericVector<long int> pages_; // object number for every /Page object const char *datadir_; // where to find the custom font // Bookkeeping only. DIY = Do It Yourself. void AppendPDFObjectDIY(size_t objectsize); // Bookkeeping + emit data. void AppendPDFObject(const char *data); // Create the /Contents object for an entire page. static char* GetPDFTextObjects(TessBaseAPI* api, double width, double height); // Turn an image into a PDF object. Only transcode if we have to. static bool imageToPDFObj(Pix *pix, char *filename, long int objnum, char **pdf_object, long int *pdf_object_size); }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessUnlvRenderer : public TessResultRenderer { public: explicit TessUnlvRenderer(const char *outputbase); protected: virtual bool AddImageHandler(TessBaseAPI* api); }; /** * Renders tesseract output into a plain UTF-8 text string */ class TESS_API TessBoxTextRenderer : public TessResultRenderer { public: explicit TessBoxTextRenderer(const char *outputbase); protected: virtual bool AddImageHandler(TessBaseAPI* api); }; } // namespace tesseract. #endif // TESSERACT_API_RENDERER_H__
1080228-arabicocr11
api/renderer.h
C++
asf20
8,215
#ifndef _OCL_KERNEL_H_ #define _OCL_KERNEL_H_ #ifndef USE_EXTERNAL_KERNEL #define KERNEL( ... )# __VA_ARGS__ "\n" // Double precision is a default of spreadsheets // cl_khr_fp64: Khronos extension // cl_amd_fp64: AMD extension // use build option outside to define fp_t ///////////////////////////////////////////// const char *kernel_src = KERNEL( \n#ifdef KHR_DP_EXTENSION\n \n#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n \n#elif AMD_DP_EXTENSION\n \n#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n \n#else\n \n#endif\n __kernel void composeRGBPixel(__global uint *tiffdata, int w, int h,int wpl, __global uint *output) { int i = get_global_id(1); int j = get_global_id(0); int tiffword,rval,gval,bval; //Ignore the excess if ((i >= h) || (j >= w)) return; tiffword = tiffdata[i * w + j]; rval = ((tiffword) & 0xff); gval = (((tiffword) >> 8) & 0xff); bval = (((tiffword) >> 16) & 0xff); output[i*wpl+j] = (rval << (8 * (sizeof(uint) - 1 - 0))) | (gval << (8 * (sizeof(uint) - 1 - 1))) | (bval << (8 * (sizeof(uint) - 1 - 2))); } ) KERNEL( \n__kernel void pixSubtract_inplace(__global int *dword, __global int *sword, const int wpl, const int h) { const unsigned int row = get_global_id(1); const unsigned int col = get_global_id(0); const unsigned int pos = row * wpl + col; //Ignore the execss if (row >= h || col >= wpl) return; *(dword + pos) &= ~(*(sword + pos)); }\n ) KERNEL( \n__kernel void pixSubtract(__global int *dword, __global int *sword, const int wpl, const int h, __global int *outword) { const unsigned int row = get_global_id(1); const unsigned int col = get_global_id(0); const unsigned int pos = row * wpl + col; //Ignore the execss if (row >= h || col >= wpl) return; *(outword + pos) = *(dword + pos) & ~(*(sword + pos)); }\n ) KERNEL( \n__kernel void pixAND(__global int *dword, __global int *sword, __global int *outword, const int wpl, const int h) { const unsigned int row = get_global_id(1); const unsigned int col = get_global_id(0); const unsigned int pos = row * wpl + col; //Ignore the execss if (row >= h || col >= wpl) return; *(outword + pos) = *(dword + pos) & (*(sword + pos)); }\n ) KERNEL( \n__kernel void pixOR(__global int *dword, __global int *sword, __global int *outword, const int wpl, const int h) { const unsigned int row = get_global_id(1); const unsigned int col = get_global_id(0); const unsigned int pos = row * wpl + col; //Ignore the execss if (row >= h || col >= wpl) return; *(outword + pos) = *(dword + pos) | (*(sword + pos)); }\n ) KERNEL( \n__kernel void morphoDilateHor_5x5(__global int *sword,__global int *dword, const int wpl, const int h) { const unsigned int pos = get_global_id(0); unsigned int prevword, nextword, currword,tempword; unsigned int destword; const int col = pos % wpl; //Ignore the execss if (pos >= (wpl * h)) return; currword = *(sword + pos); destword = currword; //Handle boundary conditions if(col==0) prevword=0; else prevword = *(sword + pos - 1); if(col==(wpl - 1)) nextword=0; else nextword = *(sword + pos + 1); //Loop unrolled //1 bit to left and 1 bit to right //Get the max value on LHS of every pixel tempword = (prevword << (31)) | ((currword >> 1)); destword |= tempword; //Get max value on RHS of every pixel tempword = (currword << 1) | (nextword >> (31)); destword |= tempword; //2 bit to left and 2 bit to right //Get the max value on LHS of every pixel tempword = (prevword << (30)) | ((currword >> 2)); destword |= tempword; //Get max value on RHS of every pixel tempword = (currword << 2) | (nextword >> (30)); destword |= tempword; *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoDilateVer_5x5(__global int *sword,__global int *dword, const int wpl, const int h) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int tempword; unsigned int destword; int i; //Ignore the execss if (row >= h || col >= wpl) return; destword = *(sword + pos); //2 words above i = (row - 2) < 0 ? row : (row - 2); tempword = *(sword + i*wpl + col); destword |= tempword; //1 word above i = (row - 1) < 0 ? row : (row - 1); tempword = *(sword + i*wpl + col); destword |= tempword; //1 word below i = (row >= (h - 1)) ? row : (row + 1); tempword = *(sword + i*wpl + col); destword |= tempword; //2 words below i = (row >= (h - 2)) ? row : (row + 2); tempword = *(sword + i*wpl + col); destword |= tempword; *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoDilateHor(__global int *sword,__global int *dword,const int xp, const int xn, const int wpl, const int h) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int parbitsxp, parbitsxn, nwords; unsigned int destword, tempword, lastword, currword; unsigned int lnextword, lprevword, rnextword, rprevword, firstword, secondword; int i, j, siter, eiter; //Ignore the execss if (pos >= (wpl*h) || (xn < 1 && xp < 1)) return; currword = *(sword + pos); destword = currword; parbitsxp = xp & 31; parbitsxn = xn & 31; nwords = xp >> 5; if (parbitsxp > 0) nwords += 1; else parbitsxp = 31; siter = (col - nwords); eiter = (col + nwords); //Get prev word if (col==0) firstword = 0x0; else firstword = *(sword + pos - 1); //Get next word if (col == (wpl - 1)) secondword = 0x0; else secondword = *(sword + pos + 1); //Last partial bits on either side for (i = 1; i <= parbitsxp; i++) { //Get the max value on LHS of every pixel tempword = ((i == parbitsxp) && (parbitsxp != parbitsxn)) ? 0x0 : (firstword << (32-i)) | ((currword >> i)); destword |= tempword; //Get max value on RHS of every pixel tempword = (currword << i) | (secondword >> (32 - i)); destword |= tempword; } //Return if halfwidth <= 1 word if (nwords == 1) { if (xn == 32) { destword |= firstword; } if (xp == 32) { destword |= secondword; } *(dword + pos) = destword; return; } if (siter < 0) firstword = 0x0; else firstword = *(sword + row*wpl + siter); if (eiter >= wpl) lastword = 0x0; else lastword = *(sword + row*wpl + eiter); for ( i = 1; i < nwords; i++) { //Gets LHS words if ((siter + i) < 0) secondword = 0x0; else secondword = *(sword + row*wpl + siter + i); lprevword = firstword << (32 - parbitsxn) | secondword >> parbitsxn; firstword = secondword; if ((siter + i + 1) < 0) secondword = 0x0; else secondword = *(sword + row*wpl + siter + i + 1); lnextword = firstword << (32 - parbitsxn) | secondword >> parbitsxn; //Gets RHS words if ((eiter - i) >= wpl) firstword = 0x0; else firstword = *(sword + row*wpl + eiter - i); rnextword = firstword << parbitsxp | lastword >> (32 - parbitsxp); lastword = firstword; if ((eiter - i - 1) >= wpl) firstword = 0x0; else firstword = *(sword + row*wpl + eiter - i - 1); rprevword = firstword << parbitsxp | lastword >> (32 - parbitsxp); for (j = 1; j < 32; j++) { //OR LHS full words tempword = (lprevword << j) | (lnextword >> (32 - j)); destword |= tempword; //OR RHS full words tempword = (rprevword << j) | (rnextword >> (32 - j)); destword |= tempword; } destword |= lprevword; destword |= lnextword; destword |= rprevword; destword |= rnextword; lastword = firstword; firstword = secondword; } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoDilateHor_32word(__global int *sword,__global int *dword, const int halfwidth, const int wpl, const int h, const char isEven) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int prevword, nextword, currword,tempword; unsigned int destword; int i; //Ignore the execss if (pos >= (wpl * h)) return; currword = *(sword + pos); destword = currword; //Handle boundary conditions if(col==0) prevword=0; else prevword = *(sword + pos - 1); if(col==(wpl - 1)) nextword=0; else nextword = *(sword + pos + 1); for (i = 1; i <= halfwidth; i++) { //Get the max value on LHS of every pixel if (i == halfwidth && isEven) { tempword = 0x0; } else { tempword = (prevword << (32-i)) | ((currword >> i)); } destword |= tempword; //Get max value on RHS of every pixel tempword = (currword << i) | (nextword >> (32 - i)); destword |= tempword; } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoDilateVer(__global int *sword,__global int *dword, const int yp, const int wpl, const int h, const int yn) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int tempword; unsigned int destword; int i, siter, eiter; //Ignore the execss if (row >= h || col >= wpl) return; destword = *(sword + pos); //Set start position and end position considering the boundary conditions siter = (row - yn) < 0 ? 0 : (row - yn); eiter = (row >= (h - yp)) ? (h - 1) : (row + yp); for (i = siter; i <= eiter; i++) { tempword = *(sword + i*wpl + col); destword |= tempword; } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoErodeHor_5x5(__global int *sword,__global int *dword, const int wpl, const int h) { const unsigned int pos = get_global_id(0); unsigned int prevword, nextword, currword,tempword; unsigned int destword; const int col = pos % wpl; //Ignore the execss if (pos >= (wpl * h)) return; currword = *(sword + pos); destword = currword; //Handle boundary conditions if(col==0) prevword=0xffffffff; else prevword = *(sword + pos - 1); if(col==(wpl - 1)) nextword=0xffffffff; else nextword = *(sword + pos + 1); //Loop unrolled //1 bit to left and 1 bit to right //Get the min value on LHS of every pixel tempword = (prevword << (31)) | ((currword >> 1)); destword &= tempword; //Get min value on RHS of every pixel tempword = (currword << 1) | (nextword >> (31)); destword &= tempword; //2 bit to left and 2 bit to right //Get the min value on LHS of every pixel tempword = (prevword << (30)) | ((currword >> 2)); destword &= tempword; //Get min value on RHS of every pixel tempword = (currword << 2) | (nextword >> (30)); destword &= tempword; *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoErodeVer_5x5(__global int *sword,__global int *dword, const int wpl, const int h, const int fwmask, const int lwmask) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int tempword; unsigned int destword; int i; //Ignore the execss if (row >= h || col >= wpl) return; destword = *(sword + pos); if (row < 2 || row >= (h - 2)) { destword = 0x0; } else { //2 words above //i = (row - 2) < 0 ? row : (row - 2); i = (row - 2); tempword = *(sword + i*wpl + col); destword &= tempword; //1 word above //i = (row - 1) < 0 ? row : (row - 1); i = (row - 1); tempword = *(sword + i*wpl + col); destword &= tempword; //1 word below //i = (row >= (h - 1)) ? row : (row + 1); i = (row + 1); tempword = *(sword + i*wpl + col); destword &= tempword; //2 words below //i = (row >= (h - 2)) ? row : (row + 2); i = (row + 2); tempword = *(sword + i*wpl + col); destword &= tempword; if (col == 0) { destword &= fwmask; } if (col == (wpl - 1)) { destword &= lwmask; } } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoErodeHor(__global int *sword,__global int *dword, const int xp, const int xn, const int wpl, const int h, const char isAsymmetric, const int rwmask, const int lwmask) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int parbitsxp, parbitsxn, nwords; unsigned int destword, tempword, lastword, currword; unsigned int lnextword, lprevword, rnextword, rprevword, firstword, secondword; int i, j, siter, eiter; //Ignore the execss if (pos >= (wpl*h) || (xn < 1 && xp < 1)) return; currword = *(sword + pos); destword = currword; parbitsxp = xp & 31; parbitsxn = xn & 31; nwords = xp >> 5; if (parbitsxp > 0) nwords += 1; else parbitsxp = 31; siter = (col - nwords); eiter = (col + nwords); //Get prev word if (col==0) firstword = 0xffffffff; else firstword = *(sword + pos - 1); //Get next word if (col == (wpl - 1)) secondword = 0xffffffff; else secondword = *(sword + pos + 1); //Last partial bits on either side for (i = 1; i <= parbitsxp; i++) { //Get the max value on LHS of every pixel tempword = (firstword << (32-i)) | ((currword >> i)); destword &= tempword; //Get max value on RHS of every pixel tempword = ((i == parbitsxp) && (parbitsxp != parbitsxn)) ? 0xffffffff : (currword << i) | (secondword >> (32 - i)); //tempword = (currword << i) | (secondword >> (32 - i)); destword &= tempword; } //Return if halfwidth <= 1 word if (nwords == 1) { if (xp == 32) { destword &= firstword; } if (xn == 32) { destword &= secondword; } //Clear boundary pixels if (isAsymmetric) { if (col == 0) destword &= rwmask; if (col == (wpl - 1)) destword &= lwmask; } *(dword + pos) = destword; return; } if (siter < 0) firstword = 0xffffffff; else firstword = *(sword + row*wpl + siter); if (eiter >= wpl) lastword = 0xffffffff; else lastword = *(sword + row*wpl + eiter); for ( i = 1; i < nwords; i++) { //Gets LHS words if ((siter + i) < 0) secondword = 0xffffffff; else secondword = *(sword + row*wpl + siter + i); lprevword = firstword << (32 - parbitsxp) | secondword >> (parbitsxp); firstword = secondword; if ((siter + i + 1) < 0) secondword = 0xffffffff; else secondword = *(sword + row*wpl + siter + i + 1); lnextword = firstword << (32 - parbitsxp) | secondword >> (parbitsxp); //Gets RHS words if ((eiter - i) >= wpl) firstword = 0xffffffff; else firstword = *(sword + row*wpl + eiter - i); rnextword = firstword << parbitsxn | lastword >> (32 - parbitsxn); lastword = firstword; if ((eiter - i - 1) >= wpl) firstword = 0xffffffff; else firstword = *(sword + row*wpl + eiter - i - 1); rprevword = firstword << parbitsxn | lastword >> (32 - parbitsxn); for (j = 0; j < 32; j++) { //OR LHS full words tempword = (lprevword << j) | (lnextword >> (32 - j)); destword &= tempword; //OR RHS full words tempword = (rprevword << j) | (rnextword >> (32 - j)); destword &= tempword; } destword &= lprevword; destword &= lnextword; destword &= rprevword; destword &= rnextword; lastword = firstword; firstword = secondword; } if (isAsymmetric) { //Clear boundary pixels if (col < (nwords - 1)) destword = 0x0; else if (col == (nwords - 1)) destword &= rwmask; else if (col > (wpl - nwords)) destword = 0x0; else if (col == (wpl - nwords)) destword &= lwmask; } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoErodeHor_32word(__global int *sword,__global int *dword, const int halfwidth, const int wpl, const int h, const char clearBoundPixH, const int rwmask, const int lwmask, const char isEven) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int prevword, nextword, currword,tempword, destword; int i; //Ignore the execss if (pos >= (wpl * h)) return; currword = *(sword + pos); destword = currword; //Handle boundary conditions if(col==0) prevword=0xffffffff; else prevword = *(sword + pos - 1); if(col==(wpl - 1)) nextword=0xffffffff; else nextword = *(sword + pos + 1); for (i = 1; i <= halfwidth; i++) { //Get the min value on LHS of every pixel tempword = (prevword << (32-i)) | ((currword >> i)); destword &= tempword; //Get min value on RHS of every pixel if (i == halfwidth && isEven) { tempword = 0xffffffff; } else { tempword = (currword << i) | (nextword >> (32 - i)); } destword &= tempword; } if (clearBoundPixH) { if (col == 0) { destword &= rwmask; } else if (col == (wpl - 1)) { destword &= lwmask; } } *(dword + pos) = destword; }\n ) KERNEL( \n__kernel void morphoErodeVer(__global int *sword,__global int *dword, const int yp, const int wpl, const int h, const char clearBoundPixV, const int yn) { const int col = get_global_id(0); const int row = get_global_id(1); const unsigned int pos = row * wpl + col; unsigned int tempword, destword; int i, siter, eiter; //Ignore the execss if (row >= h || col >= wpl) return; destword = *(sword + pos); //Set start position and end position considering the boundary conditions siter = (row - yp) < 0 ? 0 : (row - yp); eiter = (row >= (h - yn)) ? (h - 1) : (row + yn); for (i = siter; i <= eiter; i++) { tempword = *(sword + i*wpl + col); destword &= tempword; } //Clear boundary pixels if (clearBoundPixV && ((row < yp) || ((h - row) <= yn))) { destword = 0x0; } *(dword + pos) = destword; }\n ) // HistogramRect Kernel: Accumulate // assumes 4 channels, i.e., bytes_per_pixel = 4 // assumes number of pixels is multiple of 8 // data is layed out as // ch0 ch1 ... // bin0 bin1 bin2... bin0... // rpt0,1,2...256 rpt0,1,2... KERNEL( \n#define HIST_REDUNDANCY 256\n \n#define GROUP_SIZE 256\n \n#define HIST_SIZE 256\n \n#define NUM_CHANNELS 4\n \n#define HR_UNROLL_SIZE 8 \n \n#define HR_UNROLL_TYPE uchar8 \n __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_HistogramRectAllChannels( __global const uchar8 *data, uint numPixels, __global uint *histBuffer) { // declare variables uchar8 pixels; int threadOffset = get_global_id(0)%HIST_REDUNDANCY; // for each pixel/channel, accumulate in global memory for ( uint pc = get_global_id(0); pc < numPixels*NUM_CHANNELS/HR_UNROLL_SIZE; pc += get_global_size(0) ) { pixels = data[pc]; // channel bin thread atomic_inc( &histBuffer[ 0*HIST_SIZE*HIST_REDUNDANCY + pixels.s0*HIST_REDUNDANCY + threadOffset ]); // ch0 atomic_inc( &histBuffer[ 0*HIST_SIZE*HIST_REDUNDANCY + pixels.s4*HIST_REDUNDANCY + threadOffset ]); // ch0 atomic_inc( &histBuffer[ 1*HIST_SIZE*HIST_REDUNDANCY + pixels.s1*HIST_REDUNDANCY + threadOffset ]); // ch1 atomic_inc( &histBuffer[ 1*HIST_SIZE*HIST_REDUNDANCY + pixels.s5*HIST_REDUNDANCY + threadOffset ]); // ch1 atomic_inc( &histBuffer[ 2*HIST_SIZE*HIST_REDUNDANCY + pixels.s2*HIST_REDUNDANCY + threadOffset ]); // ch2 atomic_inc( &histBuffer[ 2*HIST_SIZE*HIST_REDUNDANCY + pixels.s6*HIST_REDUNDANCY + threadOffset ]); // ch2 atomic_inc( &histBuffer[ 3*HIST_SIZE*HIST_REDUNDANCY + pixels.s3*HIST_REDUNDANCY + threadOffset ]); // ch3 atomic_inc( &histBuffer[ 3*HIST_SIZE*HIST_REDUNDANCY + pixels.s7*HIST_REDUNDANCY + threadOffset ]); // ch3 } } ) KERNEL( // NUM_CHANNELS = 1 __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_HistogramRectOneChannel( __global const uchar8 *data, uint numPixels, __global uint *histBuffer) { // declare variables uchar8 pixels; int threadOffset = get_global_id(0)%HIST_REDUNDANCY; // for each pixel/channel, accumulate in global memory for ( uint pc = get_global_id(0); pc < numPixels/HR_UNROLL_SIZE; pc += get_global_size(0) ) { pixels = data[pc]; // bin thread atomic_inc( &histBuffer[ pixels.s0*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s1*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s2*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s3*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s4*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s5*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s6*HIST_REDUNDANCY + threadOffset ]); atomic_inc( &histBuffer[ pixels.s7*HIST_REDUNDANCY + threadOffset ]); } } ) KERNEL( // unused \n __attribute__((reqd_work_group_size(256, 1, 1))) \n __kernel \n void kernel_HistogramRectAllChannels_Grey( \n __global const uchar* data, \n uint numPixels, \n __global uint *histBuffer) { // each wg will write HIST_SIZE*NUM_CHANNELS into this result; cpu will accumulate across wg's \n \n /* declare variables */ \n \n // work indices \n size_t groupId = get_group_id(0); \n size_t localId = get_local_id(0); // 0 -> 256-1 \n size_t globalId = get_global_id(0); // 0 -> 8*10*256-1=20480-1 \n uint numThreads = get_global_size(0); \n \n /* accumulate in global memory */ \n for ( uint pc = get_global_id(0); pc < numPixels; pc += get_global_size(0) ) { \n uchar value = data[ pc ]; \n int idx = value * get_global_size(0) + get_global_id(0); \n histBuffer[ idx ]++; \n \n } \n \n } // kernel_HistogramRectAllChannels_Grey ) // HistogramRect Kernel: Reduction // only supports 4 channels // each work group handles a single channel of a single histogram bin KERNEL( __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_HistogramRectAllChannelsReduction( int n, // unused pixel redundancy __global uint *histBuffer, __global int* histResult) { // declare variables int channel = get_group_id(0)/HIST_SIZE; int bin = get_group_id(0)%HIST_SIZE; int value = 0; // accumulate in register for ( uint i = get_local_id(0); i < HIST_REDUNDANCY; i+=GROUP_SIZE) { value += histBuffer[ channel*HIST_SIZE*HIST_REDUNDANCY+bin*HIST_REDUNDANCY+i]; } // reduction in local memory __local int localHist[GROUP_SIZE]; localHist[get_local_id(0)] = value; barrier(CLK_LOCAL_MEM_FENCE); for (int stride = GROUP_SIZE/2; stride >= 1; stride /= 2) { if (get_local_id(0) < stride) { value = localHist[ get_local_id(0)+stride]; } barrier(CLK_LOCAL_MEM_FENCE); if (get_local_id(0) < stride) { localHist[ get_local_id(0)] += value; } barrier(CLK_LOCAL_MEM_FENCE); } // write reduction to final result if (get_local_id(0) == 0) { histResult[get_group_id(0)] = localHist[0]; } } // kernel_HistogramRectAllChannels ) KERNEL( // NUM_CHANNELS = 1 __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_HistogramRectOneChannelReduction( int n, // unused pixel redundancy __global uint *histBuffer, __global int* histResult) { // declare variables // int channel = get_group_id(0)/HIST_SIZE; int bin = get_group_id(0)%HIST_SIZE; int value = 0; // accumulate in register for ( int i = get_local_id(0); i < HIST_REDUNDANCY; i+=GROUP_SIZE) { value += histBuffer[ bin*HIST_REDUNDANCY+i]; } // reduction in local memory __local int localHist[GROUP_SIZE]; localHist[get_local_id(0)] = value; barrier(CLK_LOCAL_MEM_FENCE); for (int stride = GROUP_SIZE/2; stride >= 1; stride /= 2) { if (get_local_id(0) < stride) { value = localHist[ get_local_id(0)+stride]; } barrier(CLK_LOCAL_MEM_FENCE); if (get_local_id(0) < stride) { localHist[ get_local_id(0)] += value; } barrier(CLK_LOCAL_MEM_FENCE); } // write reduction to final result if (get_local_id(0) == 0) { histResult[get_group_id(0)] = localHist[0]; } } // kernel_HistogramRectOneChannelReduction ) KERNEL( // unused // each work group (x256) handles a histogram bin \n __attribute__((reqd_work_group_size(256, 1, 1))) \n __kernel \n void kernel_HistogramRectAllChannelsReduction_Grey( \n int n, // pixel redundancy that needs to be accumulated \n __global uint *histBuffer, \n __global uint* histResult) { // each wg accumulates 1 bin \n \n /* declare variables */ \n \n // work indices \n size_t groupId = get_group_id(0); \n size_t localId = get_local_id(0); // 0 -> 256-1 \n size_t globalId = get_global_id(0); // 0 -> 8*10*256-1=20480-1 \n uint numThreads = get_global_size(0); \n unsigned int hist = 0; \n \n /* accumulate in global memory */ \n for ( uint p = 0; p < n; p+=GROUP_SIZE) { \n hist += histBuffer[ (get_group_id(0)*n + p)]; \n } \n \n /* reduction in local memory */ \n // populate local memory \n __local unsigned int localHist[GROUP_SIZE]; \n localHist[localId] = hist; \n barrier(CLK_LOCAL_MEM_FENCE); \n \n for (int stride = GROUP_SIZE/2; stride >= 1; stride /= 2) { \n if (localId < stride) { \n hist = localHist[ (localId+stride)]; \n } \n barrier(CLK_LOCAL_MEM_FENCE); \n if (localId < stride) { \n localHist[ localId] += hist; \n } \n barrier(CLK_LOCAL_MEM_FENCE); \n } \n \n if (localId == 0) \n histResult[get_group_id(0)] = localHist[0]; \n \n } // kernel_HistogramRectAllChannelsReduction_Grey ) // ThresholdRectToPix Kernel // only supports 4 channels // imageData is input image (24-bits/pixel) // pix is output image (1-bit/pixel) KERNEL( \n#define CHAR_VEC_WIDTH 8 \n \n#define PIXELS_PER_WORD 32 \n \n#define PIXELS_PER_BURST 8 \n \n#define BURSTS_PER_WORD (PIXELS_PER_WORD/PIXELS_PER_BURST) \n typedef union { uchar s[PIXELS_PER_BURST*NUM_CHANNELS]; uchar8 v[(PIXELS_PER_BURST*NUM_CHANNELS)/CHAR_VEC_WIDTH]; } charVec; __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_ThresholdRectToPix( __global const uchar8 *imageData, int height, int width, int wpl, // words per line __global int *thresholds, __global int *hi_values, __global int *pix) { // declare variables int pThresholds[NUM_CHANNELS]; int pHi_Values[NUM_CHANNELS]; for ( int i = 0; i < NUM_CHANNELS; i++) { pThresholds[i] = thresholds[i]; pHi_Values[i] = hi_values[i]; } // for each word (32 pixels) in output image for ( uint w = get_global_id(0); w < wpl*height; w += get_global_size(0) ) { unsigned int word = 0; // all bits start at zero // for each burst in word for ( int b = 0; b < BURSTS_PER_WORD; b++) { // load burst charVec pixels; for ( int i = 0; i < (PIXELS_PER_BURST*NUM_CHANNELS)/CHAR_VEC_WIDTH; i++ ) { pixels.v[i] = imageData[w*(BURSTS_PER_WORD*(PIXELS_PER_BURST*NUM_CHANNELS)/CHAR_VEC_WIDTH) + b*((PIXELS_PER_BURST*NUM_CHANNELS)/CHAR_VEC_WIDTH) + i]; } // for each pixel in burst for ( int p = 0; p < PIXELS_PER_BURST; p++) { for ( int c = 0; c < NUM_CHANNELS; c++) { unsigned char pixChan = pixels.s[p*NUM_CHANNELS + c]; if (pHi_Values[c] >= 0 && (pixChan > pThresholds[c]) == (pHi_Values[c] == 0)) { word |= (0x80000000 >> ((b*PIXELS_PER_BURST+p)&31)); } } } } pix[w] = word; } } // only supports 1 channel typedef union { uchar s[PIXELS_PER_BURST]; uchar8 v[(PIXELS_PER_BURST)/CHAR_VEC_WIDTH]; } charVec1; __attribute__((reqd_work_group_size(256, 1, 1))) __kernel void kernel_ThresholdRectToPix_OneChan( __global const uchar8 *imageData, int height, int width, int wpl, // words per line __global int *thresholds, __global int *hi_values, __global int *pix) { // declare variables int pThresholds[1]; int pHi_Values[1]; for ( int i = 0; i < 1; i++) { pThresholds[i] = thresholds[i]; pHi_Values[i] = hi_values[i]; } // for each word (32 pixels) in output image for ( uint w = get_global_id(0); w < wpl*height; w += get_global_size(0) ) { unsigned int word = 0; // all bits start at zero // for each burst in word for ( int b = 0; b < BURSTS_PER_WORD; b++) { // load burst charVec1 pixels; for ( int i = 0; i < (PIXELS_PER_BURST)/CHAR_VEC_WIDTH; i++ ) { pixels.v[i] = imageData[w*(BURSTS_PER_WORD*(PIXELS_PER_BURST)/CHAR_VEC_WIDTH) + b*((PIXELS_PER_BURST)/CHAR_VEC_WIDTH) + i]; } // for each pixel in burst for ( int p = 0; p < PIXELS_PER_BURST; p++) { for ( int c = 0; c < 1; c++) { unsigned char pixChan = pixels.s[p + c]; if (pHi_Values[c] >= 0 && (pixChan > pThresholds[c]) == (pHi_Values[c] == 0)) { word |= (0x80000000 >> ((b*PIXELS_PER_BURST+p)&31)); } } } } pix[w] = word; } } ) ; // close char* #endif // USE_EXTERNAL_KERNEL #endif //_OCL_KERNEL_H_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ // Alternative histogram kernel written to use uchar and different global memory scattered write // was a little better for intel platforms but still not faster then native serial code #if 0 /* data layed out as bin0 bin1 bin2... r,g,b,a,r,g,b,a,r,g,b,a nthreads/4 copies */ \n__attribute__((reqd_work_group_size(256, 1, 1))) \n __kernel \n void kernel_HistogramRectAllChannels_uchar( \n volatile __global const uchar *data, \n uint numPixels, \n volatile __global uint *histBuffer) { \n \n // for each pixel/channel, accumulate in global memory \n for ( uint pc = get_global_id(0); pc < numPixels*NUM_CHANNELS; pc += get_global_size(0) ) { \n uchar value = data[pc]; \n int idx = value*get_global_size(0) + get_global_id(0); \n histBuffer[ idx ]++; // coalesced if same value \n } \n } // kernel_HistogramRectAllChannels \n \n __attribute__((reqd_work_group_size(256, 1, 1))) \n __kernel \n void kernel_HistogramRectAllChannelsReduction_uchar( \n int n, // pixel redundancy that needs to be accumulated = nthreads/4 \n __global uint4 *histBuffer, \n __global uint* histResult) { // each wg accumulates 1 bin (all channels within it \n \n // declare variables \n int binIdx = get_group_id(0); \n size_t groupId = get_group_id(0); \n size_t localId = get_local_id(0); // 0 -> 256-1 \n size_t globalId = get_global_id(0); // 0 -> 8*10*256-1=20480-1 \n uint numThreads = get_global_size(0); \n uint4 hist = {0, 0, 0, 0}; \n \n // accumulate in register \n for ( uint p = get_local_id(0); p < n; p+=GROUP_SIZE) { \n hist += histBuffer[binIdx*n+p]; \n } \n \n // reduction in local memory \n __local uint4 localHist[GROUP_SIZE]; \n localHist[localId] = hist; \n barrier(CLK_LOCAL_MEM_FENCE); \n \n for (int stride = GROUP_SIZE/2; stride >= 1; stride /= 2) { \n if (localId < stride) { \n hist = localHist[ localId+stride]; \n } \n barrier(CLK_LOCAL_MEM_FENCE); \n if (localId < stride) { \n localHist[ localId] += hist; \n } \n barrier(CLK_LOCAL_MEM_FENCE); \n } \n \n // write reduction to final result \n if (localId == 0) { \n histResult[0*HIST_SIZE+binIdx] = localHist[0].s0; \n histResult[1*HIST_SIZE+binIdx] = localHist[0].s1; \n histResult[2*HIST_SIZE+binIdx] = localHist[0].s2; \n histResult[3*HIST_SIZE+binIdx] = localHist[0].s3; \n } \n \n } // kernel_HistogramRectAllChannels #endif
1080228-arabicocr11
opencl/oclkernels.h
C
asf20
35,547
#ifdef USE_OPENCL #ifndef DEVICE_SELECTION_H #define DEVICE_SELECTION_H #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #define DS_DEVICE_NAME_LENGTH 256 typedef enum { DS_SUCCESS = 0, DS_INVALID_PROFILE = 1000, DS_MEMORY_ERROR, DS_INVALID_PERF_EVALUATOR_TYPE, DS_INVALID_PERF_EVALUATOR, DS_PERF_EVALUATOR_ERROR, DS_FILE_ERROR, DS_UNKNOWN_DEVICE_TYPE, DS_PROFILE_FILE_ERROR, DS_SCORE_SERIALIZER_ERROR, DS_SCORE_DESERIALIZER_ERROR } ds_status; // device type typedef enum { DS_DEVICE_NATIVE_CPU = 0, DS_DEVICE_OPENCL_DEVICE } ds_device_type; typedef struct { ds_device_type type; cl_device_id oclDeviceID; char* oclDeviceName; char* oclDriverVersion; // a pointer to the score data, the content/format is application defined. void* score; } ds_device; typedef struct { unsigned int numDevices; ds_device* devices; const char* version; } ds_profile; // deallocate memory used by score typedef ds_status (*ds_score_release)(void* score); static ds_status releaseDSProfile(ds_profile* profile, ds_score_release sr) { ds_status status = DS_SUCCESS; if (profile!=NULL) { if (profile->devices!=NULL && sr!=NULL) { unsigned int i; for (i = 0; i < profile->numDevices; i++) { status = sr(profile->devices[i].score); if (status != DS_SUCCESS) break; } free(profile->devices); } free(profile); } return status; } static ds_status initDSProfile(ds_profile** p, const char* version) { int numDevices; cl_uint numPlatforms; cl_platform_id* platforms = NULL; cl_device_id* devices = NULL; ds_status status = DS_SUCCESS; ds_profile* profile = NULL; unsigned int next; unsigned int i; if (p == NULL) return DS_INVALID_PROFILE; profile = (ds_profile*)malloc(sizeof(ds_profile)); if (profile == NULL) return DS_MEMORY_ERROR; memset(profile, 0, sizeof(ds_profile)); clGetPlatformIDs(0, NULL, &numPlatforms); if (numPlatforms == 0) goto cleanup; platforms = (cl_platform_id*)malloc(numPlatforms*sizeof(cl_platform_id)); if (platforms == NULL) { status = DS_MEMORY_ERROR; goto cleanup; } clGetPlatformIDs(numPlatforms, platforms, NULL); numDevices = 0; for (i = 0; i < (unsigned int)numPlatforms; i++) { cl_uint num; clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, 0, NULL, &num); numDevices+=num; } if (numDevices == 0) goto cleanup; devices = (cl_device_id*)malloc(numDevices*sizeof(cl_device_id)); if (devices == NULL) { status = DS_MEMORY_ERROR; goto cleanup; } profile->numDevices = numDevices+1; // +1 to numDevices to include the native CPU profile->devices = (ds_device*)malloc(profile->numDevices*sizeof(ds_device)); if (profile->devices == NULL) { profile->numDevices = 0; status = DS_MEMORY_ERROR; goto cleanup; } memset(profile->devices, 0, profile->numDevices*sizeof(ds_device)); next = 0; for (i = 0; i < (unsigned int)numPlatforms; i++) { cl_uint num; unsigned j; clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, numDevices, devices, &num); for (j = 0; j < num; j++, next++) { char buffer[DS_DEVICE_NAME_LENGTH]; size_t length; profile->devices[next].type = DS_DEVICE_OPENCL_DEVICE; profile->devices[next].oclDeviceID = devices[j]; clGetDeviceInfo(profile->devices[next].oclDeviceID, CL_DEVICE_NAME , DS_DEVICE_NAME_LENGTH, &buffer, NULL); length = strlen(buffer); profile->devices[next].oclDeviceName = (char*)malloc(length+1); memcpy(profile->devices[next].oclDeviceName, buffer, length+1); clGetDeviceInfo(profile->devices[next].oclDeviceID, CL_DRIVER_VERSION , DS_DEVICE_NAME_LENGTH, &buffer, NULL); length = strlen(buffer); profile->devices[next].oclDriverVersion = (char*)malloc(length+1); memcpy(profile->devices[next].oclDriverVersion, buffer, length+1); } } profile->devices[next].type = DS_DEVICE_NATIVE_CPU; profile->version = version; cleanup: if (platforms) free(platforms); if (devices) free(devices); if (status == DS_SUCCESS) { *p = profile; } else { if (profile) { if (profile->devices) free(profile->devices); free(profile); } } return status; } // Pointer to a function that calculates the score of a device (ex: // device->score) update the data size of score. The encoding and the format // of the score data is implementation defined. The function should return // DS_SUCCESS if there's no error to be reported. typedef ds_status (*ds_perf_evaluator)(ds_device* device, void* data); typedef enum { DS_EVALUATE_ALL ,DS_EVALUATE_NEW_ONLY } ds_evaluation_type; static ds_status profileDevices(ds_profile* profile, const ds_evaluation_type type, ds_perf_evaluator evaluator, void* evaluatorData, unsigned int* numUpdates) { ds_status status = DS_SUCCESS; unsigned int i; unsigned int updates = 0; if (profile == NULL) { return DS_INVALID_PROFILE; } if (evaluator == NULL) { return DS_INVALID_PERF_EVALUATOR; } for (i = 0; i < profile->numDevices; i++) { ds_status evaluatorStatus; switch (type) { case DS_EVALUATE_NEW_ONLY: if (profile->devices[i].score != NULL) break; // else fall through case DS_EVALUATE_ALL: evaluatorStatus = evaluator(profile->devices+i, evaluatorData); if (evaluatorStatus != DS_SUCCESS) { status = evaluatorStatus; return status; } updates++; break; default: return DS_INVALID_PERF_EVALUATOR_TYPE; break; }; } if (numUpdates) *numUpdates = updates; return status; } #define DS_TAG_VERSION "<version>" #define DS_TAG_VERSION_END "</version>" #define DS_TAG_DEVICE "<device>" #define DS_TAG_DEVICE_END "</device>" #define DS_TAG_SCORE "<score>" #define DS_TAG_SCORE_END "</score>" #define DS_TAG_DEVICE_TYPE "<type>" #define DS_TAG_DEVICE_TYPE_END "</type>" #define DS_TAG_DEVICE_NAME "<name>" #define DS_TAG_DEVICE_NAME_END "</name>" #define DS_TAG_DEVICE_DRIVER_VERSION "<driver>" #define DS_TAG_DEVICE_DRIVER_VERSION_END "</driver>" #define DS_DEVICE_NATIVE_CPU_STRING "native_cpu" typedef ds_status (*ds_score_serializer)(ds_device* device, void** serializedScore, unsigned int* serializedScoreSize); static ds_status writeProfileToFile(ds_profile* profile, ds_score_serializer serializer, const char* file) { ds_status status = DS_SUCCESS; FILE* profileFile = NULL; if (profile == NULL) return DS_INVALID_PROFILE; profileFile = fopen(file, "wb"); if (profileFile==NULL) { status = DS_FILE_ERROR; } else { unsigned int i; // write version string fwrite(DS_TAG_VERSION, sizeof(char), strlen(DS_TAG_VERSION), profileFile); fwrite(profile->version, sizeof(char), strlen(profile->version), profileFile); fwrite(DS_TAG_VERSION_END, sizeof(char), strlen(DS_TAG_VERSION_END), profileFile); fwrite("\n", sizeof(char), 1, profileFile); for (i = 0; i < profile->numDevices && status == DS_SUCCESS; i++) { void* serializedScore; unsigned int serializedScoreSize; fwrite(DS_TAG_DEVICE, sizeof(char), strlen(DS_TAG_DEVICE), profileFile); fwrite(DS_TAG_DEVICE_TYPE, sizeof(char), strlen(DS_TAG_DEVICE_TYPE), profileFile); fwrite(&profile->devices[i].type,sizeof(ds_device_type),1, profileFile); fwrite(DS_TAG_DEVICE_TYPE_END, sizeof(char), strlen(DS_TAG_DEVICE_TYPE_END), profileFile); switch(profile->devices[i].type) { case DS_DEVICE_NATIVE_CPU: { // There's no need to emit a device name for the native CPU device. /* fwrite(DS_TAG_DEVICE_NAME, sizeof(char), strlen(DS_TAG_DEVICE_NAME), profileFile); fwrite(DS_DEVICE_NATIVE_CPU_STRING,sizeof(char), strlen(DS_DEVICE_NATIVE_CPU_STRING), profileFile); fwrite(DS_TAG_DEVICE_NAME_END, sizeof(char), strlen(DS_TAG_DEVICE_NAME_END), profileFile); */ } break; case DS_DEVICE_OPENCL_DEVICE: { fwrite(DS_TAG_DEVICE_NAME, sizeof(char), strlen(DS_TAG_DEVICE_NAME), profileFile); fwrite(profile->devices[i].oclDeviceName, sizeof(char),strlen(profile->devices[i].oclDeviceName), profileFile); fwrite(DS_TAG_DEVICE_NAME_END, sizeof(char), strlen(DS_TAG_DEVICE_NAME_END), profileFile); fwrite(DS_TAG_DEVICE_DRIVER_VERSION, sizeof(char), strlen(DS_TAG_DEVICE_DRIVER_VERSION), profileFile); fwrite(profile->devices[i].oclDriverVersion, sizeof(char), strlen(profile->devices[i].oclDriverVersion), profileFile); fwrite(DS_TAG_DEVICE_DRIVER_VERSION_END, sizeof(char), strlen(DS_TAG_DEVICE_DRIVER_VERSION_END), profileFile); } break; default: status = DS_UNKNOWN_DEVICE_TYPE; break; }; fwrite(DS_TAG_SCORE, sizeof(char), strlen(DS_TAG_SCORE), profileFile); status = serializer(profile->devices+i, &serializedScore, &serializedScoreSize); if (status == DS_SUCCESS && serializedScore!=NULL && serializedScoreSize > 0) { fwrite(serializedScore, sizeof(char), serializedScoreSize, profileFile); free(serializedScore); } fwrite(DS_TAG_SCORE_END, sizeof(char), strlen(DS_TAG_SCORE_END), profileFile); fwrite(DS_TAG_DEVICE_END, sizeof(char), strlen(DS_TAG_DEVICE_END), profileFile); fwrite("\n",sizeof(char),1,profileFile); } fclose(profileFile); } return status; } static ds_status readProFile(const char* fileName, char** content, size_t* contentSize) { FILE * input = NULL; size_t size = 0; char* binary = NULL; *contentSize = 0; *content = NULL; input = fopen(fileName, "rb"); if(input == NULL) { return DS_FILE_ERROR; } fseek(input, 0L, SEEK_END); size = ftell(input); rewind(input); binary = (char*)malloc(size); if(binary == NULL) { fclose(input); return DS_FILE_ERROR; } fread(binary, sizeof(char), size, input); fclose(input); *contentSize = size; *content = binary; return DS_SUCCESS; } static const char* findString(const char* contentStart, const char* contentEnd, const char* string) { size_t stringLength; const char* currentPosition; const char* found; found = NULL; stringLength = strlen(string); currentPosition = contentStart; for(currentPosition = contentStart; currentPosition < contentEnd; currentPosition++) { if (*currentPosition == string[0]) { if (currentPosition+stringLength < contentEnd) { if (strncmp(currentPosition, string, stringLength) == 0) { found = currentPosition; break; } } } } return found; } typedef ds_status (*ds_score_deserializer)(ds_device* device, const unsigned char* serializedScore, unsigned int serializedScoreSize); static ds_status readProfileFromFile(ds_profile* profile, ds_score_deserializer deserializer, const char* file) { ds_status status = DS_SUCCESS; char* contentStart = NULL; const char* contentEnd = NULL; size_t contentSize; if (profile==NULL) return DS_INVALID_PROFILE; status = readProFile(file, &contentStart, &contentSize); if (status == DS_SUCCESS) { const char* currentPosition; const char* dataStart; const char* dataEnd; size_t versionStringLength; contentEnd = contentStart + contentSize; currentPosition = contentStart; // parse the version string dataStart = findString(currentPosition, contentEnd, DS_TAG_VERSION); if (dataStart == NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } dataStart += strlen(DS_TAG_VERSION); dataEnd = findString(dataStart, contentEnd, DS_TAG_VERSION_END); if (dataEnd==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } versionStringLength = strlen(profile->version); if (versionStringLength!=(dataEnd-dataStart) || strncmp(profile->version, dataStart, versionStringLength)!=0) { // version mismatch status = DS_PROFILE_FILE_ERROR; goto cleanup; } currentPosition = dataEnd+strlen(DS_TAG_VERSION_END); // parse the device information while (1) { unsigned int i; const char* deviceTypeStart; const char* deviceTypeEnd; ds_device_type deviceType; const char* deviceNameStart; const char* deviceNameEnd; const char* deviceScoreStart; const char* deviceScoreEnd; const char* deviceDriverStart; const char* deviceDriverEnd; dataStart = findString(currentPosition, contentEnd, DS_TAG_DEVICE); if (dataStart==NULL) { // nothing useful remain, quit... break; } dataStart+=strlen(DS_TAG_DEVICE); dataEnd = findString(dataStart, contentEnd, DS_TAG_DEVICE_END); if (dataEnd==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } // parse the device type deviceTypeStart = findString(dataStart, contentEnd, DS_TAG_DEVICE_TYPE); if (deviceTypeStart==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceTypeStart+=strlen(DS_TAG_DEVICE_TYPE); deviceTypeEnd = findString(deviceTypeStart, contentEnd, DS_TAG_DEVICE_TYPE_END); if (deviceTypeEnd==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } memcpy(&deviceType, deviceTypeStart, sizeof(ds_device_type)); // parse the device name if (deviceType == DS_DEVICE_OPENCL_DEVICE) { deviceNameStart = findString(dataStart, contentEnd, DS_TAG_DEVICE_NAME); if (deviceNameStart==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceNameStart+=strlen(DS_TAG_DEVICE_NAME); deviceNameEnd = findString(deviceNameStart, contentEnd, DS_TAG_DEVICE_NAME_END); if (deviceNameEnd==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceDriverStart = findString(dataStart, contentEnd, DS_TAG_DEVICE_DRIVER_VERSION); if (deviceDriverStart==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceDriverStart+=strlen(DS_TAG_DEVICE_DRIVER_VERSION); deviceDriverEnd = findString(deviceDriverStart, contentEnd, DS_TAG_DEVICE_DRIVER_VERSION_END); if (deviceDriverEnd ==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } // check if this device is on the system for (i = 0; i < profile->numDevices; i++) { if (profile->devices[i].type == DS_DEVICE_OPENCL_DEVICE) { size_t actualDeviceNameLength; size_t driverVersionLength; actualDeviceNameLength = strlen(profile->devices[i].oclDeviceName); driverVersionLength = strlen(profile->devices[i].oclDriverVersion); if (actualDeviceNameLength == (deviceNameEnd - deviceNameStart) && driverVersionLength == (deviceDriverEnd - deviceDriverStart) && strncmp(profile->devices[i].oclDeviceName, deviceNameStart, actualDeviceNameLength)==0 && strncmp(profile->devices[i].oclDriverVersion, deviceDriverStart, driverVersionLength)==0) { deviceScoreStart = findString(dataStart, contentEnd, DS_TAG_SCORE); if (deviceNameStart==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceScoreStart+=strlen(DS_TAG_SCORE); deviceScoreEnd = findString(deviceScoreStart, contentEnd, DS_TAG_SCORE_END); status = deserializer(profile->devices+i, (const unsigned char*)deviceScoreStart, deviceScoreEnd-deviceScoreStart); if (status != DS_SUCCESS) { goto cleanup; } } } } } else if (deviceType == DS_DEVICE_NATIVE_CPU) { for (i = 0; i < profile->numDevices; i++) { if (profile->devices[i].type == DS_DEVICE_NATIVE_CPU) { deviceScoreStart = findString(dataStart, contentEnd, DS_TAG_SCORE); if (deviceScoreStart==NULL) { status = DS_PROFILE_FILE_ERROR; goto cleanup; } deviceScoreStart+=strlen(DS_TAG_SCORE); deviceScoreEnd = findString(deviceScoreStart, contentEnd, DS_TAG_SCORE_END); status = deserializer(profile->devices+i, (const unsigned char*)deviceScoreStart, deviceScoreEnd-deviceScoreStart); if (status != DS_SUCCESS) { goto cleanup; } } } } // skip over the current one to find the next device currentPosition = dataEnd+strlen(DS_TAG_DEVICE_END); } } cleanup: if (contentStart!=NULL) free(contentStart); return status; } static ds_status getNumDeviceWithEmptyScore(ds_profile* profile, unsigned int* num) { unsigned int i; if (profile == NULL || num==NULL) return DS_MEMORY_ERROR; *num=0; for (i = 0; i < profile->numDevices; i++) { if (profile->devices[i].score == NULL) { *num++; } } return DS_SUCCESS; } #endif #endif
1080228-arabicocr11
opencl/opencl_device_selection.h
C
asf20
18,730
#ifdef _WIN32 #include <Windows.h> #include <io.h> #else #include <sys/types.h> #include <unistd.h> #endif #include <float.h> #include "openclwrapper.h" #include "oclkernels.h" // for micro-benchmark #include "otsuthr.h" #include "thresholder.h" #ifdef USE_OPENCL #if ON_APPLE #define TIMESPEC mach_timespec #else #define TIMESPEC timespec #endif #include "opencl_device_selection.h" GPUEnv OpenclDevice::gpuEnv; #if USE_DEVICE_SELECTION bool OpenclDevice::deviceIsSelected = false; ds_device OpenclDevice::selectedDevice; #endif int OpenclDevice::isInited =0; struct tiff_transform { int vflip; /* if non-zero, image needs a vertical fip */ int hflip; /* if non-zero, image needs a horizontal flip */ int rotate; /* -1 -> counterclockwise 90-degree rotation, 0 -> no rotation 1 -> clockwise 90-degree rotation */ }; static struct tiff_transform tiff_orientation_transforms[] = { {0, 0, 0}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}, {0, 1, -1}, {0, 0, 1}, {0, 1, 1}, {0, 0, -1} }; static const l_int32 MAX_PAGES_IN_TIFF_FILE = 3000; cl_mem pixsCLBuffer, pixdCLBuffer, pixdCLIntermediate; //Morph operations buffers cl_mem pixThBuffer; //output from thresholdtopix calculation cl_int clStatus; KernelEnv rEnv; // substitute invalid characters in device name with _ void legalizeFileName( char *fileName) { //printf("fileName: %s\n", fileName); char *invalidChars = "/\?:*\"><| "; // space is valid but can cause headaches // for each invalid char for (int i = 0; i < strlen(invalidChars); i++) { char invalidStr[4]; invalidStr[0] = invalidChars[i]; invalidStr[1] = NULL; //printf("eliminating %s\n", invalidStr); //char *pos = strstr(fileName, invalidStr); // initial ./ is valid for present directory //if (*pos == '.') pos++; //if (*pos == '/') pos++; for ( char *pos = strstr(fileName, invalidStr); pos != NULL; pos = strstr(pos+1, invalidStr)) { //printf("\tfound: %s, ", pos); pos[0] = '_'; //printf("fileName: %s\n", fileName); } } } void populateGPUEnvFromDevice( GPUEnv *gpuInfo, cl_device_id device ) { //printf("[DS] populateGPUEnvFromDevice\n"); size_t size; gpuInfo->mnIsUserCreated = 1; // device gpuInfo->mpDevID = device; gpuInfo->mpArryDevsID = new cl_device_id[1]; gpuInfo->mpArryDevsID[0] = gpuInfo->mpDevID; clStatus = clGetDeviceInfo(gpuInfo->mpDevID, CL_DEVICE_TYPE , sizeof(cl_device_type), (void *) &gpuInfo->mDevType , &size); CHECK_OPENCL( clStatus, "populateGPUEnv::getDeviceInfo(TYPE)"); // platform clStatus = clGetDeviceInfo(gpuInfo->mpDevID, CL_DEVICE_PLATFORM , sizeof(cl_platform_id), (void *) &gpuInfo->mpPlatformID , &size); CHECK_OPENCL( clStatus, "populateGPUEnv::getDeviceInfo(PLATFORM)"); // context cl_context_properties props[3]; props[0] = CL_CONTEXT_PLATFORM; props[1] = (cl_context_properties) gpuInfo->mpPlatformID; props[2] = 0; gpuInfo->mpContext = clCreateContext(props, 1, &gpuInfo->mpDevID, NULL, NULL, &clStatus); CHECK_OPENCL( clStatus, "populateGPUEnv::createContext"); // queue cl_command_queue_properties queueProperties = 0; gpuInfo->mpCmdQueue = clCreateCommandQueue( gpuInfo->mpContext, gpuInfo->mpDevID, queueProperties, &clStatus ); CHECK_OPENCL( clStatus, "populateGPUEnv::createCommandQueue"); } int OpenclDevice::LoadOpencl() { #ifdef WIN32 HINSTANCE HOpenclDll = NULL; void * OpenclDll = NULL; //fprintf(stderr, " LoadOpenclDllxx... \n"); OpenclDll = static_cast<HINSTANCE>( HOpenclDll ); OpenclDll = LoadLibrary( "openCL.dll" ); if ( !static_cast<HINSTANCE>( OpenclDll ) ) { fprintf(stderr, "[OD] Load opencl.dll failed!\n"); FreeLibrary( static_cast<HINSTANCE>( OpenclDll ) ); return 0; } fprintf(stderr, "[OD] Load opencl.dll successful!\n"); #endif return 1; } int OpenclDevice::SetKernelEnv( KernelEnv *envInfo ) { envInfo->mpkContext = gpuEnv.mpContext; envInfo->mpkCmdQueue = gpuEnv.mpCmdQueue; envInfo->mpkProgram = gpuEnv.mpArryPrograms[0]; return 1; } cl_mem allocateZeroCopyBuffer(KernelEnv rEnv, l_uint32 *hostbuffer, size_t nElements, cl_mem_flags flags, cl_int *pStatus) { cl_mem membuffer = clCreateBuffer( rEnv.mpkContext, (cl_mem_flags) (flags), nElements * sizeof(l_uint32), hostbuffer, pStatus); return membuffer; } PIX* mapOutputCLBuffer(KernelEnv rEnv, cl_mem clbuffer, PIX* pixd, PIX* pixs, int elements, cl_mem_flags flags, bool memcopy = false, bool sync = true) { PROCNAME("mapOutputCLBuffer"); if (!pixd) { if (memcopy) { if ((pixd = pixCreateTemplate(pixs)) == NULL) (PIX *)ERROR_PTR("pixd not made", procName, NULL); } else { if ((pixd = pixCreateHeader(pixGetWidth(pixs), pixGetHeight(pixs), pixGetDepth(pixs))) == NULL) (PIX *)ERROR_PTR("pixd not made", procName, NULL); } } l_uint32 *pValues = (l_uint32 *)clEnqueueMapBuffer(rEnv.mpkCmdQueue, clbuffer, CL_TRUE, flags, 0, elements * sizeof(l_uint32), 0, NULL, NULL, NULL ); if (memcopy) { memcpy(pixGetData(pixd), pValues, elements * sizeof(l_uint32)); } else { pixSetData(pixd, pValues); } clEnqueueUnmapMemObject(rEnv.mpkCmdQueue,clbuffer,pValues,0,NULL,NULL); if (sync) { clFinish( rEnv.mpkCmdQueue ); } return pixd; } cl_mem allocateIntBuffer( KernelEnv rEnv, const l_uint32 *_pValues, size_t nElements, cl_int *pStatus , bool sync = false) { cl_mem xValues = clCreateBuffer( rEnv.mpkContext, (cl_mem_flags) (CL_MEM_READ_WRITE), nElements * sizeof(l_int32), NULL, pStatus); if (_pValues != NULL) { l_int32 *pValues = (l_int32 *)clEnqueueMapBuffer( rEnv.mpkCmdQueue, xValues, CL_TRUE, CL_MAP_WRITE, 0, nElements * sizeof(l_int32), 0, NULL, NULL, NULL ); memcpy(pValues, _pValues, nElements * sizeof(l_int32)); clEnqueueUnmapMemObject(rEnv.mpkCmdQueue,xValues,pValues,0,NULL,NULL); if (sync) clFinish( rEnv.mpkCmdQueue ); } return xValues; } int OpenclDevice::InitOpenclRunEnv( GPUEnv *gpuInfo ) { size_t length; cl_int clStatus; cl_uint numPlatforms, numDevices; cl_platform_id *platforms; cl_context_properties cps[3]; char platformName[256]; unsigned int i; // Have a look at the available platforms. if ( !gpuInfo->mnIsUserCreated ) { clStatus = clGetPlatformIDs( 0, NULL, &numPlatforms ); if ( clStatus != CL_SUCCESS ) { return 1; } gpuInfo->mpPlatformID = NULL; if ( 0 < numPlatforms ) { platforms = (cl_platform_id*) malloc( numPlatforms * sizeof( cl_platform_id ) ); if ( platforms == (cl_platform_id*) NULL ) { return 1; } clStatus = clGetPlatformIDs( numPlatforms, platforms, NULL ); if ( clStatus != CL_SUCCESS ) { return 1; } for ( i = 0; i < numPlatforms; i++ ) { clStatus = clGetPlatformInfo( platforms[i], CL_PLATFORM_VENDOR, sizeof( platformName ), platformName, NULL ); if ( clStatus != CL_SUCCESS ) { return 1; } gpuInfo->mpPlatformID = platforms[i]; //if (!strcmp(platformName, "Intel(R) Coporation")) //if( !strcmp( platformName, "Advanced Micro Devices, Inc." )) { gpuInfo->mpPlatformID = platforms[i]; if ( getenv("SC_OPENCLCPU") ) { clStatus = clGetDeviceIDs(gpuInfo->mpPlatformID, // platform CL_DEVICE_TYPE_CPU, // device_type for CPU device 0, // num_entries NULL, // devices &numDevices); printf("Selecting OpenCL device: CPU (a)\n"); } else { clStatus = clGetDeviceIDs(gpuInfo->mpPlatformID, // platform CL_DEVICE_TYPE_GPU, // device_type for GPU device 0, // num_entries NULL, // devices &numDevices); printf("Selecting OpenCL device: GPU (a)\n"); } if ( clStatus != CL_SUCCESS ) continue; if ( numDevices ) break; } } if ( clStatus != CL_SUCCESS ) return 1; free( platforms ); } if ( NULL == gpuInfo->mpPlatformID ) return 1; // Use available platform. cps[0] = CL_CONTEXT_PLATFORM; cps[1] = (cl_context_properties) gpuInfo->mpPlatformID; cps[2] = 0; // Set device type for OpenCL if ( getenv("SC_OPENCLCPU") ) { gpuInfo->mDevType = CL_DEVICE_TYPE_CPU; printf("Selecting OpenCL device: CPU (b)\n"); } else { gpuInfo->mDevType = CL_DEVICE_TYPE_GPU; printf("Selecting OpenCL device: GPU (b)\n"); } gpuInfo->mpContext = clCreateContextFromType( cps, gpuInfo->mDevType, NULL, NULL, &clStatus ); if ( ( gpuInfo->mpContext == (cl_context) NULL) || ( clStatus != CL_SUCCESS ) ) { gpuInfo->mDevType = CL_DEVICE_TYPE_CPU; gpuInfo->mpContext = clCreateContextFromType( cps, gpuInfo->mDevType, NULL, NULL, &clStatus ); printf("Selecting OpenCL device: CPU (c)\n"); } if ( ( gpuInfo->mpContext == (cl_context) NULL) || ( clStatus != CL_SUCCESS ) ) { gpuInfo->mDevType = CL_DEVICE_TYPE_DEFAULT; gpuInfo->mpContext = clCreateContextFromType( cps, gpuInfo->mDevType, NULL, NULL, &clStatus ); printf("Selecting OpenCL device: DEFAULT (c)\n"); } if ( ( gpuInfo->mpContext == (cl_context) NULL) || ( clStatus != CL_SUCCESS ) ) return 1; // Detect OpenCL devices. // First, get the size of device list data clStatus = clGetContextInfo( gpuInfo->mpContext, CL_CONTEXT_DEVICES, 0, NULL, &length ); if ( ( clStatus != CL_SUCCESS ) || ( length == 0 ) ) return 1; // Now allocate memory for device list based on the size we got earlier gpuInfo->mpArryDevsID = (cl_device_id*) malloc( length ); if ( gpuInfo->mpArryDevsID == (cl_device_id*) NULL ) return 1; // Now, get the device list data clStatus = clGetContextInfo( gpuInfo->mpContext, CL_CONTEXT_DEVICES, length, gpuInfo->mpArryDevsID, NULL ); if ( clStatus != CL_SUCCESS ) return 1; // Create OpenCL command queue. gpuInfo->mpCmdQueue = clCreateCommandQueue( gpuInfo->mpContext, gpuInfo->mpArryDevsID[0], 0, &clStatus ); if ( clStatus != CL_SUCCESS ) return 1; } clStatus = clGetCommandQueueInfo( gpuInfo->mpCmdQueue, CL_QUEUE_THREAD_HANDLE_AMD, 0, NULL, NULL ); // Check device extensions for double type size_t aDevExtInfoSize = 0; clStatus = clGetDeviceInfo( gpuInfo->mpArryDevsID[0], CL_DEVICE_EXTENSIONS, 0, NULL, &aDevExtInfoSize ); CHECK_OPENCL( clStatus, "clGetDeviceInfo" ); char *aExtInfo = new char[aDevExtInfoSize]; clStatus = clGetDeviceInfo( gpuInfo->mpArryDevsID[0], CL_DEVICE_EXTENSIONS, sizeof(char) * aDevExtInfoSize, aExtInfo, NULL); CHECK_OPENCL( clStatus, "clGetDeviceInfo" ); gpuInfo->mnKhrFp64Flag = 0; gpuInfo->mnAmdFp64Flag = 0; if ( strstr( aExtInfo, "cl_khr_fp64" ) ) { gpuInfo->mnKhrFp64Flag = 1; } else { // Check if cl_amd_fp64 extension is supported if ( strstr( aExtInfo, "cl_amd_fp64" ) ) gpuInfo->mnAmdFp64Flag = 1; } delete []aExtInfo; return 0; } void OpenclDevice::releaseMorphCLBuffers() { if (pixdCLIntermediate != NULL) clReleaseMemObject(pixdCLIntermediate); if (pixsCLBuffer != NULL) clReleaseMemObject(pixsCLBuffer); if (pixdCLBuffer != NULL) clReleaseMemObject(pixdCLBuffer); if (pixThBuffer != NULL) clReleaseMemObject(pixThBuffer); } int OpenclDevice::initMorphCLAllocations(l_int32 wpl, l_int32 h, PIX* pixs) { SetKernelEnv( &rEnv ); if (pixThBuffer != NULL) { pixsCLBuffer = allocateZeroCopyBuffer(rEnv, NULL, wpl*h, CL_MEM_ALLOC_HOST_PTR, &clStatus); //Get the output from ThresholdToPix operation clStatus = clEnqueueCopyBuffer(rEnv.mpkCmdQueue, pixThBuffer, pixsCLBuffer, 0, 0, sizeof(l_uint32) * wpl*h, 0, NULL, NULL); } else { //Get data from the source image l_uint32* srcdata = (l_uint32*) malloc(wpl*h*sizeof(l_uint32)); memcpy(srcdata, pixGetData(pixs), wpl*h*sizeof(l_uint32)); pixsCLBuffer = allocateZeroCopyBuffer(rEnv, srcdata, wpl*h, CL_MEM_USE_HOST_PTR, &clStatus); } pixdCLBuffer = allocateZeroCopyBuffer(rEnv, NULL, wpl*h, CL_MEM_ALLOC_HOST_PTR, &clStatus); pixdCLIntermediate = allocateZeroCopyBuffer(rEnv, NULL, wpl*h, CL_MEM_ALLOC_HOST_PTR, &clStatus); return (int)clStatus; } int OpenclDevice::InitEnv() { //PERF_COUNT_START("OD::InitEnv") // printf("[OD] OpenclDevice::InitEnv()\n"); #ifdef SAL_WIN32 while( 1 ) { if( 1 == LoadOpencl() ) break; } PERF_COUNT_SUB("LoadOpencl") #endif // sets up environment, compiles programs #if USE_DEVICE_SELECTION InitOpenclRunEnv_DeviceSelection( 0 ); //PERF_COUNT_SUB("called InitOpenclRunEnv_DS") #else // init according to device InitOpenclRunEnv( 0 ); #endif //PERF_COUNT_END return 1; } int OpenclDevice::ReleaseOpenclRunEnv() { ReleaseOpenclEnv( &gpuEnv ); #ifdef SAL_WIN32 FreeOpenclDll(); #endif return 1; } inline int OpenclDevice::AddKernelConfig( int kCount, const char *kName ) { if ( kCount < 1 ) fprintf(stderr,"Error: ( KCount < 1 ) AddKernelConfig\n" ); strcpy( gpuEnv.mArrykernelNames[kCount-1], kName ); gpuEnv.mnKernelCount++; return 0; } int OpenclDevice::RegistOpenclKernel() { if ( !gpuEnv.mnIsUserCreated ) memset( &gpuEnv, 0, sizeof(gpuEnv) ); gpuEnv.mnFileCount = 0; //argc; gpuEnv.mnKernelCount = 0UL; AddKernelConfig( 1, (const char*) "oclAverageSub1" ); return 0; } int OpenclDevice::InitOpenclRunEnv( int argc ) { int status = 0; if ( MAX_CLKERNEL_NUM <= 0 ) { return 1; } if ( ( argc > MAX_CLFILE_NUM ) || ( argc < 0 ) ) return 1; if ( !isInited ) { RegistOpenclKernel(); //initialize devices, context, comand_queue status = InitOpenclRunEnv( &gpuEnv ); if ( status ) { fprintf(stderr,"init_opencl_env failed.\n"); return 1; } fprintf(stderr,"init_opencl_env successed.\n"); //initialize program, kernelName, kernelCount if( getenv( "SC_FLOAT" ) ) { gpuEnv.mnKhrFp64Flag = 0; gpuEnv.mnAmdFp64Flag = 0; } if( gpuEnv.mnKhrFp64Flag ) { fprintf(stderr,"----use khr double type in kernel----\n"); status = CompileKernelFile( &gpuEnv, "-D KHR_DP_EXTENSION -Dfp_t=double -Dfp_t4=double4 -Dfp_t16=double16" ); } else if( gpuEnv.mnAmdFp64Flag ) { fprintf(stderr,"----use amd double type in kernel----\n"); status = CompileKernelFile( &gpuEnv, "-D AMD_DP_EXTENSION -Dfp_t=double -Dfp_t4=double4 -Dfp_t16=double16" ); } else { fprintf(stderr,"----use float type in kernel----\n"); status = CompileKernelFile( &gpuEnv, "-Dfp_t=float -Dfp_t4=float4 -Dfp_t16=float16" ); } if ( status == 0 || gpuEnv.mnKernelCount == 0 ) { fprintf(stderr,"CompileKernelFile failed.\n"); return 1; } fprintf(stderr,"CompileKernelFile successed.\n"); isInited = 1; } return 0; } int OpenclDevice::InitOpenclRunEnv_DeviceSelection( int argc ) { //PERF_COUNT_START("InitOpenclRunEnv_DS") #if USE_DEVICE_SELECTION if (!isInited) { // after programs compiled, selects best device //printf("[DS] InitOpenclRunEnv_DS::Calling performDeviceSelection()\n"); ds_device bestDevice_DS = getDeviceSelection( ); //PERF_COUNT_SUB("called getDeviceSelection()") cl_device_id bestDevice = bestDevice_DS.oclDeviceID; // overwrite global static GPUEnv with new device if (selectedDeviceIsOpenCL() ) { //printf("[DS] InitOpenclRunEnv_DS::Calling populateGPUEnvFromDevice() for selected device\n"); populateGPUEnvFromDevice( &gpuEnv, bestDevice ); gpuEnv.mnFileCount = 0; //argc; gpuEnv.mnKernelCount = 0UL; //PERF_COUNT_SUB("populate gpuEnv") CompileKernelFile(&gpuEnv, ""); //PERF_COUNT_SUB("CompileKernelFile") } else { //printf("[DS] InitOpenclRunEnv_DS::Skipping populateGPUEnvFromDevice() b/c native cpu selected\n"); } isInited = 1; } #endif //PERF_COUNT_END return 0; } OpenclDevice::OpenclDevice() { //InitEnv(); } OpenclDevice::~OpenclDevice() { //ReleaseOpenclRunEnv(); } int OpenclDevice::ReleaseOpenclEnv( GPUEnv *gpuInfo ) { int i = 0; int clStatus = 0; if ( !isInited ) { return 1; } for ( i = 0; i < gpuEnv.mnFileCount; i++ ) { if ( gpuEnv.mpArryPrograms[i] ) { clStatus = clReleaseProgram( gpuEnv.mpArryPrograms[i] ); CHECK_OPENCL( clStatus, "clReleaseProgram" ); gpuEnv.mpArryPrograms[i] = NULL; } } if ( gpuEnv.mpCmdQueue ) { clReleaseCommandQueue( gpuEnv.mpCmdQueue ); gpuEnv.mpCmdQueue = NULL; } if ( gpuEnv.mpContext ) { clReleaseContext( gpuEnv.mpContext ); gpuEnv.mpContext = NULL; } isInited = 0; gpuInfo->mnIsUserCreated = 0; free( gpuInfo->mpArryDevsID ); return 1; } int OpenclDevice::BinaryGenerated( const char * clFileName, FILE ** fhandle ) { unsigned int i = 0; cl_int clStatus; int status = 0; char *str = NULL; FILE *fd = NULL; cl_uint numDevices=0; if ( getenv("SC_OPENCLCPU") ) { clStatus = clGetDeviceIDs(gpuEnv.mpPlatformID, // platform CL_DEVICE_TYPE_CPU, // device_type for CPU device 0, // num_entries NULL, // devices ID &numDevices); } else { clStatus = clGetDeviceIDs(gpuEnv.mpPlatformID, // platform CL_DEVICE_TYPE_GPU, // device_type for GPU device 0, // num_entries NULL, // devices ID &numDevices); } CHECK_OPENCL( clStatus, "clGetDeviceIDs" ); for ( i = 0; i < numDevices; i++ ) { char fileName[256] = { 0 }, cl_name[128] = { 0 }; if ( gpuEnv.mpArryDevsID[i] != 0 ) { char deviceName[1024]; clStatus = clGetDeviceInfo( gpuEnv.mpArryDevsID[i], CL_DEVICE_NAME, sizeof(deviceName), deviceName, NULL ); CHECK_OPENCL( clStatus, "clGetDeviceInfo" ); str = (char*) strstr( clFileName, (char*) ".cl" ); memcpy( cl_name, clFileName, str - clFileName ); cl_name[str - clFileName] = '\0'; sprintf( fileName, "%s-%s.bin", cl_name, deviceName ); legalizeFileName(fileName); fd = fopen( fileName, "rb" ); status = ( fd != NULL ) ? 1 : 0; } } if ( fd != NULL ) { *fhandle = fd; } return status; } int OpenclDevice::CachedOfKernerPrg( const GPUEnv *gpuEnvCached, const char * clFileName ) { int i; for ( i = 0; i < gpuEnvCached->mnFileCount; i++ ) { if ( strcasecmp( gpuEnvCached->mArryKnelSrcFile[i], clFileName ) == 0 ) { if ( gpuEnvCached->mpArryPrograms[i] != NULL ) { return 1; } } } return 0; } int OpenclDevice::WriteBinaryToFile( const char* fileName, const char* birary, size_t numBytes ) { FILE *output = NULL; output = fopen( fileName, "wb" ); if ( output == NULL ) { return 0; } fwrite( birary, sizeof(char), numBytes, output ); fclose( output ); return 1; } int OpenclDevice::GeneratBinFromKernelSource( cl_program program, const char * clFileName ) { unsigned int i = 0; cl_int clStatus; size_t *binarySizes, numDevices; cl_device_id *mpArryDevsID; char **binaries, *str = NULL; clStatus = clGetProgramInfo( program, CL_PROGRAM_NUM_DEVICES, sizeof(numDevices), &numDevices, NULL ); CHECK_OPENCL( clStatus, "clGetProgramInfo" ); mpArryDevsID = (cl_device_id*) malloc( sizeof(cl_device_id) * numDevices ); if ( mpArryDevsID == NULL ) { return 0; } /* grab the handles to all of the devices in the program. */ clStatus = clGetProgramInfo( program, CL_PROGRAM_DEVICES, sizeof(cl_device_id) * numDevices, mpArryDevsID, NULL ); CHECK_OPENCL( clStatus, "clGetProgramInfo" ); /* figure out the sizes of each of the binaries. */ binarySizes = (size_t*) malloc( sizeof(size_t) * numDevices ); clStatus = clGetProgramInfo( program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t) * numDevices, binarySizes, NULL ); CHECK_OPENCL( clStatus, "clGetProgramInfo" ); /* copy over all of the generated binaries. */ binaries = (char**) malloc( sizeof(char *) * numDevices ); if ( binaries == NULL ) { return 0; } for ( i = 0; i < numDevices; i++ ) { if ( binarySizes[i] != 0 ) { binaries[i] = (char*) malloc( sizeof(char) * binarySizes[i] ); if ( binaries[i] == NULL ) { // cleanup all memory allocated so far for(int cleanupIndex = 0; cleanupIndex < i; ++cleanupIndex) { free(binaries[cleanupIndex]); } // cleanup binary array free(binaries); return 0; } } else { binaries[i] = NULL; } } clStatus = clGetProgramInfo( program, CL_PROGRAM_BINARIES, sizeof(char *) * numDevices, binaries, NULL ); CHECK_OPENCL(clStatus,"clGetProgramInfo"); /* dump out each binary into its own separate file. */ for ( i = 0; i < numDevices; i++ ) { char fileName[256] = { 0 }, cl_name[128] = { 0 }; if ( binarySizes[i] != 0 ) { char deviceName[1024]; clStatus = clGetDeviceInfo(mpArryDevsID[i], CL_DEVICE_NAME, sizeof(deviceName), deviceName, NULL); CHECK_OPENCL( clStatus, "clGetDeviceInfo" ); str = (char*) strstr( clFileName, (char*) ".cl" ); memcpy( cl_name, clFileName, str - clFileName ); cl_name[str - clFileName] = '\0'; sprintf( fileName, "%s-%s.bin", cl_name, deviceName ); legalizeFileName(fileName); if ( !WriteBinaryToFile( fileName, binaries[i], binarySizes[i] ) ) { printf("[OD] write binary[%s] failed\n", fileName); return 0; } //else printf("[OD] write binary[%s] succesfully\n", fileName); } } // Release all resouces and memory for ( i = 0; i < numDevices; i++ ) { if ( binaries[i] != NULL ) { free( binaries[i] ); binaries[i] = NULL; } } if ( binaries != NULL ) { free( binaries ); binaries = NULL; } if ( binarySizes != NULL ) { free( binarySizes ); binarySizes = NULL; } if ( mpArryDevsID != NULL ) { free( mpArryDevsID ); mpArryDevsID = NULL; } return 1; } void copyIntBuffer( KernelEnv rEnv, cl_mem xValues, const l_uint32 *_pValues, size_t nElements, cl_int *pStatus ) { l_int32 *pValues = (l_int32 *)clEnqueueMapBuffer( rEnv.mpkCmdQueue, xValues, CL_TRUE, CL_MAP_WRITE, 0, nElements * sizeof(l_int32), 0, NULL, NULL, NULL ); clFinish( rEnv.mpkCmdQueue ); if (_pValues != NULL) { for ( int i = 0; i < (int)nElements; i++ ) pValues[i] = (l_int32)_pValues[i]; } clEnqueueUnmapMemObject(rEnv.mpkCmdQueue,xValues,pValues,0,NULL,NULL); //clFinish( rEnv.mpkCmdQueue ); return; } int OpenclDevice::CompileKernelFile( GPUEnv *gpuInfo, const char *buildOption ) { //PERF_COUNT_START("CompileKernelFile") cl_int clStatus = 0; size_t length; char *buildLog = NULL, *binary; const char *source; size_t source_size[1]; int b_error, binary_status, binaryExisted, idx; size_t numDevices; cl_device_id *mpArryDevsID; FILE *fd, *fd1; const char* filename = "kernel.cl"; //fprintf(stderr, "[OD] CompileKernelFile ... \n"); if ( CachedOfKernerPrg(gpuInfo, filename) == 1 ) { return 1; } idx = gpuInfo->mnFileCount; source = kernel_src; source_size[0] = strlen( source ); binaryExisted = 0; binaryExisted = BinaryGenerated( filename, &fd ); // don't check for binary during microbenchmark //PERF_COUNT_SUB("BinaryGenerated") if ( binaryExisted == 1 ) { clStatus = clGetContextInfo( gpuInfo->mpContext, CL_CONTEXT_NUM_DEVICES, sizeof(numDevices), &numDevices, NULL ); CHECK_OPENCL( clStatus, "clGetContextInfo" ); mpArryDevsID = (cl_device_id*) malloc( sizeof(cl_device_id) * numDevices ); if ( mpArryDevsID == NULL ) { return 0; } //PERF_COUNT_SUB("get numDevices") b_error = 0; length = 0; b_error |= fseek( fd, 0, SEEK_END ) < 0; b_error |= ( length = ftell(fd) ) <= 0; b_error |= fseek( fd, 0, SEEK_SET ) < 0; if ( b_error ) { return 0; } binary = (char*) malloc( length + 2 ); if ( !binary ) { return 0; } memset( binary, 0, length + 2 ); b_error |= fread( binary, 1, length, fd ) != length; fclose( fd ); //PERF_COUNT_SUB("read file") fd = NULL; // grab the handles to all of the devices in the context. clStatus = clGetContextInfo( gpuInfo->mpContext, CL_CONTEXT_DEVICES, sizeof( cl_device_id ) * numDevices, mpArryDevsID, NULL ); CHECK_OPENCL( clStatus, "clGetContextInfo" ); //PERF_COUNT_SUB("get devices") //fprintf(stderr, "[OD] Create kernel from binary\n"); gpuInfo->mpArryPrograms[idx] = clCreateProgramWithBinary( gpuInfo->mpContext,numDevices, mpArryDevsID, &length, (const unsigned char**) &binary, &binary_status, &clStatus ); CHECK_OPENCL( clStatus, "clCreateProgramWithBinary" ); //PERF_COUNT_SUB("clCreateProgramWithBinary") free( binary ); free( mpArryDevsID ); mpArryDevsID = NULL; //PERF_COUNT_SUB("binaryExisted") } else { // create a CL program using the kernel source //fprintf(stderr, "[OD] Create kernel from source\n"); gpuInfo->mpArryPrograms[idx] = clCreateProgramWithSource( gpuInfo->mpContext, 1, &source, source_size, &clStatus); CHECK_OPENCL( clStatus, "clCreateProgramWithSource" ); //PERF_COUNT_SUB("!binaryExisted") } if ( gpuInfo->mpArryPrograms[idx] == (cl_program) NULL ) { return 0; } //char options[512]; // create a cl program executable for all the devices specified //printf("[OD] BuildProgram.\n"); PERF_COUNT_START("OD::CompileKernel::clBuildProgram") if (!gpuInfo->mnIsUserCreated) { clStatus = clBuildProgram(gpuInfo->mpArryPrograms[idx], 1, gpuInfo->mpArryDevsID, buildOption, NULL, NULL); //PERF_COUNT_SUB("clBuildProgram notUserCreated") } else { clStatus = clBuildProgram(gpuInfo->mpArryPrograms[idx], 1, &(gpuInfo->mpDevID), buildOption, NULL, NULL); //PERF_COUNT_SUB("clBuildProgram isUserCreated") } PERF_COUNT_END if ( clStatus != CL_SUCCESS ) { printf ("BuildProgram error!\n"); if ( !gpuInfo->mnIsUserCreated ) { clStatus = clGetProgramBuildInfo( gpuInfo->mpArryPrograms[idx], gpuInfo->mpArryDevsID[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &length ); } else { clStatus = clGetProgramBuildInfo( gpuInfo->mpArryPrograms[idx], gpuInfo->mpDevID, CL_PROGRAM_BUILD_LOG, 0, NULL, &length); } if ( clStatus != CL_SUCCESS ) { printf("opencl create build log fail\n"); return 0; } buildLog = (char*) malloc( length ); if ( buildLog == (char*) NULL ) { return 0; } if ( !gpuInfo->mnIsUserCreated ) { clStatus = clGetProgramBuildInfo( gpuInfo->mpArryPrograms[idx], gpuInfo->mpArryDevsID[0], CL_PROGRAM_BUILD_LOG, length, buildLog, &length ); } else { clStatus = clGetProgramBuildInfo( gpuInfo->mpArryPrograms[idx], gpuInfo->mpDevID, CL_PROGRAM_BUILD_LOG, length, buildLog, &length ); } if ( clStatus != CL_SUCCESS ) { printf("opencl program build info fail\n"); return 0; } fd1 = fopen( "kernel-build.log", "w+" ); if ( fd1 != NULL ) { fwrite( buildLog, sizeof(char), length, fd1 ); fclose( fd1 ); } free( buildLog ); //PERF_COUNT_SUB("build error log") return 0; } strcpy( gpuInfo->mArryKnelSrcFile[idx], filename ); //PERF_COUNT_SUB("strcpy") if ( binaryExisted == 0 ) { GeneratBinFromKernelSource( gpuInfo->mpArryPrograms[idx], filename ); PERF_COUNT_SUB("GenerateBinFromKernelSource") } gpuInfo->mnFileCount += 1; //PERF_COUNT_END return 1; } l_uint32* OpenclDevice::pixReadFromTiffKernel(l_uint32 *tiffdata,l_int32 w,l_int32 h,l_int32 wpl,l_uint32 *line) { PERF_COUNT_START("pixReadFromTiffKernel") cl_int clStatus; KernelEnv rEnv; size_t globalThreads[2]; size_t localThreads[2]; int gsize; cl_mem valuesCl; cl_mem outputCl; //global and local work dimensions for Horizontal pass gsize = (w + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; localThreads[0] = GROUPSIZE_X; localThreads[1] = GROUPSIZE_Y; SetKernelEnv( &rEnv ); l_uint32 *pResult = (l_uint32 *)malloc(w*h * sizeof(l_uint32)); rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "composeRGBPixel", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel"); //Allocate input and output OCL buffers valuesCl = allocateZeroCopyBuffer(rEnv, tiffdata, w*h, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, &clStatus); outputCl = allocateZeroCopyBuffer(rEnv, pResult, w*h, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, &clStatus); //Kernel arguments clStatus = clSetKernelArg( rEnv.mpkKernel, 0, sizeof(cl_mem), (void *)&valuesCl ); CHECK_OPENCL( clStatus, "clSetKernelArg"); clStatus = clSetKernelArg( rEnv.mpkKernel, 1, sizeof(w), (void *)&w ); CHECK_OPENCL( clStatus, "clSetKernelArg" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 2, sizeof(h), (void *)&h ); CHECK_OPENCL( clStatus, "clSetKernelArg" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 3, sizeof(wpl), (void *)&wpl ); CHECK_OPENCL( clStatus, "clSetKernelArg" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 4, sizeof(cl_mem), (void *)&outputCl ); CHECK_OPENCL( clStatus, "clSetKernelArg"); //Kernel enqueue PERF_COUNT_SUB("before") clStatus = clEnqueueNDRangeKernel( rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL ); CHECK_OPENCL( clStatus, "clEnqueueNDRangeKernel" ); /* map results back from gpu */ void *ptr = clEnqueueMapBuffer(rEnv.mpkCmdQueue, outputCl, CL_TRUE, CL_MAP_READ, 0, w*h * sizeof(l_uint32), 0, NULL, NULL, &clStatus); CHECK_OPENCL( clStatus, "clEnqueueMapBuffer outputCl"); clEnqueueUnmapMemObject(rEnv.mpkCmdQueue, outputCl, ptr, 0, NULL, NULL); //Sync clFinish( rEnv.mpkCmdQueue ); PERF_COUNT_SUB("kernel & map") PERF_COUNT_END return pResult; } PIX * OpenclDevice::pixReadTiffCl ( const char *filename, l_int32 n ) { PERF_COUNT_START("pixReadTiffCL") FILE *fp; PIX *pix; //printf("pixReadTiffCl file"); PROCNAME("pixReadTiff"); if (!filename) return (PIX *)ERROR_PTR("filename not defined", procName, NULL); if ((fp = fopenReadStream(filename)) == NULL) return (PIX *)ERROR_PTR("image file not found", procName, NULL); if ((pix = pixReadStreamTiffCl(fp, n)) == NULL) { fclose(fp); return (PIX *)ERROR_PTR("pix not read", procName, NULL); } fclose(fp); PERF_COUNT_END return pix; } TIFF * OpenclDevice::fopenTiffCl(FILE *fp, const char *modestring) { l_int32 fd; PROCNAME("fopenTiff"); if (!fp) return (TIFF *)ERROR_PTR("stream not opened", procName, NULL); if (!modestring) return (TIFF *)ERROR_PTR("modestring not defined", procName, NULL); if ((fd = fileno(fp)) < 0) return (TIFF *)ERROR_PTR("invalid file descriptor", procName, NULL); lseek(fd, 0, SEEK_SET); return TIFFFdOpen(fd, "TIFFstream", modestring); } l_int32 OpenclDevice::getTiffStreamResolutionCl(TIFF *tif, l_int32 *pxres, l_int32 *pyres) { l_uint16 resunit; l_int32 foundxres, foundyres; l_float32 fxres, fyres; PROCNAME("getTiffStreamResolution"); if (!tif) return ERROR_INT("tif not opened", procName, 1); if (!pxres || !pyres) return ERROR_INT("&xres and &yres not both defined", procName, 1); *pxres = *pyres = 0; TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &resunit); foundxres = TIFFGetField(tif, TIFFTAG_XRESOLUTION, &fxres); foundyres = TIFFGetField(tif, TIFFTAG_YRESOLUTION, &fyres); if (!foundxres && !foundyres) return 1; if (!foundxres && foundyres) fxres = fyres; else if (foundxres && !foundyres) fyres = fxres; if (resunit == RESUNIT_CENTIMETER) { /* convert to ppi */ *pxres = (l_int32)(2.54 * fxres + 0.5); *pyres = (l_int32)(2.54 * fyres + 0.5); } else { *pxres = (l_int32)fxres; *pyres = (l_int32)fyres; } return 0; } struct L_Memstream { l_uint8 *buffer; /* expands to hold data when written to; */ /* fixed size when read from. */ size_t bufsize; /* current size allocated when written to; */ /* fixed size of input data when read from. */ size_t offset; /* byte offset from beginning of buffer. */ size_t hw; /* high-water mark; max bytes in buffer. */ l_uint8 **poutdata; /* input param for writing; data goes here. */ size_t *poutsize; /* input param for writing; data size goes here. */ }; typedef struct L_Memstream L_MEMSTREAM; /* These are static functions for memory I/O */ static L_MEMSTREAM *memstreamCreateForRead(l_uint8 *indata, size_t pinsize); static L_MEMSTREAM *memstreamCreateForWrite(l_uint8 **poutdata, size_t *poutsize); static tsize_t tiffReadCallback(thandle_t handle, tdata_t data, tsize_t length); static tsize_t tiffWriteCallback(thandle_t handle, tdata_t data, tsize_t length); static toff_t tiffSeekCallback(thandle_t handle, toff_t offset, l_int32 whence); static l_int32 tiffCloseCallback(thandle_t handle); static toff_t tiffSizeCallback(thandle_t handle); static l_int32 tiffMapCallback(thandle_t handle, tdata_t *data, toff_t *length); static void tiffUnmapCallback(thandle_t handle, tdata_t data, toff_t length); static L_MEMSTREAM * memstreamCreateForRead(l_uint8 *indata, size_t insize) { L_MEMSTREAM *mstream; mstream = (L_MEMSTREAM *)CALLOC(1, sizeof(L_MEMSTREAM)); mstream->buffer = indata; /* handle to input data array */ mstream->bufsize = insize; /* amount of input data */ mstream->hw = insize; /* high-water mark fixed at input data size */ mstream->offset = 0; /* offset always starts at 0 */ return mstream; } static L_MEMSTREAM * memstreamCreateForWrite(l_uint8 **poutdata, size_t *poutsize) { L_MEMSTREAM *mstream; mstream = (L_MEMSTREAM *)CALLOC(1, sizeof(L_MEMSTREAM)); mstream->buffer = (l_uint8 *)CALLOC(8 * 1024, 1); mstream->bufsize = 8 * 1024; mstream->poutdata = poutdata; /* used only at end of write */ mstream->poutsize = poutsize; /* ditto */ mstream->hw = mstream->offset = 0; return mstream; } static tsize_t tiffReadCallback(thandle_t handle, tdata_t data, tsize_t length) { L_MEMSTREAM *mstream; size_t amount; mstream = (L_MEMSTREAM *)handle; amount = L_MIN((size_t)length, mstream->hw - mstream->offset); memcpy(data, mstream->buffer + mstream->offset, amount); mstream->offset += amount; return amount; } static tsize_t tiffWriteCallback(thandle_t handle, tdata_t data, tsize_t length) { L_MEMSTREAM *mstream; size_t newsize; /* reallocNew() uses calloc to initialize the array. * If malloc is used instead, for some of the encoding methods, * not all the data in 'bufsize' bytes in the buffer will * have been initialized by the end of the compression. */ mstream = (L_MEMSTREAM *)handle; if (mstream->offset + length > mstream->bufsize) { newsize = 2 * (mstream->offset + length); mstream->buffer = (l_uint8 *)reallocNew((void **)&mstream->buffer, mstream->offset, newsize); mstream->bufsize = newsize; } memcpy(mstream->buffer + mstream->offset, data, length); mstream->offset += length; mstream->hw = L_MAX(mstream->offset, mstream->hw); return length; } static toff_t tiffSeekCallback(thandle_t handle, toff_t offset, l_int32 whence) { L_MEMSTREAM *mstream; PROCNAME("tiffSeekCallback"); mstream = (L_MEMSTREAM *)handle; switch (whence) { case SEEK_SET: /* fprintf(stderr, "seek_set: offset = %d\n", offset); */ mstream->offset = offset; break; case SEEK_CUR: /* fprintf(stderr, "seek_cur: offset = %d\n", offset); */ mstream->offset += offset; break; case SEEK_END: /* fprintf(stderr, "seek end: hw = %d, offset = %d\n", mstream->hw, offset); */ mstream->offset = mstream->hw - offset; /* offset >= 0 */ break; default: return (toff_t)ERROR_INT("bad whence value", procName, mstream->offset); } return mstream->offset; } static l_int32 tiffCloseCallback(thandle_t handle) { L_MEMSTREAM *mstream; mstream = (L_MEMSTREAM *)handle; if (mstream->poutdata) { /* writing: save the output data */ *mstream->poutdata = mstream->buffer; *mstream->poutsize = mstream->hw; } FREE(mstream); /* never free the buffer! */ return 0; } static toff_t tiffSizeCallback(thandle_t handle) { L_MEMSTREAM *mstream; mstream = (L_MEMSTREAM *)handle; return mstream->hw; } static l_int32 tiffMapCallback(thandle_t handle, tdata_t *data, toff_t *length) { L_MEMSTREAM *mstream; mstream = (L_MEMSTREAM *)handle; *data = mstream->buffer; *length = mstream->hw; return 0; } static void tiffUnmapCallback(thandle_t handle, tdata_t data, toff_t length) { return; } /*! * fopenTiffMemstream() * * Input: filename (for error output; can be "") * operation ("w" for write, "r" for read) * &data (<return> written data) * &datasize (<return> size of written data) * Return: tiff (data structure, opened for write to memory) * * Notes: * (1) This wraps up a number of callbacks for either: * * reading from tiff in memory buffer --> pix * * writing from pix --> tiff in memory buffer * (2) After use, the memstream is automatically destroyed when * TIFFClose() is called. TIFFCleanup() doesn't free the memstream. */ static TIFF * fopenTiffMemstream(const char *filename, const char *operation, l_uint8 **pdata, size_t *pdatasize) { L_MEMSTREAM *mstream; PROCNAME("fopenTiffMemstream"); if (!filename) return (TIFF *)ERROR_PTR("filename not defined", procName, NULL); if (!operation) return (TIFF *)ERROR_PTR("operation not defined", procName, NULL); if (!pdata) return (TIFF *)ERROR_PTR("&data not defined", procName, NULL); if (!pdatasize) return (TIFF *)ERROR_PTR("&datasize not defined", procName, NULL); if (!strcmp(operation, "r") && !strcmp(operation, "w")) return (TIFF *)ERROR_PTR("operation not 'r' or 'w'}", procName, NULL); if (!strcmp(operation, "r")) mstream = memstreamCreateForRead(*pdata, *pdatasize); else mstream = memstreamCreateForWrite(pdata, pdatasize); return TIFFClientOpen(filename, operation, mstream, tiffReadCallback, tiffWriteCallback, tiffSeekCallback, tiffCloseCallback, tiffSizeCallback, tiffMapCallback, tiffUnmapCallback); } PIX * OpenclDevice::pixReadMemTiffCl(const l_uint8 *data,size_t size,l_int32 n) { l_int32 i, pagefound; PIX *pix; TIFF *tif; L_MEMSTREAM *memStream; PROCNAME("pixReadMemTiffCl"); if (!data) return (PIX *)ERROR_PTR("data pointer is NULL", procName, NULL); if ((tif = fopenTiffMemstream("", "r", (l_uint8 **)&data, &size)) == NULL) return (PIX *)ERROR_PTR("tif not opened", procName, NULL); pagefound = FALSE; pix = NULL; for (i = 0; i < MAX_PAGES_IN_TIFF_FILE; i++) { if (i == n) { pagefound = TRUE; if ((pix = pixReadFromTiffStreamCl(tif)) == NULL) { TIFFCleanup(tif); return (PIX *)ERROR_PTR("pix not read", procName, NULL); } break; } if (TIFFReadDirectory(tif) == 0) break; } if (pagefound == FALSE) { L_WARNING("tiff page %d not found", procName); TIFFCleanup(tif); return NULL; } TIFFCleanup(tif); return pix; } PIX * OpenclDevice::pixReadStreamTiffCl(FILE *fp, l_int32 n) { l_int32 i, pagefound; PIX *pix; TIFF *tif; PROCNAME("pixReadStreamTiff"); if (!fp) return (PIX *)ERROR_PTR("stream not defined", procName, NULL); if ((tif = fopenTiffCl(fp, "rb")) == NULL) return (PIX *)ERROR_PTR("tif not opened", procName, NULL); pagefound = FALSE; pix = NULL; for (i = 0; i < MAX_PAGES_IN_TIFF_FILE; i++) { if (i == n) { pagefound = TRUE; if ((pix = pixReadFromTiffStreamCl(tif)) == NULL) { TIFFCleanup(tif); return (PIX *)ERROR_PTR("pix not read", procName, NULL); } break; } if (TIFFReadDirectory(tif) == 0) break; } if (pagefound == FALSE) { L_WARNING("tiff page %d not found", procName, n); TIFFCleanup(tif); return NULL; } TIFFCleanup(tif); return pix; } static l_int32 getTiffCompressedFormat(l_uint16 tiffcomp) { l_int32 comptype; switch (tiffcomp) { case COMPRESSION_CCITTFAX4: comptype = IFF_TIFF_G4; break; case COMPRESSION_CCITTFAX3: comptype = IFF_TIFF_G3; break; case COMPRESSION_CCITTRLE: comptype = IFF_TIFF_RLE; break; case COMPRESSION_PACKBITS: comptype = IFF_TIFF_PACKBITS; break; case COMPRESSION_LZW: comptype = IFF_TIFF_LZW; break; case COMPRESSION_ADOBE_DEFLATE: comptype = IFF_TIFF_ZIP; break; default: comptype = IFF_TIFF; break; } return comptype; } void compare(l_uint32 *cpu, l_uint32 *gpu,int size) { for(int i=0;i<size;i++) { if(cpu[i]!=gpu[i]) { printf("\ndoesnot match\n"); return; } } printf("\nit matches\n"); } //OpenCL implementation of pixReadFromTiffStream. //Similar to the CPU implentation of pixReadFromTiffStream PIX * OpenclDevice::pixReadFromTiffStreamCl(TIFF *tif) { l_uint8 *linebuf, *data; l_uint16 spp, bps, bpp, tiffbpl, photometry, tiffcomp, orientation; l_uint16 *redmap, *greenmap, *bluemap; l_int32 d, wpl, bpl, comptype, i, ncolors; l_int32 xres, yres; l_uint32 w, h; l_uint32 *line, *tiffdata; PIX *pix; PIXCMAP *cmap; PROCNAME("pixReadFromTiffStream"); if (!tif) return (PIX *)ERROR_PTR("tif not defined", procName, NULL); TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp); bpp = bps * spp; if (bpp > 32) return (PIX *)ERROR_PTR("can't handle bpp > 32", procName, NULL); if (spp == 1) d = bps; else if (spp == 3 || spp == 4) d = 32; else return (PIX *)ERROR_PTR("spp not in set {1,3,4}", procName, NULL); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); tiffbpl = TIFFScanlineSize(tif); if ((pix = pixCreate(w, h, d)) == NULL) return (PIX *)ERROR_PTR("pix not made", procName, NULL); data = (l_uint8 *)pixGetData(pix); wpl = pixGetWpl(pix); bpl = 4 * wpl; if (spp == 1) { if ((linebuf = (l_uint8 *)CALLOC(tiffbpl + 1, sizeof(l_uint8))) == NULL) return (PIX *)ERROR_PTR("calloc fail for linebuf", procName, NULL); for (i = 0 ; i < h ; i++) { if (TIFFReadScanline(tif, linebuf, i, 0) < 0) { FREE(linebuf); pixDestroy(&pix); return (PIX *)ERROR_PTR("line read fail", procName, NULL); } memcpy((char *)data, (char *)linebuf, tiffbpl); data += bpl; } if (bps <= 8) pixEndianByteSwap(pix); else pixEndianTwoByteSwap(pix); FREE(linebuf); } else { if ((tiffdata = (l_uint32 *)CALLOC(w * h, sizeof(l_uint32))) == NULL) { pixDestroy(&pix); return (PIX *)ERROR_PTR("calloc fail for tiffdata", procName, NULL); } if (!TIFFReadRGBAImageOriented(tif, w, h, (uint32 *)tiffdata, ORIENTATION_TOPLEFT, 0)) { FREE(tiffdata); pixDestroy(&pix); return (PIX *)ERROR_PTR("failed to read tiffdata", procName, NULL); } line = pixGetData(pix); //Invoke the OpenCL kernel for pixReadFromTiff l_uint32* output_gpu=pixReadFromTiffKernel(tiffdata,w,h,wpl,line); pixSetData(pix, output_gpu); FREE(tiffdata); } if (getTiffStreamResolutionCl(tif, &xres, &yres) == 0) { pixSetXRes(pix, xres); pixSetYRes(pix, yres); } TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp); comptype = getTiffCompressedFormat(tiffcomp); pixSetInputFormat(pix, comptype); if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) { if ((cmap = pixcmapCreate(bps)) == NULL) { pixDestroy(&pix); return (PIX *)ERROR_PTR("cmap not made", procName, NULL); } ncolors = 1 << bps; for (i = 0; i < ncolors; i++) pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8, bluemap[i] >> 8); pixSetColormap(pix, cmap); } else { if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) { if (tiffcomp == COMPRESSION_CCITTFAX3 || tiffcomp == COMPRESSION_CCITTFAX4 || tiffcomp == COMPRESSION_CCITTRLE || tiffcomp == COMPRESSION_CCITTRLEW) { photometry = PHOTOMETRIC_MINISWHITE; } else photometry = PHOTOMETRIC_MINISBLACK; } if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) || (d == 8 && photometry == PHOTOMETRIC_MINISWHITE)) pixInvert(pix, pix); } if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) { if (orientation >= 1 && orientation <= 8) { struct tiff_transform *transform = &tiff_orientation_transforms[orientation - 1]; if (transform->vflip) pixFlipTB(pix, pix); if (transform->hflip) pixFlipLR(pix, pix); if (transform->rotate) { PIX *oldpix = pix; pix = pixRotate90(oldpix, transform->rotate); pixDestroy(&oldpix); } } } return pix; } //Morphology Dilate operation for 5x5 structuring element. Invokes the relevant OpenCL kernels cl_int pixDilateCL_55(l_int32 wpl, l_int32 h) { size_t globalThreads[2]; cl_mem pixtemp; cl_int status; int gsize; size_t localThreads[2]; //Horizontal pass gsize = (wpl*h + GROUPSIZE_HMORX - 1)/ GROUPSIZE_HMORX * GROUPSIZE_HMORX; globalThreads[0] = gsize; globalThreads[1] = GROUPSIZE_HMORY; localThreads[0] = GROUPSIZE_HMORX; localThreads[1] = GROUPSIZE_HMORY; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoDilateHor_5x5", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); //Swap source and dest buffers pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; //Vertical gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; localThreads[0] = GROUPSIZE_X; localThreads[1] = GROUPSIZE_Y; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoDilateVer_5x5", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); return status; } //Morphology Erode operation for 5x5 structuring element. Invokes the relevant OpenCL kernels cl_int pixErodeCL_55(l_int32 wpl, l_int32 h) { size_t globalThreads[2]; cl_mem pixtemp; cl_int status; int gsize; l_uint32 fwmask, lwmask; size_t localThreads[2]; lwmask = lmask32[32 - 2]; fwmask = rmask32[32 - 2]; //Horizontal pass gsize = (wpl*h + GROUPSIZE_HMORX - 1)/ GROUPSIZE_HMORX * GROUPSIZE_HMORX; globalThreads[0] = gsize; globalThreads[1] = GROUPSIZE_HMORY; localThreads[0] = GROUPSIZE_HMORX; localThreads[1] = GROUPSIZE_HMORY; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoErodeHor_5x5", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); //Swap source and dest buffers pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; //Vertical gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; localThreads[0] = GROUPSIZE_X; localThreads[1] = GROUPSIZE_Y; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoErodeVer_5x5", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(fwmask), (const void *)&fwmask); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(lwmask), (const void *)&lwmask); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); return status; } //Morphology Dilate operation. Invokes the relevant OpenCL kernels cl_int pixDilateCL(l_int32 hsize, l_int32 vsize, l_int32 wpl, l_int32 h) { l_int32 xp, yp, xn, yn; SEL* sel; size_t globalThreads[2]; cl_mem pixtemp; cl_int status; int gsize; size_t localThreads[2]; char isEven; OpenclDevice::SetKernelEnv( &rEnv ); if (hsize == 5 && vsize == 5) { //Specific case for 5x5 status = pixDilateCL_55(wpl, h); return status; } sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT); selFindMaxTranslations(sel, &xp, &yp, &xn, &yn); //global and local work dimensions for Horizontal pass gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; localThreads[0] = GROUPSIZE_X; localThreads[1] = GROUPSIZE_Y; if (xp > 31 || xn > 31) { //Generic case. rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoDilateHor", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(xp), (const void *)&xp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(xn), (const void *)&xn); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); if (yp > 0 || yn > 0) { pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; } } else if (xp > 0 || xn > 0 ) { //Specfic Horizontal pass kernel for half width < 32 rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoDilateHor_32word", &status ); isEven = (xp != xn); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(xp), (const void *)&xp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(isEven), (const void *)&isEven); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); if (yp > 0 || yn > 0) { pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; } } if (yp > 0 || yn > 0) { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoDilateVer", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(yp), (const void *)&yp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(yn), (const void *)&yn); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); } return status; } //Morphology Erode operation. Invokes the relevant OpenCL kernels cl_int pixErodeCL(l_int32 hsize, l_int32 vsize, l_uint32 wpl, l_uint32 h) { l_int32 xp, yp, xn, yn; SEL* sel; size_t globalThreads[2]; size_t localThreads[2]; cl_mem pixtemp; cl_int status; int gsize; char isAsymmetric = (MORPH_BC == ASYMMETRIC_MORPH_BC); l_uint32 rwmask, lwmask; char isEven; sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT); selFindMaxTranslations(sel, &xp, &yp, &xn, &yn); OpenclDevice::SetKernelEnv( &rEnv ); if (hsize == 5 && vsize == 5 && isAsymmetric) { //Specific kernel for 5x5 status = pixErodeCL_55(wpl, h); return status; } rwmask = rmask32[32 - (xp & 31)]; lwmask = lmask32[32 - (xn & 31)]; //global and local work dimensions for Horizontal pass gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; localThreads[0] = GROUPSIZE_X; localThreads[1] = GROUPSIZE_Y; //Horizontal Pass if (xp > 31 || xn > 31 ) { //Generic case. rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoErodeHor", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(xp), (const void *)&xp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(xn), (const void *)&xn); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 6, sizeof(isAsymmetric), (const void *)&isAsymmetric); status = clSetKernelArg(rEnv.mpkKernel, 7, sizeof(rwmask), (const void *)&rwmask); status = clSetKernelArg(rEnv.mpkKernel, 8, sizeof(lwmask), (const void *)&lwmask); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); if (yp > 0 || yn > 0) { pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; } } else if (xp > 0 || xn > 0) { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoErodeHor_32word", &status ); isEven = (xp != xn); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(xp), (const void *)&xp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(isAsymmetric), (const void *)&isAsymmetric); status = clSetKernelArg(rEnv.mpkKernel, 6, sizeof(rwmask), (const void *)&rwmask); status = clSetKernelArg(rEnv.mpkKernel, 7, sizeof(lwmask), (const void *)&lwmask); status = clSetKernelArg(rEnv.mpkKernel, 8, sizeof(isEven), (const void *)&isEven); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); if (yp > 0 || yn > 0) { pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; } } //Vertical Pass if (yp > 0 || yn > 0) { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "morphoErodeVer", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &pixsCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &pixdCLBuffer); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(yp), (const void *)&yp); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clSetKernelArg(rEnv.mpkKernel, 5, sizeof(isAsymmetric), (const void *)&isAsymmetric); status = clSetKernelArg(rEnv.mpkKernel, 6, sizeof(yn), (const void *)&yn); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); } return status; } // OpenCL implementation of Morphology Dilate //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixDilateBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy = false) { l_uint32 wpl, h; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); clStatus = pixDilateCL(hsize, vsize, wpl, h); if (reqDataCopy) { pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs, wpl*h, CL_MAP_READ, false); } return pixd; } // OpenCL implementation of Morphology Erode //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixErodeBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy = false) { l_uint32 wpl, h; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); clStatus = pixErodeCL(hsize, vsize, wpl, h); if (reqDataCopy) { pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs, wpl*h, CL_MAP_READ); } return pixd; } //Morphology Open operation. Invokes the relevant OpenCL kernels cl_int pixOpenCL(l_int32 hsize, l_int32 vsize, l_int32 wpl, l_int32 h) { cl_int status; cl_mem pixtemp; //Erode followed by Dilate status = pixErodeCL(hsize, vsize, wpl, h); pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; status = pixDilateCL(hsize, vsize, wpl, h); return status; } //Morphology Close operation. Invokes the relevant OpenCL kernels cl_int pixCloseCL(l_int32 hsize, l_int32 vsize, l_int32 wpl, l_int32 h) { cl_int status; cl_mem pixtemp; //Dilate followed by Erode status = pixDilateCL(hsize, vsize, wpl, h); pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; status = pixErodeCL(hsize, vsize, wpl, h); return status; } // OpenCL implementation of Morphology Close //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixCloseBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy = false) { l_uint32 wpl, h; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); clStatus = pixCloseCL(hsize, vsize, wpl, h); if (reqDataCopy) { pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs, wpl*h, CL_MAP_READ); } return pixd; } // OpenCL implementation of Morphology Open //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixOpenBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy = false) { l_uint32 wpl, h; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); clStatus = pixOpenCL(hsize, vsize, wpl, h); if (reqDataCopy) { pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs, wpl*h, CL_MAP_READ); } return pixd; } //pix OR operation: outbuffer = buffer1 | buffer2 cl_int pixORCL_work(l_uint32 wpl, l_uint32 h, cl_mem buffer1, cl_mem buffer2, cl_mem outbuffer) { cl_int status; size_t globalThreads[2]; int gsize; size_t localThreads[] = {GROUPSIZE_X, GROUPSIZE_Y}; gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "pixOR", &status ); status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &buffer1); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &buffer2); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(cl_mem), &outbuffer); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); return status; } //pix AND operation: outbuffer = buffer1 & buffer2 cl_int pixANDCL_work(l_uint32 wpl, l_uint32 h, cl_mem buffer1, cl_mem buffer2, cl_mem outbuffer) { cl_int status; size_t globalThreads[2]; int gsize; size_t localThreads[] = {GROUPSIZE_X, GROUPSIZE_Y}; gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "pixAND", &status ); // Enqueue a kernel run call. status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &buffer1); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &buffer2); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(cl_mem), &outbuffer); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(h), (const void *)&h); status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); return status; } //output = buffer1 & ~(buffer2) cl_int pixSubtractCL_work(l_uint32 wpl, l_uint32 h, cl_mem buffer1, cl_mem buffer2, cl_mem outBuffer = NULL) { cl_int status; size_t globalThreads[2]; int gsize; size_t localThreads[] = {GROUPSIZE_X, GROUPSIZE_Y}; gsize = (wpl + GROUPSIZE_X - 1)/ GROUPSIZE_X * GROUPSIZE_X; globalThreads[0] = gsize; gsize = (h + GROUPSIZE_Y - 1)/ GROUPSIZE_Y * GROUPSIZE_Y; globalThreads[1] = gsize; if (outBuffer != NULL) { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "pixSubtract", &status ); } else { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "pixSubtract_inplace", &status ); } // Enqueue a kernel run call. status = clSetKernelArg(rEnv.mpkKernel, 0, sizeof(cl_mem), &buffer1); status = clSetKernelArg(rEnv.mpkKernel, 1, sizeof(cl_mem), &buffer2); status = clSetKernelArg(rEnv.mpkKernel, 2, sizeof(wpl), (const void *)&wpl); status = clSetKernelArg(rEnv.mpkKernel, 3, sizeof(h), (const void *)&h); if (outBuffer != NULL) { status = clSetKernelArg(rEnv.mpkKernel, 4, sizeof(cl_mem), (const void *)&outBuffer); } status = clEnqueueNDRangeKernel(rEnv.mpkCmdQueue, rEnv.mpkKernel, 2, NULL, globalThreads, localThreads, 0, NULL, NULL); return status; } // OpenCL implementation of Subtract pix //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixSubtractCL(PIX *pixd, PIX *pixs1, PIX *pixs2, bool reqDataCopy = false) { l_uint32 wpl, h; PROCNAME("pixSubtractCL"); if (!pixs1) return (PIX *)ERROR_PTR("pixs1 not defined", procName, pixd); if (!pixs2) return (PIX *)ERROR_PTR("pixs2 not defined", procName, pixd); if (pixGetDepth(pixs1) != pixGetDepth(pixs2)) return (PIX *)ERROR_PTR("depths of pixs* unequal", procName, pixd); #if EQUAL_SIZE_WARNING if (!pixSizesEqual(pixs1, pixs2)) L_WARNING("pixs1 and pixs2 not equal sizes", procName); #endif /* EQUAL_SIZE_WARNING */ wpl = pixGetWpl(pixs1); h = pixGetHeight(pixs1); clStatus = pixSubtractCL_work(wpl, h, pixdCLBuffer, pixsCLBuffer); if (reqDataCopy) { //Read back output data from OCL buffer to cpu pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs1, wpl*h, CL_MAP_READ); } return pixd; } // OpenCL implementation of Hollow pix //Note: Assumes the source and dest opencl buffer are initialized. No check done PIX* OpenclDevice::pixHollowCL(PIX *pixd, PIX *pixs, l_int32 close_hsize, l_int32 close_vsize, l_int32 open_hsize, l_int32 open_vsize, bool reqDataCopy = false) { l_uint32 wpl, h; cl_mem pixtemp; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); //First step : Close Morph operation: Dilate followed by Erode clStatus = pixCloseCL(close_hsize, close_vsize, wpl, h); //Store the output of close operation in an intermediate buffer //this will be later used for pixsubtract clStatus = clEnqueueCopyBuffer(rEnv.mpkCmdQueue, pixdCLBuffer, pixdCLIntermediate, 0, 0, sizeof(int) * wpl*h, 0, NULL, NULL); //Second step: Open Operation - Erode followed by Dilate pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; clStatus = pixOpenCL(open_hsize, open_vsize, wpl, h); //Third step: Subtract : (Close - Open) pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixdCLIntermediate; pixdCLIntermediate = pixtemp; clStatus = pixSubtractCL_work(wpl, h, pixdCLBuffer, pixsCLBuffer); if (reqDataCopy) { //Read back output data from OCL buffer to cpu pixd = mapOutputCLBuffer(rEnv, pixdCLBuffer, pixd, pixs, wpl*h, CL_MAP_READ); } return pixd; } // OpenCL implementation of Get Lines from pix function //Note: Assumes the source and dest opencl buffer are initialized. No check done void OpenclDevice::pixGetLinesCL(PIX *pixd, PIX *pixs, PIX** pix_vline, PIX** pix_hline, PIX** pixClosed, bool getpixClosed, l_int32 close_hsize, l_int32 close_vsize, l_int32 open_hsize, l_int32 open_vsize, l_int32 line_hsize, l_int32 line_vsize) { l_uint32 wpl, h; cl_mem pixtemp; wpl = pixGetWpl(pixs); h = pixGetHeight(pixs); //First step : Close Morph operation: Dilate followed by Erode clStatus = pixCloseCL(close_hsize, close_vsize, wpl, h); //Copy the Close output to CPU buffer if (getpixClosed) { *pixClosed = mapOutputCLBuffer(rEnv, pixdCLBuffer, *pixClosed, pixs, wpl*h, CL_MAP_READ, true, false); } //Store the output of close operation in an intermediate buffer //this will be later used for pixsubtract clStatus = clEnqueueCopyBuffer(rEnv.mpkCmdQueue, pixdCLBuffer, pixdCLIntermediate, 0, 0, sizeof(int) * wpl*h, 0, NULL, NULL); //Second step: Open Operation - Erode followed by Dilate pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; clStatus = pixOpenCL(open_hsize, open_vsize, wpl, h); //Third step: Subtract : (Close - Open) pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixdCLIntermediate; pixdCLIntermediate = pixtemp; clStatus = pixSubtractCL_work(wpl, h, pixdCLBuffer, pixsCLBuffer); //Store the output of Hollow operation in an intermediate buffer //this will be later used clStatus = clEnqueueCopyBuffer(rEnv.mpkCmdQueue, pixdCLBuffer, pixdCLIntermediate, 0, 0, sizeof(int) * wpl*h, 0, NULL, NULL); pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLBuffer; pixdCLBuffer = pixtemp; //Fourth step: Get vertical line //pixOpenBrick(NULL, pix_hollow, 1, min_line_length); clStatus = pixOpenCL(1, line_vsize, wpl, h); //Copy the vertical line output to CPU buffer *pix_vline = mapOutputCLBuffer(rEnv, pixdCLBuffer, *pix_vline, pixs, wpl*h, CL_MAP_READ, true, false); pixtemp = pixsCLBuffer; pixsCLBuffer = pixdCLIntermediate; pixdCLIntermediate = pixtemp; //Fifth step: Get horizontal line //pixOpenBrick(NULL, pix_hollow, min_line_length, 1); clStatus = pixOpenCL(line_hsize, 1, wpl, h); //Copy the horizontal line output to CPU buffer *pix_hline = mapOutputCLBuffer(rEnv, pixdCLBuffer, *pix_hline, pixs, wpl*h, CL_MAP_READ, true, true); return; } /************************************************************************* * HistogramRect * Otsu Thresholding Operations * histogramAllChannels is layed out as all channel 0, then all channel 1... * only supports 1 or 4 channels (bytes_per_pixel) ************************************************************************/ void OpenclDevice::HistogramRectOCL( const unsigned char* imageData, int bytes_per_pixel, int bytes_per_line, int left, // always 0 int top, // always 0 int width, int height, int kHistogramSize, int* histogramAllChannels) { PERF_COUNT_START("HistogramRectOCL") cl_int clStatus; KernelEnv histKern; SetKernelEnv( &histKern ); KernelEnv histRedKern; SetKernelEnv( &histRedKern ); /* map imagedata to device as read only */ // USE_HOST_PTR uses onion+ bus which is slowest option; also happens to be coherent which we don't need. // faster option would be to allocate initial image buffer // using a garlic bus memory type cl_mem imageBuffer = clCreateBuffer( histKern.mpkContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, width*height*bytes_per_pixel*sizeof(char), (void *)imageData, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer imageBuffer"); /* setup work group size parameters */ int block_size = 256; cl_uint numCUs; clStatus = clGetDeviceInfo( gpuEnv.mpDevID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(numCUs), &numCUs, NULL); CHECK_OPENCL( clStatus, "clCreateBuffer imageBuffer"); int requestedOccupancy = 10; int numWorkGroups = numCUs * requestedOccupancy; int numThreads = block_size*numWorkGroups; size_t local_work_size[] = {static_cast<size_t>(block_size)}; size_t global_work_size[] = {static_cast<size_t>(numThreads)}; size_t red_global_work_size[] = {static_cast<size_t>(block_size*kHistogramSize*bytes_per_pixel)}; /* map histogramAllChannels as write only */ int numBins = kHistogramSize*bytes_per_pixel*numWorkGroups; cl_mem histogramBuffer = clCreateBuffer( histKern.mpkContext, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, kHistogramSize*bytes_per_pixel*sizeof(int), (void *)histogramAllChannels, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer histogramBuffer"); /* intermediate histogram buffer */ int histRed = 256; int tmpHistogramBins = kHistogramSize*bytes_per_pixel*histRed; cl_mem tmpHistogramBuffer = clCreateBuffer( histKern.mpkContext, CL_MEM_READ_WRITE, tmpHistogramBins*sizeof(cl_uint), NULL, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer tmpHistogramBuffer"); /* atomic sync buffer */ int *zeroBuffer = new int[1]; zeroBuffer[0] = 0; cl_mem atomicSyncBuffer = clCreateBuffer( histKern.mpkContext, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(cl_int), (void *)zeroBuffer, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer atomicSyncBuffer"); //Create kernel objects based on bytes_per_pixel if (bytes_per_pixel == 1) { histKern.mpkKernel = clCreateKernel( histKern.mpkProgram, "kernel_HistogramRectOneChannel", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_HistogramRectOneChannel"); histRedKern.mpkKernel = clCreateKernel( histRedKern.mpkProgram, "kernel_HistogramRectOneChannelReduction", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_HistogramRectOneChannelReduction"); } else { histKern.mpkKernel = clCreateKernel( histKern.mpkProgram, "kernel_HistogramRectAllChannels", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_HistogramRectAllChannels"); histRedKern.mpkKernel = clCreateKernel( histRedKern.mpkProgram, "kernel_HistogramRectAllChannelsReduction", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_HistogramRectAllChannelsReduction"); } void *ptr; //Initialize tmpHistogramBuffer buffer ptr = clEnqueueMapBuffer(histKern.mpkCmdQueue, tmpHistogramBuffer, CL_TRUE, CL_MAP_WRITE, 0, tmpHistogramBins*sizeof(cl_uint), 0, NULL, NULL, &clStatus); CHECK_OPENCL( clStatus, "clEnqueueMapBuffer tmpHistogramBuffer"); memset(ptr, 0, tmpHistogramBins*sizeof(cl_uint)); clEnqueueUnmapMemObject(histKern.mpkCmdQueue, tmpHistogramBuffer, ptr, 0, NULL, NULL); /* set kernel 1 arguments */ clStatus = clSetKernelArg( histKern.mpkKernel, 0, sizeof(cl_mem), (void *)&imageBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg imageBuffer"); cl_uint numPixels = width*height; clStatus = clSetKernelArg( histKern.mpkKernel, 1, sizeof(cl_uint), (void *)&numPixels ); CHECK_OPENCL( clStatus, "clSetKernelArg numPixels" ); clStatus = clSetKernelArg( histKern.mpkKernel, 2, sizeof(cl_mem), (void *)&tmpHistogramBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg tmpHistogramBuffer"); /* set kernel 2 arguments */ int n = numThreads/bytes_per_pixel; clStatus = clSetKernelArg( histRedKern.mpkKernel, 0, sizeof(cl_int), (void *)&n ); CHECK_OPENCL( clStatus, "clSetKernelArg imageBuffer"); clStatus = clSetKernelArg( histRedKern.mpkKernel, 1, sizeof(cl_mem), (void *)&tmpHistogramBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg tmpHistogramBuffer"); clStatus = clSetKernelArg( histRedKern.mpkKernel, 2, sizeof(cl_mem), (void *)&histogramBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg histogramBuffer"); /* launch histogram */ PERF_COUNT_SUB("before") clStatus = clEnqueueNDRangeKernel( histKern.mpkCmdQueue, histKern.mpkKernel, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL ); CHECK_OPENCL( clStatus, "clEnqueueNDRangeKernel kernel_HistogramRectAllChannels" ); clFinish( histKern.mpkCmdQueue ); /* launch histogram */ clStatus = clEnqueueNDRangeKernel( histRedKern.mpkCmdQueue, histRedKern.mpkKernel, 1, NULL, red_global_work_size, local_work_size, 0, NULL, NULL ); CHECK_OPENCL( clStatus, "clEnqueueNDRangeKernel kernel_HistogramRectAllChannelsReduction" ); clFinish( histRedKern.mpkCmdQueue ); PERF_COUNT_SUB("redKernel") /* map results back from gpu */ ptr = clEnqueueMapBuffer(histRedKern.mpkCmdQueue, histogramBuffer, CL_TRUE, CL_MAP_READ, 0, kHistogramSize*bytes_per_pixel*sizeof(int), 0, NULL, NULL, &clStatus); CHECK_OPENCL( clStatus, "clEnqueueMapBuffer histogramBuffer"); clEnqueueUnmapMemObject(histRedKern.mpkCmdQueue, histogramBuffer, ptr, 0, NULL, NULL); clReleaseMemObject(histogramBuffer); clReleaseMemObject(imageBuffer); PERF_COUNT_SUB("after") PERF_COUNT_END } /************************************************************************* * Threshold the rectangle, taking everything except the image buffer pointer * from the class, using thresholds/hi_values to the output IMAGE. * only supports 1 or 4 channels ************************************************************************/ void OpenclDevice::ThresholdRectToPixOCL( const unsigned char* imageData, int bytes_per_pixel, int bytes_per_line, const int* thresholds, const int* hi_values, Pix** pix, int height, int width, int top, int left) { PERF_COUNT_START("ThresholdRectToPixOCL") /* create pix result buffer */ *pix = pixCreate(width, height, 1); uinT32* pixData = pixGetData(*pix); int wpl = pixGetWpl(*pix); int pixSize = wpl*height*sizeof(uinT32); cl_int clStatus; KernelEnv rEnv; SetKernelEnv( &rEnv ); /* setup work group size parameters */ int block_size = 256; cl_uint numCUs = 6; clStatus = clGetDeviceInfo( gpuEnv.mpDevID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(numCUs), &numCUs, NULL); CHECK_OPENCL( clStatus, "clCreateBuffer imageBuffer"); int requestedOccupancy = 10; int numWorkGroups = numCUs * requestedOccupancy; int numThreads = block_size*numWorkGroups; size_t local_work_size[] = {(size_t) block_size}; size_t global_work_size[] = {(size_t) numThreads}; /* map imagedata to device as read only */ // USE_HOST_PTR uses onion+ bus which is slowest option; also happens to be coherent which we don't need. // faster option would be to allocate initial image buffer // using a garlic bus memory type cl_mem imageBuffer = clCreateBuffer( rEnv.mpkContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, width*height*bytes_per_pixel*sizeof(char), (void *)imageData, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer imageBuffer"); /* map pix as write only */ pixThBuffer = clCreateBuffer( rEnv.mpkContext, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, pixSize, (void *)pixData, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer pix"); /* map thresholds and hi_values */ cl_mem thresholdsBuffer = clCreateBuffer( rEnv.mpkContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, bytes_per_pixel*sizeof(int), (void *)thresholds, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer thresholdBuffer"); cl_mem hiValuesBuffer = clCreateBuffer( rEnv.mpkContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, bytes_per_pixel*sizeof(int), (void *)hi_values, &clStatus ); CHECK_OPENCL( clStatus, "clCreateBuffer hiValuesBuffer"); /* compile kernel */ if (bytes_per_pixel == 4) { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "kernel_ThresholdRectToPix", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_ThresholdRectToPix"); } else { rEnv.mpkKernel = clCreateKernel( rEnv.mpkProgram, "kernel_ThresholdRectToPix_OneChan", &clStatus ); CHECK_OPENCL( clStatus, "clCreateKernel kernel_ThresholdRectToPix_OneChan"); } /* set kernel arguments */ clStatus = clSetKernelArg( rEnv.mpkKernel, 0, sizeof(cl_mem), (void *)&imageBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg imageBuffer"); cl_uint numPixels = width*height; clStatus = clSetKernelArg( rEnv.mpkKernel, 1, sizeof(int), (void *)&height ); CHECK_OPENCL( clStatus, "clSetKernelArg height" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 2, sizeof(int), (void *)&width ); CHECK_OPENCL( clStatus, "clSetKernelArg width" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 3, sizeof(int), (void *)&wpl ); CHECK_OPENCL( clStatus, "clSetKernelArg wpl" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 4, sizeof(cl_mem), (void *)&thresholdsBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg thresholdsBuffer" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 5, sizeof(cl_mem), (void *)&hiValuesBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg hiValuesBuffer" ); clStatus = clSetKernelArg( rEnv.mpkKernel, 6, sizeof(cl_mem), (void *)&pixThBuffer ); CHECK_OPENCL( clStatus, "clSetKernelArg pixThBuffer"); /* launch kernel & wait */ PERF_COUNT_SUB("before") clStatus = clEnqueueNDRangeKernel( rEnv.mpkCmdQueue, rEnv.mpkKernel, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL ); CHECK_OPENCL( clStatus, "clEnqueueNDRangeKernel kernel_ThresholdRectToPix" ); clFinish( rEnv.mpkCmdQueue ); PERF_COUNT_SUB("kernel") /* map results back from gpu */ void *ptr = clEnqueueMapBuffer(rEnv.mpkCmdQueue, pixThBuffer, CL_TRUE, CL_MAP_READ, 0, pixSize, 0, NULL, NULL, &clStatus); CHECK_OPENCL( clStatus, "clEnqueueMapBuffer histogramBuffer"); clEnqueueUnmapMemObject(rEnv.mpkCmdQueue, pixThBuffer, ptr, 0, NULL, NULL); clReleaseMemObject(imageBuffer); clReleaseMemObject(thresholdsBuffer); clReleaseMemObject(hiValuesBuffer); PERF_COUNT_SUB("after") PERF_COUNT_END } #if USE_DEVICE_SELECTION /****************************************************************************** * Data Types for Device Selection *****************************************************************************/ typedef struct _TessScoreEvaluationInputData { int height; int width; int numChannels; unsigned char *imageData; Pix *pix; } TessScoreEvaluationInputData; void populateTessScoreEvaluationInputData( TessScoreEvaluationInputData *input ) { srand(1); // 8.5x11 inches @ 300dpi rounded to clean multiples int height = 3328; // %256 int width = 2560; // %512 int numChannels = 4; input->height = height; input->width = width; input->numChannels = numChannels; unsigned char (*imageData4)[4] = (unsigned char (*)[4]) malloc(height*width*numChannels*sizeof(unsigned char)); // new unsigned char[4][height*width]; input->imageData = (unsigned char *) &imageData4[0]; // zero out image unsigned char pixelWhite[4] = { 0, 0, 0, 255}; unsigned char pixelBlack[4] = {255, 255, 255, 255}; for (int p = 0; p < height*width; p++) { //unsigned char tmp[4] = imageData4[0]; imageData4[p][0] = pixelWhite[0]; imageData4[p][1] = pixelWhite[1]; imageData4[p][2] = pixelWhite[2]; imageData4[p][3] = pixelWhite[3]; } // random lines to be eliminated int maxLineWidth = 64; // pixels wide int numLines = 10; // vertical lines for (int i = 0; i < numLines; i++) { int lineWidth = rand()%maxLineWidth; int vertLinePos = lineWidth + rand()%(width-2*lineWidth); //printf("[PI] VerticalLine @ %i (w=%i)\n", vertLinePos, lineWidth); for (int row = vertLinePos-lineWidth/2; row < vertLinePos+lineWidth/2; row++) { for (int col = 0; col < height; col++) { //imageData4[row*width+col] = pixelBlack; imageData4[row*width+col][0] = pixelBlack[0]; imageData4[row*width+col][1] = pixelBlack[1]; imageData4[row*width+col][2] = pixelBlack[2]; imageData4[row*width+col][3] = pixelBlack[3]; } } } // horizontal lines for (int i = 0; i < numLines; i++) { int lineWidth = rand()%maxLineWidth; int horLinePos = lineWidth + rand()%(height-2*lineWidth); //printf("[PI] HorizontalLine @ %i (w=%i)\n", horLinePos, lineWidth); for (int row = 0; row < width; row++) { for (int col = horLinePos-lineWidth/2; col < horLinePos+lineWidth/2; col++) { // for (int row = vertLinePos-lineWidth/2; row < vertLinePos+lineWidth/2; row++) { //printf("[PI] HoizLine pix @ (%3i, %3i)\n", row, col); //imageData4[row*width+col] = pixelBlack; imageData4[row*width+col][0] = pixelBlack[0]; imageData4[row*width+col][1] = pixelBlack[1]; imageData4[row*width+col][2] = pixelBlack[2]; imageData4[row*width+col][3] = pixelBlack[3]; } } } // spots (noise, squares) float fractionBlack = 0.1; // how much of the image should be blackened int numSpots = (height*width)*fractionBlack/(maxLineWidth*maxLineWidth/2/2); for (int i = 0; i < numSpots; i++) { int lineWidth = rand()%maxLineWidth; int col = lineWidth + rand()%(width-2*lineWidth); int row = lineWidth + rand()%(height-2*lineWidth); //printf("[PI] Spot[%i/%i] @ (%3i, %3i)\n", i, numSpots, row, col ); for (int r = row-lineWidth/2; r < row+lineWidth/2; r++) { for (int c = col-lineWidth/2; c < col+lineWidth/2; c++) { //printf("[PI] \tSpot[%i/%i] @ (%3i, %3i)\n", i, numSpots, r, c ); //imageData4[row*width+col] = pixelBlack; imageData4[r*width+c][0] = pixelBlack[0]; imageData4[r*width+c][1] = pixelBlack[1]; imageData4[r*width+c][2] = pixelBlack[2]; imageData4[r*width+c][3] = pixelBlack[3]; } } } input->pix = pixCreate(input->width, input->height, 1); } typedef struct _TessDeviceScore { float time; // small time means faster device bool clError; // were there any opencl errors bool valid; // was the correct response generated } TessDeviceScore; /****************************************************************************** * Micro Benchmarks for Device Selection *****************************************************************************/ double composeRGBPixelMicroBench( GPUEnv *env, TessScoreEvaluationInputData input, ds_device_type type ) { double time = 0; #if ON_WINDOWS LARGE_INTEGER freq, time_funct_start, time_funct_end; QueryPerformanceFrequency(&freq); #else TIMESPEC time_funct_start, time_funct_end; #endif // input data l_uint32 *tiffdata = (l_uint32 *)input.imageData;// same size and random data; data doesn't change workload // function call if (type == DS_DEVICE_OPENCL_DEVICE) { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif OpenclDevice::gpuEnv = *env; int wpl = pixGetWpl(input.pix); OpenclDevice::pixReadFromTiffKernel(tiffdata, input.width, input.height, wpl, NULL); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } else { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif Pix *pix = pixCreate(input.width, input.height, 32); l_uint32 *pixData = pixGetData(pix); int wpl = pixGetWpl(pix); //l_uint32* output_gpu=pixReadFromTiffKernel(tiffdata,w,h,wpl,line); //pixSetData(pix, output_gpu); int i, j; int idx = 0; for (i = 0; i < input.height ; i++) { for (j = 0; j < input.width; j++) { l_uint32 tiffword = tiffdata[i * input.width + j]; l_int32 rval = ((tiffword) & 0xff); l_int32 gval = (((tiffword) >> 8) & 0xff); l_int32 bval = (((tiffword) >> 16) & 0xff); l_uint32 value = (rval << 24) | (gval << 16) | (bval << 8); pixData[idx] = value; idx++; } } #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif pixDestroy(&pix); } // cleanup return time; } double histogramRectMicroBench( GPUEnv *env, TessScoreEvaluationInputData input, ds_device_type type ) { double time; #if ON_WINDOWS LARGE_INTEGER freq, time_funct_start, time_funct_end; QueryPerformanceFrequency(&freq); #else TIMESPEC time_funct_start, time_funct_end; #endif unsigned char pixelHi = (unsigned char)255; int left = 0; int top = 0; int kHistogramSize = 256; int bytes_per_line = input.width*input.numChannels; int *histogramAllChannels = new int[kHistogramSize*input.numChannels]; // function call if (type == DS_DEVICE_OPENCL_DEVICE) { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif OpenclDevice::gpuEnv = *env; int wpl = pixGetWpl(input.pix); OpenclDevice::HistogramRectOCL(input.imageData, input.numChannels, bytes_per_line, top, left, input.width, input.height, kHistogramSize, histogramAllChannels); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } else { int *histogram = new int[kHistogramSize]; #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif for (int ch = 0; ch < input.numChannels; ++ch) { tesseract::HistogramRect(input.pix, input.numChannels, left, top, input.width, input.height, histogram); } #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif delete[] histogram; } // cleanup //delete[] imageData; delete[] histogramAllChannels; return time; } //Reproducing the ThresholdRectToPix native version void ThresholdRectToPix_Native(const unsigned char* imagedata, int bytes_per_pixel, int bytes_per_line, const int* thresholds, const int* hi_values, Pix** pix) { int top = 0; int left = 0; int width = pixGetWidth(*pix); int height = pixGetHeight(*pix); *pix = pixCreate(width, height, 1); uinT32* pixdata = pixGetData(*pix); int wpl = pixGetWpl(*pix); const unsigned char* srcdata = imagedata + top * bytes_per_line + left * bytes_per_pixel; for (int y = 0; y < height; ++y) { const uinT8* linedata = srcdata; uinT32* pixline = pixdata + y * wpl; for (int x = 0; x < width; ++x, linedata += bytes_per_pixel) { bool white_result = true; for (int ch = 0; ch < bytes_per_pixel; ++ch) { if (hi_values[ch] >= 0 && (linedata[ch] > thresholds[ch]) == (hi_values[ch] == 0)) { white_result = false; break; } } if (white_result) CLEAR_DATA_BIT(pixline, x); else SET_DATA_BIT(pixline, x); } srcdata += bytes_per_line; } } double thresholdRectToPixMicroBench( GPUEnv *env, TessScoreEvaluationInputData input, ds_device_type type ) { double time; #if ON_WINDOWS LARGE_INTEGER freq, time_funct_start, time_funct_end; QueryPerformanceFrequency(&freq); #else TIMESPEC time_funct_start, time_funct_end; #endif // input data unsigned char pixelHi = (unsigned char)255; int* thresholds = new int[4]; thresholds[0] = pixelHi/2; thresholds[1] = pixelHi/2; thresholds[2] = pixelHi/2; thresholds[3] = pixelHi/2; int *hi_values = new int[4]; thresholds[0] = pixelHi; thresholds[1] = pixelHi; thresholds[2] = pixelHi; thresholds[3] = pixelHi; //Pix* pix = pixCreate(width, height, 1); int top = 0; int left = 0; int bytes_per_line = input.width*input.numChannels; // function call if (type == DS_DEVICE_OPENCL_DEVICE) { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif OpenclDevice::gpuEnv = *env; int wpl = pixGetWpl(input.pix); OpenclDevice::ThresholdRectToPixOCL(input.imageData, input.numChannels, bytes_per_line, thresholds, hi_values, &input.pix, input.height, input.width, top, left); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } else { tesseract::ImageThresholder thresholder; thresholder.SetImage( input.pix ); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif ThresholdRectToPix_Native( input.imageData, input.numChannels, bytes_per_line, thresholds, hi_values, &input.pix ); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } // cleanup delete[] thresholds; delete[] hi_values; return time; } double getLineMasksMorphMicroBench( GPUEnv *env, TessScoreEvaluationInputData input, ds_device_type type ) { double time = 0; #if ON_WINDOWS LARGE_INTEGER freq, time_funct_start, time_funct_end; QueryPerformanceFrequency(&freq); #else TIMESPEC time_funct_start, time_funct_end; #endif // input data int resolution = 300; int wpl = pixGetWpl(input.pix); int kThinLineFraction = 20; // tess constant int kMinLineLengthFraction = 4; // tess constant int max_line_width = resolution / kThinLineFraction; int min_line_length = resolution / kMinLineLengthFraction; int closing_brick = max_line_width / 3; // function call if (type == DS_DEVICE_OPENCL_DEVICE) { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif Pix *src_pix = input.pix; OpenclDevice::gpuEnv = *env; OpenclDevice::initMorphCLAllocations(wpl, input.height, input.pix); Pix *pix_vline = NULL, *pix_hline = NULL, *pix_closed = NULL; OpenclDevice::pixGetLinesCL(NULL, input.pix, &pix_vline, &pix_hline, &pix_closed, true, closing_brick, closing_brick, max_line_width, max_line_width, min_line_length, min_line_length); OpenclDevice::releaseMorphCLBuffers(); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } else { #if ON_WINDOWS QueryPerformanceCounter(&time_funct_start); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); #endif // native serial code Pix *src_pix = input.pix; Pix *pix_closed = pixCloseBrick(NULL, src_pix, closing_brick, closing_brick); Pix *pix_solid = pixOpenBrick(NULL, pix_closed, max_line_width, max_line_width); Pix *pix_hollow = pixSubtract(NULL, pix_closed, pix_solid); pixDestroy(&pix_solid); Pix *pix_vline = pixOpenBrick(NULL, pix_hollow, 1, min_line_length); Pix *pix_hline = pixOpenBrick(NULL, pix_hollow, min_line_length, 1); pixDestroy(&pix_hollow); #if ON_WINDOWS QueryPerformanceCounter(&time_funct_end); time = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); #else clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); time = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; #endif } return time; } /****************************************************************************** * Device Selection *****************************************************************************/ #include "stdlib.h" // encode score object as byte string ds_status serializeScore( ds_device* device, void **serializedScore, unsigned int* serializedScoreSize ) { *serializedScoreSize = sizeof(TessDeviceScore); *serializedScore = (void *) new unsigned char[*serializedScoreSize]; memcpy(*serializedScore, device->score, *serializedScoreSize); return DS_SUCCESS; } // parses byte string and stores in score object ds_status deserializeScore( ds_device* device, const unsigned char* serializedScore, unsigned int serializedScoreSize ) { // check that serializedScoreSize == sizeof(TessDeviceScore); device->score = new TessDeviceScore; memcpy(device->score, serializedScore, serializedScoreSize); return DS_SUCCESS; } // evaluate devices ds_status evaluateScoreForDevice( ds_device *device, void *inputData) { // overwrite statuc gpuEnv w/ current device // so native opencl calls can be used; they use static gpuEnv printf("\n[DS] Device: \"%s\" (%s) evaluation...\n", device->oclDeviceName, device->type==DS_DEVICE_OPENCL_DEVICE ? "OpenCL" : "Native" ); GPUEnv *env = NULL; if (device->type == DS_DEVICE_OPENCL_DEVICE) { env = new GPUEnv; //printf("[DS] populating tmp GPUEnv from device\n"); populateGPUEnvFromDevice( env, device->oclDeviceID); env->mnFileCount = 0; //argc; env->mnKernelCount = 0UL; //printf("[DS] compiling kernels for tmp GPUEnv\n"); OpenclDevice::gpuEnv = *env; OpenclDevice::CompileKernelFile(env, ""); } TessScoreEvaluationInputData *input = (TessScoreEvaluationInputData *)inputData; // pixReadTiff double composeRGBPixelTime = composeRGBPixelMicroBench( env, *input, device->type ); // HistogramRect double histogramRectTime = histogramRectMicroBench( env, *input, device->type ); // ThresholdRectToPix double thresholdRectToPixTime = thresholdRectToPixMicroBench( env, *input, device->type ); // getLineMasks double getLineMasksMorphTime = getLineMasksMorphMicroBench( env, *input, device->type ); // weigh times (% of cpu time) // these weights should be the % execution time that the native cpu code took float composeRGBPixelWeight = 1.2f; float histogramRectWeight = 2.4f; float thresholdRectToPixWeight = 4.5f; float getLineMasksMorphWeight = 5.0f; float weightedTime = composeRGBPixelWeight * composeRGBPixelTime + histogramRectWeight * histogramRectTime + thresholdRectToPixWeight * thresholdRectToPixTime + getLineMasksMorphWeight * getLineMasksMorphTime ; device->score = (void *)new TessDeviceScore; ((TessDeviceScore *)device->score)->time = weightedTime; printf("[DS] Device: \"%s\" (%s) evaluated\n", device->oclDeviceName, device->type==DS_DEVICE_OPENCL_DEVICE ? "OpenCL" : "Native" ); printf("[DS]%25s: %f (w=%.1f)\n", "composeRGBPixel", composeRGBPixelTime, composeRGBPixelWeight ); printf("[DS]%25s: %f (w=%.1f)\n", "HistogramRect", histogramRectTime, histogramRectWeight ); printf("[DS]%25s: %f (w=%.1f)\n", "ThresholdRectToPix", thresholdRectToPixTime, thresholdRectToPixWeight ); printf("[DS]%25s: %f (w=%.1f)\n", "getLineMasksMorph", getLineMasksMorphTime, getLineMasksMorphWeight ); printf("[DS]%25s: %f\n", "Score", ((TessDeviceScore *)device->score)->time ); return DS_SUCCESS; } // initial call to select device ds_device OpenclDevice::getDeviceSelection( ) { //PERF_COUNT_START("getDeviceSelection") if (!deviceIsSelected) { PERF_COUNT_START("getDeviceSelection") // check if opencl is available at runtime if( 1 == LoadOpencl() ) { // opencl is available //PERF_COUNT_SUB("LoadOpencl") // setup devices ds_status status; ds_profile *profile; status = initDSProfile( &profile, "v0.1" ); PERF_COUNT_SUB("initDSProfile") // try reading scores from file char *fileName = "tesseract_opencl_profile_devices.dat"; status = readProfileFromFile( profile, deserializeScore, fileName); if (status != DS_SUCCESS) { // need to run evaluation printf("[DS] Profile file not available (%s); performing profiling.\n", fileName); // create input data TessScoreEvaluationInputData input; populateTessScoreEvaluationInputData( &input ); //PERF_COUNT_SUB("populateTessScoreEvaluationInputData") // perform evaluations unsigned int numUpdates; status = profileDevices( profile, DS_EVALUATE_ALL, evaluateScoreForDevice, (void *)&input, &numUpdates ); PERF_COUNT_SUB("profileDevices") // write scores to file if ( status == DS_SUCCESS ) { status = writeProfileToFile( profile, serializeScore, fileName); PERF_COUNT_SUB("writeProfileToFile") if ( status == DS_SUCCESS ) { printf("[DS] Scores written to file (%s).\n", fileName); } else { printf("[DS] Error saving scores to file (%s); scores not written to file.\n", fileName); } } else { printf("[DS] Unable to evaluate performance; scores not written to file.\n"); } } else { PERF_COUNT_SUB("readProfileFromFile") printf("[DS] Profile read from file (%s).\n", fileName); } // we now have device scores either from file or evaluation // select fastest using custom Tesseract selection algorithm float bestTime = FLT_MAX; // begin search with worst possible time int bestDeviceIdx = -1; for (int d = 0; d < profile->numDevices; d++) { //((TessDeviceScore *)device->score)->time ds_device device = profile->devices[d]; TessDeviceScore score = *(TessDeviceScore *)device.score; float time = score.time; printf("[DS] Device[%i] %i:%s score is %f\n", d+1, device.type, device.oclDeviceName, time); if (time < bestTime) { bestTime = time; bestDeviceIdx = d; } } printf("[DS] Selected Device[%i]: \"%s\" (%s)\n", bestDeviceIdx+1, profile->devices[bestDeviceIdx].oclDeviceName, profile->devices[bestDeviceIdx].type==DS_DEVICE_OPENCL_DEVICE ? "OpenCL" : "Native"); // cleanup // TODO: call destructor for profile object? bool overrided = false; char *overrideDeviceStr = getenv("TESSERACT_OPENCL_DEVICE"); if (overrideDeviceStr != NULL) { int overrideDeviceIdx = atoi(overrideDeviceStr); if (overrideDeviceIdx > 0 && overrideDeviceIdx <= profile->numDevices ) { printf("[DS] Overriding Device Selection (TESSERACT_OPENCL_DEVICE=%s, %i)\n", overrideDeviceStr, overrideDeviceIdx); bestDeviceIdx = overrideDeviceIdx - 1; overrided = true; } else { printf("[DS] Ignoring invalid TESSERACT_OPENCL_DEVICE=%s ([1,%i] are valid devices).\n", overrideDeviceStr, profile->numDevices); } } if (overrided) { printf("[DS] Overridden Device[%i]: \"%s\" (%s)\n", bestDeviceIdx+1, profile->devices[bestDeviceIdx].oclDeviceName, profile->devices[bestDeviceIdx].type==DS_DEVICE_OPENCL_DEVICE ? "OpenCL" : "Native"); } selectedDevice = profile->devices[bestDeviceIdx]; } else { // opencl isn't available at runtime, select native cpu device printf("[DS] OpenCL runtime not available.\n"); selectedDevice.type = DS_DEVICE_NATIVE_CPU; selectedDevice.oclDeviceName = "(null)"; selectedDevice.score = NULL; selectedDevice.oclDeviceID = NULL; selectedDevice.oclDriverVersion = NULL; } deviceIsSelected = true; PERF_COUNT_SUB("select from Profile") PERF_COUNT_END } //PERF_COUNT_END return selectedDevice; } #endif bool OpenclDevice::selectedDeviceIsOpenCL() { #if USE_DEVICE_SELECTION ds_device device = getDeviceSelection(); return (device.type == DS_DEVICE_OPENCL_DEVICE); #else return true; #endif } bool OpenclDevice::selectedDeviceIsNativeCPU() { #if USE_DEVICE_SELECTION ds_device device = getDeviceSelection(); return (device.type == DS_DEVICE_NATIVE_CPU); #else return false; #endif } #endif
1080228-arabicocr11
opencl/openclwrapper.cpp
C++
asf20
116,970
AM_CPPFLAGS += -I$(top_srcdir)/ccutil -I$(top_srcdir)/ccstruct -I$(top_srcdir)/ccmain if USE_OPENCL AM_CPPFLAGS += -I$(OPENCL_HDR_PATH) endif noinst_HEADERS = \ openclwrapper.h oclkernels.h opencl_device_selection.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_opencl.la else lib_LTLIBRARIES = libtesseract_opencl.la libtesseract_opencl_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_opencl_la_LIBADD = \ ../ccutil/libtesseract_ccutil.la \ ../viewer/libtesseract_viewer.la if USE_OPENCL libtesseract_opencl_la_LDFLAGS += $(OPENCL_LIB) endif endif libtesseract_opencl_la_SOURCES = \ openclwrapper.cpp
1080228-arabicocr11
opencl/Makefile.am
Makefile
asf20
652
#include <stdio.h> #include "allheaders.h" #include "pix.h" #ifdef USE_OPENCL #include "tiff.h" #include "tiffio.h" #endif #include "tprintf.h" // including CL/cl.h doesn't occur until USE_OPENCL defined below // platform preprocessor commands #if defined( WIN32 ) || defined( __WIN32__ ) || defined( _WIN32 ) || defined( __CYGWIN32__ ) || defined( __MINGW32__ ) #define ON_WINDOWS 1 #define ON_LINUX 0 #define ON_APPLE 0 #define ON_OTHER 0 #define IF_WINDOWS(X) X #define IF_LINUX(X) #define IF_APPLE(X) #define IF_OTHER(X) #define NOT_WINDOWS(X) #elif defined( __linux__ ) #define ON_WINDOWS 0 #define ON_LINUX 1 #define ON_APPLE 0 #define ON_OTHER 0 #define IF_WINDOWS(X) #define IF_LINUX(X) X #define IF_APPLE(X) #define IF_OTHER(X) #define NOT_WINDOWS(X) X #elif defined( __APPLE__ ) #define ON_WINDOWS 0 #define ON_LINUX 0 #define ON_APPLE 1 #define ON_OTHER 0 #define IF_WINDOWS(X) #define IF_LINUX(X) #define IF_APPLE(X) X #define IF_OTHER(X) #define NOT_WINDOWS(X) X #else #define ON_WINDOWS 0 #define ON_LINUX 0 #define ON_APPLE 0 #define ON_OTHER 1 #define IF_WINDOWS(X) #define IF_LINUX(X) #define IF_APPLE(X) #define IF_OTHER(X) X #define NOT_WINDOWS(X) X #endif #if ON_LINUX #include <time.h> #endif #if ON_APPLE #include <mach/clock.h> #include <mach/mach.h> #define CLOCK_MONOTONIC SYSTEM_CLOCK #define clock_gettime clock_get_time #endif /************************************************************************************ * enable/disable reporting of performance * PERF_REPORT_LEVEL * 0 - no reporting * 1 - no reporting * 2 - report total function call time for functions we're tracking * 3 - optionally report breakdown of function calls (kernel launch, kernel time, data copies) ************************************************************************************/ #define PERF_COUNT_VERBOSE 1 #define PERF_COUNT_REPORT_STR "[%36s], %24s, %11.6f\n" #if ON_WINDOWS #if PERF_COUNT_VERBOSE >= 2 #define PERF_COUNT_START(FUNCT_NAME) \ char *funct_name = FUNCT_NAME; \ double elapsed_time_sec; \ LARGE_INTEGER freq, time_funct_start, time_funct_end, time_sub_start, time_sub_end; \ QueryPerformanceFrequency(&freq); \ QueryPerformanceCounter(&time_funct_start); \ time_sub_start = time_funct_start; \ time_sub_end = time_funct_start; #define PERF_COUNT_END \ QueryPerformanceCounter(&time_funct_end); \ elapsed_time_sec = (time_funct_end.QuadPart-time_funct_start.QuadPart)/(double)(freq.QuadPart); \ tprintf(PERF_COUNT_REPORT_STR, funct_name, "total", elapsed_time_sec); #else #define PERF_COUNT_START(FUNCT_NAME) #define PERF_COUNT_END #endif #if PERF_COUNT_VERBOSE >= 3 #define PERF_COUNT_SUB(SUB) \ QueryPerformanceCounter(&time_sub_end); \ elapsed_time_sec = (time_sub_end.QuadPart-time_sub_start.QuadPart)/(double)(freq.QuadPart); \ tprintf(PERF_COUNT_REPORT_STR, funct_name, SUB, elapsed_time_sec); \ time_sub_start = time_sub_end; #else #define PERF_COUNT_SUB(SUB) #endif // not on windows #else #if PERF_COUNT_VERBOSE >= 2 #define PERF_COUNT_START(FUNCT_NAME) \ char *funct_name = FUNCT_NAME; \ double elapsed_time_sec; \ timespec time_funct_start, time_funct_end, time_sub_start, time_sub_end; \ clock_gettime( CLOCK_MONOTONIC, &time_funct_start ); \ time_sub_start = time_funct_start; \ time_sub_end = time_funct_start; #define PERF_COUNT_END \ clock_gettime( CLOCK_MONOTONIC, &time_funct_end ); \ elapsed_time_sec = (time_funct_end.tv_sec - time_funct_start.tv_sec)*1.0 + (time_funct_end.tv_nsec - time_funct_start.tv_nsec)/1000000000.0; \ tprintf(PERF_COUNT_REPORT_STR, funct_name, "total", elapsed_time_sec); #else #define PERF_COUNT_START(FUNCT_NAME) #define PERF_COUNT_END #endif #if PERF_COUNT_VERBOSE >= 3 #define PERF_COUNT_SUB(SUB) \ clock_gettime( CLOCK_MONOTONIC, &time_sub_end ); \ elapsed_time_sec = (time_sub_end.tv_sec - time_sub_start.tv_sec)*1.0 + (time_sub_end.tv_nsec - time_sub_start.tv_nsec)/1000000000.0; \ tprintf(PERF_COUNT_REPORT_STR, funct_name, SUB, elapsed_time_sec); \ time_sub_start = time_sub_end; #else #define PERF_COUNT_SUB(SUB) #endif #endif /************************************************************************** * enable/disable use of OpenCL **************************************************************************/ #ifdef USE_OPENCL #define USE_DEVICE_SELECTION 1 #include "opencl_device_selection.h" #ifndef strcasecmp #define strcasecmp strcmp #endif #define MAX_KERNEL_STRING_LEN 64 #define MAX_CLFILE_NUM 50 #define MAX_CLKERNEL_NUM 200 #define MAX_KERNEL_NAME_LEN 64 #define CL_QUEUE_THREAD_HANDLE_AMD 0x403E #define GROUPSIZE_X 16 #define GROUPSIZE_Y 16 #define GROUPSIZE_HMORX 256 #define GROUPSIZE_HMORY 1 typedef struct _KernelEnv { cl_context mpkContext; cl_command_queue mpkCmdQueue; cl_program mpkProgram; cl_kernel mpkKernel; char mckKernelName[150]; } KernelEnv; typedef struct _OpenCLEnv { cl_platform_id mpOclPlatformID; cl_context mpOclContext; cl_device_id mpOclDevsID; cl_command_queue mpOclCmdQueue; } OpenCLEnv; typedef int ( *cl_kernel_function )( void **userdata, KernelEnv *kenv ); static l_int32 MORPH_BC = ASYMMETRIC_MORPH_BC; static const l_uint32 lmask32[] = {0x0, 0x80000000, 0xc0000000, 0xe0000000, 0xf0000000, 0xf8000000, 0xfc000000, 0xfe000000, 0xff000000, 0xff800000, 0xffc00000, 0xffe00000, 0xfff00000, 0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000, 0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000, 0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00, 0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0, 0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff}; static const l_uint32 rmask32[] = {0x0, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff, 0x0001ffff, 0x0003ffff, 0x0007ffff, 0x000fffff, 0x001fffff, 0x003fffff, 0x007fffff, 0x00ffffff, 0x01ffffff, 0x03ffffff, 0x07ffffff, 0x0fffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff}; #define CHECK_OPENCL(status,name) \ if( status != CL_SUCCESS ) \ { \ printf ("OpenCL error code is %d at when %s .\n", status, name); \ } typedef struct _GPUEnv { //share vb in all modules in hb library cl_platform_id mpPlatformID; cl_device_type mDevType; cl_context mpContext; cl_device_id *mpArryDevsID; cl_device_id mpDevID; cl_command_queue mpCmdQueue; cl_kernel mpArryKernels[MAX_CLFILE_NUM]; cl_program mpArryPrograms[MAX_CLFILE_NUM]; //one program object maps one kernel source file char mArryKnelSrcFile[MAX_CLFILE_NUM][256], //the max len of kernel file name is 256 mArrykernelNames[MAX_CLKERNEL_NUM][MAX_KERNEL_STRING_LEN + 1]; cl_kernel_function mpArryKnelFuncs[MAX_CLKERNEL_NUM]; int mnKernelCount, mnFileCount, // only one kernel file mnIsUserCreated; // 1: created , 0:no create and needed to create by opencl wrapper int mnKhrFp64Flag; int mnAmdFp64Flag; } GPUEnv; class OpenclDevice { public: static GPUEnv gpuEnv; static int isInited; OpenclDevice(); ~OpenclDevice(); static int InitEnv(); // load dll, call InitOpenclRunEnv(0) static int InitOpenclRunEnv( int argc ); // RegistOpenclKernel, double flags, compile kernels static int InitOpenclRunEnv_DeviceSelection( int argc ); // RegistOpenclKernel, double flags, compile kernels static int InitOpenclRunEnv( GPUEnv *gpu ); // select device by env_CPU or selector static int RegistOpenclKernel(); static int ReleaseOpenclRunEnv(); static int ReleaseOpenclEnv( GPUEnv *gpuInfo ); static int CompileKernelFile( GPUEnv *gpuInfo, const char *buildOption ); static int CachedOfKernerPrg( const GPUEnv *gpuEnvCached, const char * clFileName ); static int GeneratBinFromKernelSource( cl_program program, const char * clFileName ); static int WriteBinaryToFile( const char* fileName, const char* birary, size_t numBytes ); static int BinaryGenerated( const char * clFileName, FILE ** fhandle ); //static int CompileKernelFile( const char *filename, GPUEnv *gpuInfo, const char *buildOption ); static l_uint32* pixReadFromTiffKernel(l_uint32 *tiffdata,l_int32 w,l_int32 h,l_int32 wpl, l_uint32 *line); static Pix* pixReadTiffCl( const char *filename, l_int32 n ); static PIX * pixReadStreamTiffCl ( FILE *fp, l_int32 n ); static PIX * pixReadMemTiffCl(const l_uint8 *data, size_t size, l_int32 n); static PIX* pixReadFromTiffStreamCl(TIFF *tif); static int composeRGBPixelCl(int *tiffdata,int *line,int h,int w); static l_int32 getTiffStreamResolutionCl(TIFF *tif,l_int32 *pxres,l_int32 *pyres); static TIFF* fopenTiffCl(FILE *fp,const char *modestring); /* OpenCL implementations of Morphological operations*/ //Initialiation of OCL buffers used in Morph operations static int initMorphCLAllocations(l_int32 wpl, l_int32 h, PIX* pixs); static void releaseMorphCLBuffers(); // OpenCL implementation of Morphology Dilate static PIX* pixDilateBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy); // OpenCL implementation of Morphology Erode static PIX* pixErodeBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy); // OpenCL implementation of Morphology Close static PIX* pixCloseBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy); // OpenCL implementation of Morphology Open static PIX* pixOpenBrickCL(PIX *pixd, PIX *pixs, l_int32 hsize, l_int32 vsize, bool reqDataCopy); // OpenCL implementation of Morphology Open static PIX* pixSubtractCL(PIX *pixd, PIX *pixs1, PIX *pixs2, bool reqDataCopy); // OpenCL implementation of Morphology (Hollow = Closed - Open) static PIX* pixHollowCL(PIX *pixd, PIX *pixs, l_int32 close_hsize, l_int32 close_vsize, l_int32 open_hsize, l_int32 open_vsize, bool reqDataCopy); static void pixGetLinesCL(PIX *pixd, PIX *pixs, PIX** pix_vline, PIX** pix_hline, PIX** pixClosed, bool getpixClosed, l_int32 close_hsize, l_int32 close_vsize, l_int32 open_hsize, l_int32 open_vsize, l_int32 line_hsize, l_int32 line_vsize); //int InitOpenclAttr( OpenCLEnv * env ); //int ReleaseKernel( KernelEnv * env ); static int SetKernelEnv( KernelEnv *envInfo ); //int CreateKernel( char * kernelname, KernelEnv * env ); //int RunKernel( const char *kernelName, void **userdata ); //int ConvertToString( const char *filename, char **source ); //int CheckKernelName( KernelEnv *envInfo, const char *kernelName ); //int RegisterKernelWrapper( const char *kernelName, cl_kernel_function function ); //int RunKernelWrapper( cl_kernel_function function, const char * kernelName, void **usrdata ); //int GetKernelEnvAndFunc( const char *kernelName, KernelEnv *env, cl_kernel_function *function ); // static cl_device_id performDeviceSelection( ); //static bool thresholdRectToPixMicroBench( TessScoreEvaluationInputData input, ds_device_type type); static int LoadOpencl(); #ifdef WIN32 //static int OpenclInite(); static void FreeOpenclDll(); #endif //int GetOpenclState(); //void SetOpenclState( int state ); inline static int AddKernelConfig( int kCount, const char *kName ); /* for binarization */ static void HistogramRectOCL( const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height, int kHistogramSize, int *histogramAllChannels); static void ThresholdRectToPixOCL( const unsigned char* imagedata, int bytes_per_pixel, int bytes_per_line, const int* thresholds, const int* hi_values, Pix** pix, int rect_height, int rect_width, int rect_top, int rect_left); #if USE_DEVICE_SELECTION static ds_device getDeviceSelection(); static ds_device selectedDevice; static bool deviceIsSelected; #endif static bool selectedDeviceIsOpenCL(); static bool selectedDeviceIsNativeCPU(); }; #endif
1080228-arabicocr11
opencl/openclwrapper.h
C++
asf20
12,552
datadir = @datadir@/tessdata/configs data_DATA = inter makebox box.train unlv ambigs.train api_config kannada box.train.stderr quiet logfile digits hocr linebox pdf rebox strokewidth bigram EXTRA_DIST = inter makebox box.train unlv ambigs.train api_config kannada box.train.stderr quiet logfile digits hocr linebox pdf rebox strokewidth bigram
1080228-arabicocr11
tessdata/configs/Makefile.am
Makefile
asf20
344
datadir = @datadir@/tessdata data_DATA = pdf.ttf pdf.ttx EXTRA_DIST = $(data_DATA) SUBDIRS = configs tessconfigs langdata = bul.traineddata mlt.traineddata chr.traineddata \ slk.traineddata dan-frak.traineddata eng.traineddata \ ces.traineddata afr.traineddata swa.traineddata \ kan.traineddata bel.traineddata ind.traineddata \ lit.traineddata nld.traineddata osd.traineddata \ mkd.traineddata est.traineddata fra.traineddata \ hin.traineddata lat_lid.traineddata nor.traineddata \ por.traineddata ron.traineddata swe.traineddata \ pol.traineddata ara.traineddata tel.traineddata \ ell.traineddata mal.traineddata vie.traineddata \ heb.traineddata deu.traineddata eus.traineddata \ ita_old.traineddata rus.traineddata sqi.traineddata \ spa.traineddata glg.traineddata slk-frak.traineddata \ equ.traineddata hrv.traineddata frk.traineddata \ cat.traineddata lav.traineddata ukr.traineddata \ enm.traineddata dan.traineddata fin.traineddata \ ben.traineddata srp.traineddata tha.traineddata \ hun.traineddata tgl.traineddata frm.traineddata \ slv.traineddata chi_sim.traineddata tam.traineddata \ tur.traineddata epo.traineddata msa.traineddata \ kor.traineddata isl.traineddata jpn.traineddata \ chi_tra.traineddata ita.traineddata spa_old.traineddata \ deu-frak.traineddata aze.traineddata fra.cube.lm \ ita.tesseract_cube.nn eng.cube.word-freq rus.cube.lm \ spa.cube.size fra.cube.nn fra.cube.params rus.cube.size \ fra.cube.fold eng.cube.size ita.cube.bigrams \ eng.tesseract_cube.nn rus.cube.params hin.cube.nn \ spa.cube.params hin.cube.lm fra.cube.word-freq \ spa.cube.word-freq ara.cube.nn ara.cube.word-freq \ spa.cube.fold eng.cube.nn eng.cube.params eng.cube.lm \ ita.cube.size hin.tesseract_cube.nn ita.cube.lm \ fra.cube.bigrams ara.cube.fold spa.cube.bigrams \ hin.cube.word-freq rus.cube.word-freq ita.cube.word-freq \ fra.tesseract_cube.nn rus.cube.fold ara.cube.size \ eng.cube.fold ita.cube.params ara.cube.params ita.cube.fold \ ara.cube.bigrams hin.cube.params hin.cube.fold spa.cube.lm \ ita.cube.nn fra.cube.size eng.cube.bigrams ara.cube.lm \ rus.cube.nn spa.cube.nn hin.cube.bigrams .PHONY: install-langs install-langs: @if [ ! -d $(DESTDIR)$(datadir) ]; then mkdir -p $(DESTDIR)$(datadir); fi; @if test "${LANGS}" != ""; then \ for lang_code in ${LANGS}; do \ echo "installing data for $$lang_code"; \ $(INSTALL) -m 644 $(srcdir)/$$lang_code.* $(DESTDIR)$(datadir); \ done; \ else \ for l in ./*.traineddata; do \ filename=`basename $$l`; \ lang_code=$${filename%.*}; \ if test "$$lang_code" == "*"; then \ echo "No lang present."; \ break; \ fi; \ echo "installing data for $$lang_code"; \ $(INSTALL) -m 644 $(srcdir)/$$lang_code.* $(DESTDIR)$(datadir); \ done; \ fi; uninstall-local: cd $(DESTDIR)$(datadir); \ rm -f $(langdata)
1080228-arabicocr11
tessdata/Makefile.am
Makefile
asf20
2,844
datadir = @datadir@/tessdata/tessconfigs data_DATA = batch batch.nochop nobatch matdemo segdemo msdemo EXTRA_DIST = batch batch.nochop nobatch matdemo segdemo msdemo
1080228-arabicocr11
tessdata/tessconfigs/Makefile.am
Makefile
asf20
166
#!/bin/sh # This is a simple script which is meant to help developers # better deal with the GNU autotools, specifically: # # aclocal # autoheader # autoconf # automake # # The whole thing is quite complex... # # The idea is to run this collection of tools on a single platform, # typically the main development platform, running a recent version of # autoconf. In theory, if we had these tools on each platform where we # ever expected to port the software, we would never need to checkin # more than a few autotools configuration files. However, the whole # idea is to generate a configure script and associated files in a way # that is portable across platforms, so we *have* to check in a whole # bunch of files generated by all these tools. # The real source files are: # # acinclude.m4 (used by aclocal) # configure.ac (main autoconf file) # Makefile.am, */Makefile.am (automake config files) # # All the rest is auto-generated. if [ "$1" == "clean" ]; then echo "Cleaning..." rm configure aclocal.m4 rm m4/* rmdir m4 rm config/* rmdir config find . -iname "Makefile.in" -type f -exec rm '{}' + fi # create m4 directory if it not exists if [ ! -d m4 ]; then mkdir m4 fi bail_out() { echo echo " Something went wrong, bailing out!" echo exit 1 } # --- Step 1: Generate aclocal.m4 from: # . acinclude.m4 # . config/*.m4 (these files are referenced in acinclude.m4) mkdir -p config echo "Running aclocal" aclocal -I config || bail_out # --- Step 2: echo "Running libtoolize" libtoolize -f -c || glibtoolize -f -c || bail_out libtoolize --automake || glibtoolize --automake || bail_out # --- Step 3: Generate config.h.in from: # . configure.ac (look for AM_CONFIG_HEADER tag or AC_CONFIG_HEADER tag) echo "Running autoheader" autoheader -f || bail_out # --- Step 4: Generate Makefile.in, src/Makefile.in, and a whole bunch of # files in config (config.guess, config.sub, depcomp, # install-sh, missing, mkinstalldirs) plus COPYING and # INSTALL from: # . Makefile.am # . src/Makefile.am # # Using --add-missing --copy makes sure that, if these files are missing, # they are copied from the system so they can be used in a distribution. echo "Running automake --add-missing --copy" automake --add-missing -c -Wno-portability > /dev/null || bail_out # --- Step 5: Generate configure and include/miaconfig.h from: # . configure.ac # echo "Running autoconf" autoconf || bail_out echo "" echo "All done." echo "To build the software now, do something like:" echo "" echo "$ ./configure [--enable-debug] [...other options]"
1080228-arabicocr11
autogen.sh
Shell
asf20
2,706
/* -*-C-*- ******************************************************************************** * * File: context.c (Formerly context.c) * Description: Context checking functions * Author: Mark Seaman, OCR Technology * Created: Thu Feb 15 11:18:24 1990 * Modified: Tue Jul 9 17:38:16 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1990, Hewlett-Packard Company. ** 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. * *********************************************************************************/ #include "dict.h" #include "tprintf.h" #include "unicharset.h" namespace tesseract { static const int kMinAbsoluteGarbageWordLength = 10; static const float kMinAbsoluteGarbageAlphanumFrac = 0.5f; const int case_state_table[6][4] = { { /* 0. Begining of word */ /* P U L D */ /* -1. Error on case */ 0, 1, 5, 4 }, { /* 1. After initial capital */ 0, 3, 2, 4 }, { /* 2. After lower case */ 0, -1, 2, -1 }, { /* 3. After upper case */ 0, 3, -1, 4 }, { /* 4. After a digit */ 0, -1, -1, 4 }, { /* 5. After initial lower case */ 5, -1, 2, -1 }, }; int Dict::case_ok(const WERD_CHOICE &word, const UNICHARSET &unicharset) { int state = 0; int x; for (x = 0; x < word.length(); ++x) { UNICHAR_ID ch_id = word.unichar_id(x); if (unicharset.get_isupper(ch_id)) state = case_state_table[state][1]; else if (unicharset.get_islower(ch_id)) state = case_state_table[state][2]; else if (unicharset.get_isdigit(ch_id)) state = case_state_table[state][3]; else state = case_state_table[state][0]; if (state == -1) return false; } return state != 5; // single lower is bad } bool Dict::absolute_garbage(const WERD_CHOICE &word, const UNICHARSET &unicharset) { if (word.length() < kMinAbsoluteGarbageWordLength) return false; int num_alphanum = 0; for (int x = 0; x < word.length(); ++x) { num_alphanum += (unicharset.get_isalpha(word.unichar_id(x)) || unicharset.get_isdigit(word.unichar_id(x))); } return (static_cast<float>(num_alphanum) / static_cast<float>(word.length()) < kMinAbsoluteGarbageAlphanumFrac); } } // namespace tesseract
1080228-arabicocr11
dict/context.cpp
C
asf20
3,180
/* -*-C-*- ******************************************************************************** * * File: trie.h (Formerly trie.h) * Description: Functions to build a trie data structure. * Author: Mark Seaman, SW Productivity * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri Jul 26 11:26:34 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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 TRIE_H #define TRIE_H #include "dawg.h" #include "cutil.h" #include "genericvector.h" class UNICHARSET; // Note: if we consider either NODE_REF or EDGE_INDEX to ever exceed // max int32, we will need to change GenericVector to use int64 for size // and address indices. This does not seem to be needed immediately, // since currently the largest number of edges limit used by tesseract // (kMaxNumEdges in wordlist2dawg.cpp) is far less than max int32. // There are also int casts below to satisfy the WIN32 compiler that would // need to be changed. // It might be cleanest to change the types of most of the Trie/Dawg related // typedefs to int and restrict the casts to extracting these values from // the 64 bit EDGE_RECORD. typedef inT64 EDGE_INDEX; // index of an edge in a given node typedef bool *NODE_MARKER; typedef GenericVector<EDGE_RECORD> EDGE_VECTOR; struct TRIE_NODE_RECORD { EDGE_VECTOR forward_edges; EDGE_VECTOR backward_edges; }; typedef GenericVector<TRIE_NODE_RECORD *> TRIE_NODES; namespace tesseract { /** * Concrete class for Trie data structure that allows to store a list of * words (extends Dawg base class) as well as dynamically add new words. * This class stores a vector of pointers to TRIE_NODE_RECORDs, each of * which has a vector of forward and backward edges. */ class Trie : public Dawg { public: enum RTLReversePolicy { RRP_DO_NO_REVERSE, RRP_REVERSE_IF_HAS_RTL, RRP_FORCE_REVERSE, }; // Minimum number of concrete characters at the beginning of user patterns. static const int kSaneNumConcreteChars = 0; // Various unicode whitespace characters are used to denote unichar patterns, // (character classifier would never produce these whitespace characters as a // valid classification). static const char kAlphaPatternUnicode[]; static const char kDigitPatternUnicode[]; static const char kAlphanumPatternUnicode[]; static const char kPuncPatternUnicode[]; static const char kLowerPatternUnicode[]; static const char kUpperPatternUnicode[]; static const char *get_reverse_policy_name( RTLReversePolicy reverse_policy); // max_num_edges argument allows limiting the amount of memory this // Trie can consume (if a new word insert would cause the Trie to // contain more edges than max_num_edges, all the edges are cleared // so that new inserts can proceed). Trie(DawgType type, const STRING &lang, PermuterType perm, int unicharset_size, int debug_level) { init(type, lang, perm, unicharset_size, debug_level); num_edges_ = 0; deref_node_index_mask_ = ~letter_mask_; new_dawg_node(); // need to allocate node 0 initialized_patterns_ = false; } virtual ~Trie() { nodes_.delete_data_pointers(); } // Reset the Trie to empty. void clear(); /** Returns the edge that corresponds to the letter out of this node. */ EDGE_REF edge_char_of(NODE_REF node_ref, UNICHAR_ID unichar_id, bool word_end) const { EDGE_RECORD *edge_ptr; EDGE_INDEX edge_index; if (!edge_char_of(node_ref, NO_EDGE, FORWARD_EDGE, word_end, unichar_id, &edge_ptr, &edge_index)) return NO_EDGE; return make_edge_ref(node_ref, edge_index); } /** * Fills the given NodeChildVector with all the unichar ids (and the * corresponding EDGE_REFs) for which there is an edge out of this node. */ void unichar_ids_of(NODE_REF node, NodeChildVector *vec, bool word_end) const { const EDGE_VECTOR &forward_edges = nodes_[static_cast<int>(node)]->forward_edges; for (int i = 0; i < forward_edges.size(); ++i) { if (!word_end || end_of_word_from_edge_rec(forward_edges[i])) { vec->push_back(NodeChild(unichar_id_from_edge_rec(forward_edges[i]), make_edge_ref(node, i))); } } } /** * Returns the next node visited by following the edge * indicated by the given EDGE_REF. */ NODE_REF next_node(EDGE_REF edge_ref) const { if (edge_ref == NO_EDGE || num_edges_ == 0) return NO_EDGE; return next_node_from_edge_rec(*deref_edge_ref(edge_ref)); } /** * Returns true if the edge indicated by the given EDGE_REF * marks the end of a word. */ bool end_of_word(EDGE_REF edge_ref) const { if (edge_ref == NO_EDGE || num_edges_ == 0) return false; return end_of_word_from_edge_rec(*deref_edge_ref(edge_ref)); } /** Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF. */ UNICHAR_ID edge_letter(EDGE_REF edge_ref) const { if (edge_ref == NO_EDGE || num_edges_ == 0) return INVALID_UNICHAR_ID; return unichar_id_from_edge_rec(*deref_edge_ref(edge_ref)); } // Sets the UNICHAR_ID in the given edge_rec to unicharset_size_, marking // the edge dead. void KillEdge(EDGE_RECORD* edge_rec) const { *edge_rec &= ~letter_mask_; *edge_rec |= (unicharset_size_ << LETTER_START_BIT); } bool DeadEdge(const EDGE_RECORD& edge_rec) const { return unichar_id_from_edge_rec(edge_rec) == unicharset_size_; } // Prints the contents of the node indicated by the given NODE_REF. // At most max_num_edges will be printed. void print_node(NODE_REF node, int max_num_edges) const; // Writes edges from nodes_ to an EDGE_ARRAY and creates a SquishedDawg. // Eliminates redundant edges and returns the pointer to the SquishedDawg. // Note: the caller is responsible for deallocating memory associated // with the returned SquishedDawg pointer. SquishedDawg *trie_to_dawg(); // Reads a list of words from the given file and adds into the Trie. // Calls WERD_CHOICE::reverse_unichar_ids_if_rtl() according to the reverse // policy and information in the unicharset. // Returns false on error. bool read_and_add_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse); // Reads a list of words from the given file, applying the reverse_policy, // according to information in the unicharset. // Returns false on error. bool read_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse_policy, GenericVector<STRING>* words); // Adds a list of words previously read using read_word_list to the trie // using the given unicharset to convert to unichar-ids. // Returns false on error. bool add_word_list(const GenericVector<STRING>& words, const UNICHARSET &unicharset); // Inserts the list of patterns from the given file into the Trie. // The pattern list file should contain one pattern per line in UTF-8 format. // // Each pattern can contain any non-whitespace characters, however only the // patterns that contain characters from the unicharset of the corresponding // language will be useful. // The only meta character is '\'. To be used in a pattern as an ordinary // string it should be escaped with '\' (e.g. string "C:\Documents" should // be written in the patterns file as "C:\\Documents"). // This function supports a very limited regular expression syntax. One can // express a character, a certain character class and a number of times the // entity should be repeated in the pattern. // // To denote a character class use one of: // \c - unichar for which UNICHARSET::get_isalpha() is true (character) // \d - unichar for which UNICHARSET::get_isdigit() is true // \n - unichar for which UNICHARSET::get_isdigit() and // UNICHARSET::isalpha() are true // \p - unichar for which UNICHARSET::get_ispunct() is true // \a - unichar for which UNICHARSET::get_islower() is true // \A - unichar for which UNICHARSET::get_isupper() is true // // \* could be specified after each character or pattern to indicate that // the character/pattern can be repeated any number of times before the next // character/pattern occurs. // // Examples: // 1-8\d\d-GOOG-411 will be expanded to strings: // 1-800-GOOG-411, 1-801-GOOG-411, ... 1-899-GOOG-411. // // http://www.\n\*.com will be expanded to strings like: // http://www.a.com http://www.a123.com ... http://www.ABCDefgHIJKLMNop.com // // Note: In choosing which patterns to include please be aware of the fact // providing very generic patterns will make tesseract run slower. // For example \n\* at the beginning of the pattern will make Tesseract // consider all the combinations of proposed character choices for each // of the segmentations, which will be unacceptably slow. // Because of potential problems with speed that could be difficult to // identify, each user pattern has to have at least kSaneNumConcreteChars // concrete characters from the unicharset at the beginning. bool read_pattern_list(const char *filename, const UNICHARSET &unicharset); // Initializes the values of *_pattern_ unichar ids. // This function should be called before calling read_pattern_list(). void initialize_patterns(UNICHARSET *unicharset); // Fills in the given unichar id vector with the unichar ids that represent // the patterns of the character classes of the given unichar_id. void unichar_id_to_patterns(UNICHAR_ID unichar_id, const UNICHARSET &unicharset, GenericVector<UNICHAR_ID> *vec) const; // Returns the given EDGE_REF if the EDGE_RECORD that it points to has // a self loop and the given unichar_id matches the unichar_id stored in the // EDGE_RECORD, returns NO_EDGE otherwise. virtual EDGE_REF pattern_loop_edge(EDGE_REF edge_ref, UNICHAR_ID unichar_id, bool word_end) const { if (edge_ref == NO_EDGE) return NO_EDGE; EDGE_RECORD *edge_rec = deref_edge_ref(edge_ref); return (marker_flag_from_edge_rec(*edge_rec) && unichar_id == unichar_id_from_edge_rec(*edge_rec) && word_end == end_of_word_from_edge_rec(*edge_rec)) ? edge_ref : NO_EDGE; } // Adds a word to the Trie (creates the necessary nodes and edges). // // If repetitions vector is not NULL, each entry in the vector indicates // whether the unichar id with the corresponding index in the word is allowed // to repeat an unlimited number of times. For each entry that is true, MARKER // flag of the corresponding edge created for this unichar id is set to true). // // Return true if add succeeded, false otherwise (e.g. when a word contained // an invalid unichar id or the trie was getting too large and was cleared). bool add_word_to_dawg(const WERD_CHOICE &word, const GenericVector<bool> *repetitions); bool add_word_to_dawg(const WERD_CHOICE &word) { return add_word_to_dawg(word, NULL); } protected: // The structure of an EDGE_REF for Trie edges is as follows: // [LETTER_START_BIT, flag_start_bit_): // edge index in *_edges in a TRIE_NODE_RECORD // [flag_start_bit, 30th bit]: node index in nodes (TRIE_NODES vector) // // With this arrangement there are enough bits to represent edge indices // (each node can have at most unicharset_size_ forward edges and // the position of flag_start_bit is set to be log2(unicharset_size_)). // It is also possible to accommodate a maximum number of nodes that is at // least as large as that of the SquishedDawg representation (in SquishedDawg // each EDGE_RECORD has 32-(flag_start_bit+NUM_FLAG_BITS) bits to represent // the next node index). // // Returns the pointer to EDGE_RECORD after decoding the location // of the edge from the information in the given EDGE_REF. // This function assumes that EDGE_REF holds valid node/edge indices. inline EDGE_RECORD *deref_edge_ref(EDGE_REF edge_ref) const { int edge_index = static_cast<int>( (edge_ref & letter_mask_) >> LETTER_START_BIT); int node_index = static_cast<int>( (edge_ref & deref_node_index_mask_) >> flag_start_bit_); TRIE_NODE_RECORD *node_rec = nodes_[node_index]; return &(node_rec->forward_edges[edge_index]); } /** Constructs EDGE_REF from the given node_index and edge_index. */ inline EDGE_REF make_edge_ref(NODE_REF node_index, EDGE_INDEX edge_index) const { return ((node_index << flag_start_bit_) | (edge_index << LETTER_START_BIT)); } /** Sets up this edge record to the requested values. */ inline void link_edge(EDGE_RECORD *edge, NODE_REF nxt, bool repeats, int direction, bool word_end, UNICHAR_ID unichar_id) { EDGE_RECORD flags = 0; if (repeats) flags |= MARKER_FLAG; if (word_end) flags |= WERD_END_FLAG; if (direction == BACKWARD_EDGE) flags |= DIRECTION_FLAG; *edge = ((nxt << next_node_start_bit_) | (static_cast<EDGE_RECORD>(flags) << flag_start_bit_) | (static_cast<EDGE_RECORD>(unichar_id) << LETTER_START_BIT)); } /** Prints the given EDGE_RECORD. */ inline void print_edge_rec(const EDGE_RECORD &edge_rec) const { tprintf("|" REFFORMAT "|%s%s%s|%d|", next_node_from_edge_rec(edge_rec), marker_flag_from_edge_rec(edge_rec) ? "R," : "", (direction_from_edge_rec(edge_rec) == FORWARD_EDGE) ? "F" : "B", end_of_word_from_edge_rec(edge_rec) ? ",E" : "", unichar_id_from_edge_rec(edge_rec)); } // Returns true if the next node in recorded the given EDGE_RECORD // has exactly one forward edge. inline bool can_be_eliminated(const EDGE_RECORD &edge_rec) { NODE_REF node_ref = next_node_from_edge_rec(edge_rec); return (node_ref != NO_EDGE && nodes_[static_cast<int>(node_ref)]->forward_edges.size() == 1); } // Prints the contents of the Trie. // At most max_num_edges will be printed for each node. void print_all(const char* msg, int max_num_edges) { tprintf("\n__________________________\n%s\n", msg); for (int i = 0; i < nodes_.size(); ++i) print_node(i, max_num_edges); tprintf("__________________________\n"); } // Finds the edge with the given direction, word_end and unichar_id // in the node indicated by node_ref. Fills in the pointer to the // EDGE_RECORD and the index of the edge with the the values // corresponding to the edge found. Returns true if an edge was found. bool edge_char_of(NODE_REF node_ref, NODE_REF next_node, int direction, bool word_end, UNICHAR_ID unichar_id, EDGE_RECORD **edge_ptr, EDGE_INDEX *edge_index) const; // Adds an single edge linkage between node1 and node2 in the direction // indicated by direction argument. bool add_edge_linkage(NODE_REF node1, NODE_REF node2, bool repeats, int direction, bool word_end, UNICHAR_ID unichar_id); // Adds forward edge linkage from node1 to node2 and the corresponding // backward edge linkage in the other direction. bool add_new_edge(NODE_REF node1, NODE_REF node2, bool repeats, bool word_end, UNICHAR_ID unichar_id) { return (add_edge_linkage(node1, node2, repeats, FORWARD_EDGE, word_end, unichar_id) && add_edge_linkage(node2, node1, repeats, BACKWARD_EDGE, word_end, unichar_id)); } // Sets the word ending flags in an already existing edge pair. // Returns true on success. void add_word_ending(EDGE_RECORD *edge, NODE_REF the_next_node, bool repeats, UNICHAR_ID unichar_id); // Allocates space for a new node in the Trie. NODE_REF new_dawg_node(); // Removes a single edge linkage to between node1 and node2 in the // direction indicated by direction argument. void remove_edge_linkage(NODE_REF node1, NODE_REF node2, int direction, bool word_end, UNICHAR_ID unichar_id); // Removes forward edge linkage from node1 to node2 and the corresponding // backward edge linkage in the other direction. void remove_edge(NODE_REF node1, NODE_REF node2, bool word_end, UNICHAR_ID unichar_id) { remove_edge_linkage(node1, node2, FORWARD_EDGE, word_end, unichar_id); remove_edge_linkage(node2, node1, BACKWARD_EDGE, word_end, unichar_id); } // Compares edge1 and edge2 in the given node to see if they point to two // next nodes that could be collapsed. If they do, performs the reduction // and returns true. bool eliminate_redundant_edges(NODE_REF node, const EDGE_RECORD &edge1, const EDGE_RECORD &edge2); // Assuming that edge_index indicates the first edge in a group of edges // in this node with a particular letter value, looks through these edges // to see if any of them can be collapsed. If so does it. Returns to the // caller when all edges with this letter have been reduced. // Returns true if further reduction is possible with this same letter. bool reduce_lettered_edges(EDGE_INDEX edge_index, UNICHAR_ID unichar_id, NODE_REF node, EDGE_VECTOR* backward_edges, NODE_MARKER reduced_nodes); /** * Order num_edges of consequtive EDGE_RECORDS in the given EDGE_VECTOR in * increasing order of unichar ids. This function is normally called * for all edges in a single node, and since number of edges in each node * is usually quite small, selection sort is used. */ void sort_edges(EDGE_VECTOR *edges); /** Eliminates any redundant edges from this node in the Trie. */ void reduce_node_input(NODE_REF node, NODE_MARKER reduced_nodes); // Returns the pattern unichar id for the given character class code. UNICHAR_ID character_class_to_pattern(char ch); // Member variables TRIE_NODES nodes_; // vector of nodes in the Trie uinT64 num_edges_; // sum of all edges (forward and backward) uinT64 deref_direction_mask_; // mask for EDGE_REF to extract direction uinT64 deref_node_index_mask_; // mask for EDGE_REF to extract node index // Freelist of edges in the root backwards node that were previously zeroed. GenericVector<EDGE_INDEX> root_back_freelist_; // Variables for translating character class codes denoted in user patterns // file to the unichar ids used to represent them in a Trie. bool initialized_patterns_; UNICHAR_ID alpha_pattern_; UNICHAR_ID digit_pattern_; UNICHAR_ID alphanum_pattern_; UNICHAR_ID punc_pattern_; UNICHAR_ID lower_pattern_; UNICHAR_ID upper_pattern_; }; } // namespace tesseract #endif
1080228-arabicocr11
dict/trie.h
C
asf20
19,920
/****************************************************************************** ** Filename: stopper.c ** Purpose: Stopping criteria for word classifier. ** Author: Dan Johnson ** History: Mon Apr 29 14:56:49 1991, DSJ, Created. ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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. ******************************************************************************/ #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> #include "stopper.h" #include "ambigs.h" #include "ccutil.h" #include "const.h" #include "danerror.h" #include "dict.h" #include "efio.h" #include "helpers.h" #include "matchdefs.h" #include "pageres.h" #include "params.h" #include "ratngs.h" #include "scanutils.h" #include "unichar.h" #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4800) // int/bool warnings #endif using tesseract::ScriptPos; /**---------------------------------------------------------------------------- Private Code ----------------------------------------------------------------------------**/ namespace tesseract { bool Dict::AcceptableChoice(const WERD_CHOICE& best_choice, XHeightConsistencyEnum xheight_consistency) { float CertaintyThreshold = stopper_nondict_certainty_base; int WordSize; if (stopper_no_acceptable_choices) return false; if (best_choice.length() == 0) return false; bool no_dang_ambigs = !best_choice.dangerous_ambig_found(); bool is_valid_word = valid_word_permuter(best_choice.permuter(), false); bool is_case_ok = case_ok(best_choice, getUnicharset()); if (stopper_debug_level >= 1) { const char *xht = "UNKNOWN"; switch (xheight_consistency) { case XH_GOOD: xht = "NORMAL"; break; case XH_SUBNORMAL: xht = "SUBNORMAL"; break; case XH_INCONSISTENT: xht = "INCONSISTENT"; break; default: xht = "UNKNOWN"; } tprintf("\nStopper: %s (word=%c, case=%c, xht_ok=%s=[%g,%g])\n", best_choice.unichar_string().string(), (is_valid_word ? 'y' : 'n'), (is_case_ok ? 'y' : 'n'), xht, best_choice.min_x_height(), best_choice.max_x_height()); } // Do not accept invalid words in PASS1. if (reject_offset_ <= 0.0f && !is_valid_word) return false; if (is_valid_word && is_case_ok) { WordSize = LengthOfShortestAlphaRun(best_choice); WordSize -= stopper_smallword_size; if (WordSize < 0) WordSize = 0; CertaintyThreshold += WordSize * stopper_certainty_per_char; } if (stopper_debug_level >= 1) tprintf("Stopper: Rating = %4.1f, Certainty = %4.1f, Threshold = %4.1f\n", best_choice.rating(), best_choice.certainty(), CertaintyThreshold); if (no_dang_ambigs && best_choice.certainty() > CertaintyThreshold && xheight_consistency < XH_INCONSISTENT && UniformCertainties(best_choice)) { return true; } else { if (stopper_debug_level >= 1) { tprintf("AcceptableChoice() returned false" " (no_dang_ambig:%d cert:%.4g thresh:%g uniform:%d)\n", no_dang_ambigs, best_choice.certainty(), CertaintyThreshold, UniformCertainties(best_choice)); } return false; } } bool Dict::AcceptableResult(WERD_RES* word) { if (word->best_choice == NULL) return false; float CertaintyThreshold = stopper_nondict_certainty_base - reject_offset_; int WordSize; if (stopper_debug_level >= 1) { tprintf("\nRejecter: %s (word=%c, case=%c, unambig=%c, multiple=%c)\n", word->best_choice->debug_string().string(), (valid_word(*word->best_choice) ? 'y' : 'n'), (case_ok(*word->best_choice, getUnicharset()) ? 'y' : 'n'), word->best_choice->dangerous_ambig_found() ? 'n' : 'y', word->best_choices.singleton() ? 'n' : 'y'); } if (word->best_choice->length() == 0 || !word->best_choices.singleton()) return false; if (valid_word(*word->best_choice) && case_ok(*word->best_choice, getUnicharset())) { WordSize = LengthOfShortestAlphaRun(*word->best_choice); WordSize -= stopper_smallword_size; if (WordSize < 0) WordSize = 0; CertaintyThreshold += WordSize * stopper_certainty_per_char; } if (stopper_debug_level >= 1) tprintf("Rejecter: Certainty = %4.1f, Threshold = %4.1f ", word->best_choice->certainty(), CertaintyThreshold); if (word->best_choice->certainty() > CertaintyThreshold && !stopper_no_acceptable_choices) { if (stopper_debug_level >= 1) tprintf("ACCEPTED\n"); return true; } else { if (stopper_debug_level >= 1) tprintf("REJECTED\n"); return false; } } bool Dict::NoDangerousAmbig(WERD_CHOICE *best_choice, DANGERR *fixpt, bool fix_replaceable, MATRIX *ratings) { if (stopper_debug_level > 2) { tprintf("\nRunning NoDangerousAmbig() for %s\n", best_choice->debug_string().string()); } // Construct BLOB_CHOICE_LIST_VECTOR with ambiguities // for each unichar id in BestChoice. BLOB_CHOICE_LIST_VECTOR ambig_blob_choices; int i; bool ambigs_found = false; // For each position in best_choice: // -- choose AMBIG_SPEC_LIST that corresponds to unichar_id at best_choice[i] // -- initialize wrong_ngram with a single unichar_id at best_choice[i] // -- look for ambiguities corresponding to wrong_ngram in the list while // adding the following unichar_ids from best_choice to wrong_ngram // // Repeat the above procedure twice: first time look through // ambigs to be replaced and replace all the ambiguities found; // second time look through dangerous ambiguities and construct // ambig_blob_choices with fake a blob choice for each ambiguity // and pass them to dawg_permute_and_select() to search for // ambiguous words in the dictionaries. // // Note that during the execution of the for loop (on the first pass) // if replacements are made the length of best_choice might change. for (int pass = 0; pass < (fix_replaceable ? 2 : 1); ++pass) { bool replace = (fix_replaceable && pass == 0); const UnicharAmbigsVector &table = replace ? getUnicharAmbigs().replace_ambigs() : getUnicharAmbigs().dang_ambigs(); if (!replace) { // Initialize ambig_blob_choices with lists containing a single // unichar id for the correspoding position in best_choice. // best_choice consisting from only the original letters will // have a rating of 0.0. for (i = 0; i < best_choice->length(); ++i) { BLOB_CHOICE_LIST *lst = new BLOB_CHOICE_LIST(); BLOB_CHOICE_IT lst_it(lst); // TODO(rays/antonova) Put real xheights and y shifts here. lst_it.add_to_end(new BLOB_CHOICE(best_choice->unichar_id(i), 0.0, 0.0, -1, -1, -1, 0, 1, 0, BCC_AMBIG)); ambig_blob_choices.push_back(lst); } } UNICHAR_ID wrong_ngram[MAX_AMBIG_SIZE + 1]; int wrong_ngram_index; int next_index; int blob_index = 0; for (i = 0; i < best_choice->length(); blob_index += best_choice->state(i), ++i) { UNICHAR_ID curr_unichar_id = best_choice->unichar_id(i); if (stopper_debug_level > 2) { tprintf("Looking for %s ngrams starting with %s:\n", replace ? "replaceable" : "ambiguous", getUnicharset().debug_str(curr_unichar_id).string()); } int num_wrong_blobs = best_choice->state(i); wrong_ngram_index = 0; wrong_ngram[wrong_ngram_index] = curr_unichar_id; if (curr_unichar_id == INVALID_UNICHAR_ID || curr_unichar_id >= table.size() || table[curr_unichar_id] == NULL) { continue; // there is no ambig spec for this unichar id } AmbigSpec_IT spec_it(table[curr_unichar_id]); for (spec_it.mark_cycle_pt(); !spec_it.cycled_list();) { const AmbigSpec *ambig_spec = spec_it.data(); wrong_ngram[wrong_ngram_index+1] = INVALID_UNICHAR_ID; int compare = UnicharIdArrayUtils::compare(wrong_ngram, ambig_spec->wrong_ngram); if (stopper_debug_level > 2) { tprintf("candidate ngram: "); UnicharIdArrayUtils::print(wrong_ngram, getUnicharset()); tprintf("current ngram from spec: "); UnicharIdArrayUtils::print(ambig_spec->wrong_ngram, getUnicharset()); tprintf("comparison result: %d\n", compare); } if (compare == 0) { // Record the place where we found an ambiguity. if (fixpt != NULL) { UNICHAR_ID leftmost_id = ambig_spec->correct_fragments[0]; fixpt->push_back(DANGERR_INFO( blob_index, blob_index + num_wrong_blobs, replace, getUnicharset().get_isngram(ambig_spec->correct_ngram_id), leftmost_id)); if (stopper_debug_level > 1) { tprintf("fixpt+=(%d %d %d %d %s)\n", blob_index, blob_index + num_wrong_blobs, false, getUnicharset().get_isngram( ambig_spec->correct_ngram_id), getUnicharset().id_to_unichar(leftmost_id)); } } if (replace) { if (stopper_debug_level > 2) { tprintf("replace ambiguity with %s : ", getUnicharset().id_to_unichar( ambig_spec->correct_ngram_id)); UnicharIdArrayUtils::print( ambig_spec->correct_fragments, getUnicharset()); } ReplaceAmbig(i, ambig_spec->wrong_ngram_size, ambig_spec->correct_ngram_id, best_choice, ratings); } else if (i > 0 || ambig_spec->type != CASE_AMBIG) { // We found dang ambig - update ambig_blob_choices. if (stopper_debug_level > 2) { tprintf("found ambiguity: "); UnicharIdArrayUtils::print( ambig_spec->correct_fragments, getUnicharset()); } ambigs_found = true; for (int tmp_index = 0; tmp_index <= wrong_ngram_index; ++tmp_index) { // Add a blob choice for the corresponding fragment of the // ambiguity. These fake blob choices are initialized with // negative ratings (which are not possible for real blob // choices), so that dawg_permute_and_select() considers any // word not consisting of only the original letters a better // choice and stops searching for alternatives once such a // choice is found. BLOB_CHOICE_IT bc_it(ambig_blob_choices[i+tmp_index]); bc_it.add_to_end(new BLOB_CHOICE( ambig_spec->correct_fragments[tmp_index], -1.0, 0.0, -1, -1, -1, 0, 1, 0, BCC_AMBIG)); } } spec_it.forward(); } else if (compare == -1) { if (wrong_ngram_index+1 < ambig_spec->wrong_ngram_size && ((next_index = wrong_ngram_index+1+i) < best_choice->length())) { // Add the next unichar id to wrong_ngram and keep looking for // more ambigs starting with curr_unichar_id in AMBIG_SPEC_LIST. wrong_ngram[++wrong_ngram_index] = best_choice->unichar_id(next_index); num_wrong_blobs += best_choice->state(next_index); } else { break; // no more matching ambigs in this AMBIG_SPEC_LIST } } else { spec_it.forward(); } } // end searching AmbigSpec_LIST } // end searching best_choice } // end searching replace and dangerous ambigs // If any ambiguities were found permute the constructed ambig_blob_choices // to see if an alternative dictionary word can be found. if (ambigs_found) { if (stopper_debug_level > 2) { tprintf("\nResulting ambig_blob_choices:\n"); for (i = 0; i < ambig_blob_choices.length(); ++i) { print_ratings_list("", ambig_blob_choices.get(i), getUnicharset()); tprintf("\n"); } } WERD_CHOICE *alt_word = dawg_permute_and_select(ambig_blob_choices, 0.0); ambigs_found = (alt_word->rating() < 0.0); if (ambigs_found) { if (stopper_debug_level >= 1) { tprintf ("Stopper: Possible ambiguous word = %s\n", alt_word->debug_string().string()); } if (fixpt != NULL) { // Note: Currently character choices combined from fragments can only // be generated by NoDangrousAmbigs(). This code should be updated if // the capability to produce classifications combined from character // fragments is added to other functions. int orig_i = 0; for (i = 0; i < alt_word->length(); ++i) { const UNICHARSET &uchset = getUnicharset(); bool replacement_is_ngram = uchset.get_isngram(alt_word->unichar_id(i)); UNICHAR_ID leftmost_id = alt_word->unichar_id(i); if (replacement_is_ngram) { // we have to extract the leftmost unichar from the ngram. const char *str = uchset.id_to_unichar(leftmost_id); int step = uchset.step(str); if (step) leftmost_id = uchset.unichar_to_id(str, step); } int end_i = orig_i + alt_word->state(i); if (alt_word->state(i) > 1 || (orig_i + 1 == end_i && replacement_is_ngram)) { // Compute proper blob indices. int blob_start = 0; for (int j = 0; j < orig_i; ++j) blob_start += best_choice->state(j); int blob_end = blob_start; for (int j = orig_i; j < end_i; ++j) blob_end += best_choice->state(j); fixpt->push_back(DANGERR_INFO(blob_start, blob_end, true, replacement_is_ngram, leftmost_id)); if (stopper_debug_level > 1) { tprintf("fixpt->dangerous+=(%d %d %d %d %s)\n", orig_i, end_i, true, replacement_is_ngram, uchset.id_to_unichar(leftmost_id)); } } orig_i += alt_word->state(i); } } } delete alt_word; } if (output_ambig_words_file_ != NULL) { fprintf(output_ambig_words_file_, "\n"); } ambig_blob_choices.delete_data_pointers(); return !ambigs_found; } void Dict::EndDangerousAmbigs() {} void Dict::SettupStopperPass1() { reject_offset_ = 0.0; } void Dict::SettupStopperPass2() { reject_offset_ = stopper_phase2_certainty_rejection_offset; } void Dict::ReplaceAmbig(int wrong_ngram_begin_index, int wrong_ngram_size, UNICHAR_ID correct_ngram_id, WERD_CHOICE *werd_choice, MATRIX *ratings) { int num_blobs_to_replace = 0; int begin_blob_index = 0; int i; // Rating and certainty for the new BLOB_CHOICE are derived from the // replaced choices. float new_rating = 0.0f; float new_certainty = 0.0f; BLOB_CHOICE* old_choice = NULL; for (i = 0; i < wrong_ngram_begin_index + wrong_ngram_size; ++i) { if (i >= wrong_ngram_begin_index) { int num_blobs = werd_choice->state(i); int col = begin_blob_index + num_blobs_to_replace; int row = col + num_blobs - 1; BLOB_CHOICE_LIST* choices = ratings->get(col, row); ASSERT_HOST(choices != NULL); old_choice = FindMatchingChoice(werd_choice->unichar_id(i), choices); ASSERT_HOST(old_choice != NULL); new_rating += old_choice->rating(); new_certainty += old_choice->certainty(); num_blobs_to_replace += num_blobs; } else { begin_blob_index += werd_choice->state(i); } } new_certainty /= wrong_ngram_size; // If there is no entry in the ratings matrix, add it. MATRIX_COORD coord(begin_blob_index, begin_blob_index + num_blobs_to_replace - 1); if (!coord.Valid(*ratings)) { ratings->IncreaseBandSize(coord.row - coord.col + 1); } if (ratings->get(coord.col, coord.row) == NULL) ratings->put(coord.col, coord.row, new BLOB_CHOICE_LIST); BLOB_CHOICE_LIST* new_choices = ratings->get(coord.col, coord.row); BLOB_CHOICE* choice = FindMatchingChoice(correct_ngram_id, new_choices); if (choice != NULL) { // Already there. Upgrade if new rating better. if (new_rating < choice->rating()) choice->set_rating(new_rating); if (new_certainty < choice->certainty()) choice->set_certainty(new_certainty); // DO NOT SORT!! It will mess up the iterator in LanguageModel::UpdateState. } else { // Need a new choice with the correct_ngram_id. choice = new BLOB_CHOICE(*old_choice); choice->set_unichar_id(correct_ngram_id); choice->set_rating(new_rating); choice->set_certainty(new_certainty); choice->set_classifier(BCC_AMBIG); choice->set_matrix_cell(coord.col, coord.row); BLOB_CHOICE_IT it (new_choices); it.add_to_end(choice); } // Remove current unichar from werd_choice. On the last iteration // set the correct replacement unichar instead of removing a unichar. for (int replaced_count = 0; replaced_count < wrong_ngram_size; ++replaced_count) { if (replaced_count + 1 == wrong_ngram_size) { werd_choice->set_blob_choice(wrong_ngram_begin_index, num_blobs_to_replace, choice); } else { werd_choice->remove_unichar_id(wrong_ngram_begin_index + 1); } } if (stopper_debug_level >= 1) { werd_choice->print("ReplaceAmbig() "); tprintf("Modified blob_choices: "); print_ratings_list("\n", new_choices, getUnicharset()); } } int Dict::LengthOfShortestAlphaRun(const WERD_CHOICE &WordChoice) { int shortest = MAX_INT32; int curr_len = 0; for (int w = 0; w < WordChoice.length(); ++w) { if (getUnicharset().get_isalpha(WordChoice.unichar_id(w))) { curr_len++; } else if (curr_len > 0) { if (curr_len < shortest) shortest = curr_len; curr_len = 0; } } if (curr_len > 0 && curr_len < shortest) { shortest = curr_len; } else if (shortest == MAX_INT32) { shortest = 0; } return shortest; } int Dict::UniformCertainties(const WERD_CHOICE& word) { float Certainty; float WorstCertainty = MAX_FLOAT32; float CertaintyThreshold; FLOAT64 TotalCertainty; FLOAT64 TotalCertaintySquared; FLOAT64 Variance; FLOAT32 Mean, StdDev; int word_length = word.length(); if (word_length < 3) return true; TotalCertainty = TotalCertaintySquared = 0.0; for (int i = 0; i < word_length; ++i) { Certainty = word.certainty(i); TotalCertainty += Certainty; TotalCertaintySquared += Certainty * Certainty; if (Certainty < WorstCertainty) WorstCertainty = Certainty; } // Subtract off worst certainty from statistics. word_length--; TotalCertainty -= WorstCertainty; TotalCertaintySquared -= WorstCertainty * WorstCertainty; Mean = TotalCertainty / word_length; Variance = ((word_length * TotalCertaintySquared - TotalCertainty * TotalCertainty) / (word_length * (word_length - 1))); if (Variance < 0.0) Variance = 0.0; StdDev = sqrt(Variance); CertaintyThreshold = Mean - stopper_allowable_character_badness * StdDev; if (CertaintyThreshold > stopper_nondict_certainty_base) CertaintyThreshold = stopper_nondict_certainty_base; if (word.certainty() < CertaintyThreshold) { if (stopper_debug_level >= 1) tprintf("Stopper: Non-uniform certainty = %4.1f" " (m=%4.1f, s=%4.1f, t=%4.1f)\n", word.certainty(), Mean, StdDev, CertaintyThreshold); return false; } else { return true; } } } // namespace tesseract
1080228-arabicocr11
dict/stopper.cpp
C++
asf20
20,563
/* -*-C-*- ******************************************************************************** * * File: dawg.h (Formerly dawg.h) * Description: Definition of a class that represents Directed Accyclic Word * Graph (DAWG), functions to build and manipulate the DAWG. * Author: Mark Seaman, SW Productivity * Created: Fri Oct 16 14:37:00 1987 * Modified: Wed Jun 19 16:50:24 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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 DICT_DAWG_H_ #define DICT_DAWG_H_ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "elst.h" #include "ratngs.h" #include "params.h" #include "tesscallback.h" #ifndef __GNUC__ #ifdef _WIN32 #define NO_EDGE (inT64) 0xffffffffffffffffi64 #endif /*_WIN32*/ #else #define NO_EDGE (inT64) 0xffffffffffffffffll #endif /*__GNUC__*/ /*---------------------------------------------------------------------- T y p e s ----------------------------------------------------------------------*/ class UNICHARSET; typedef uinT64 EDGE_RECORD; typedef EDGE_RECORD *EDGE_ARRAY; typedef inT64 EDGE_REF; typedef inT64 NODE_REF; typedef EDGE_REF *NODE_MAP; namespace tesseract { struct NodeChild { UNICHAR_ID unichar_id; EDGE_REF edge_ref; NodeChild(UNICHAR_ID id, EDGE_REF ref): unichar_id(id), edge_ref(ref) {} NodeChild(): unichar_id(INVALID_UNICHAR_ID), edge_ref(NO_EDGE) {} }; typedef GenericVector<NodeChild> NodeChildVector; typedef GenericVector<int> SuccessorList; typedef GenericVector<SuccessorList *> SuccessorListsVector; enum DawgType { DAWG_TYPE_PUNCTUATION, DAWG_TYPE_WORD, DAWG_TYPE_NUMBER, DAWG_TYPE_PATTERN, DAWG_TYPE_COUNT // number of enum entries }; /*---------------------------------------------------------------------- C o n s t a n t s ----------------------------------------------------------------------*/ #define FORWARD_EDGE (inT32) 0 #define BACKWARD_EDGE (inT32) 1 #define MAX_NODE_EDGES_DISPLAY (inT64) 100 #define MARKER_FLAG (inT64) 1 #define DIRECTION_FLAG (inT64) 2 #define WERD_END_FLAG (inT64) 4 #define LETTER_START_BIT 0 #define NUM_FLAG_BITS 3 #define REFFORMAT "%lld" static const bool kDawgSuccessors[DAWG_TYPE_COUNT][DAWG_TYPE_COUNT] = { { 0, 1, 1, 0 }, // for DAWG_TYPE_PUNCTUATION { 1, 0, 0, 0 }, // for DAWG_TYPE_WORD { 1, 0, 0, 0 }, // for DAWG_TYPE_NUMBER { 0, 0, 0, 0 }, // for DAWG_TYPE_PATTERN }; static const char kWildcard[] = "*"; /*---------------------------------------------------------------------- C l a s s e s a n d S t r u c t s ----------------------------------------------------------------------*/ // /// Abstract class (an interface) that declares methods needed by the /// various tesseract classes to operate on SquishedDawg and Trie objects. /// /// This class initializes all the edge masks (since their usage by /// SquishedDawg and Trie is identical) and implements simple accessors /// for each of the fields encoded in an EDGE_RECORD. /// This class also implements word_in_dawg() and check_for_words() /// (since they use only the public methods of SquishedDawg and Trie /// classes that are inherited from the Dawg base class). // class Dawg { public: /// Magic number to determine endianness when reading the Dawg from file. static const inT16 kDawgMagicNumber = 42; /// A special unichar id that indicates that any appropriate pattern /// (e.g.dicitonary word, 0-9 digit, etc) can be inserted instead /// Used for expressing patterns in punctuation and number Dawgs. static const UNICHAR_ID kPatternUnicharID = 0; inline DawgType type() const { return type_; } inline const STRING &lang() const { return lang_; } inline PermuterType permuter() const { return perm_; } virtual ~Dawg() {}; /// Returns true if the given word is in the Dawg. bool word_in_dawg(const WERD_CHOICE &word) const; // Returns true if the given word prefix is not contraindicated by the dawg. // If requires_complete is true, then the exact complete word must be present. bool prefix_in_dawg(const WERD_CHOICE &prefix, bool requires_complete) const; /// Checks the Dawg for the words that are listed in the requested file. /// Returns the number of words in the given file missing from the Dawg. int check_for_words(const char *filename, const UNICHARSET &unicharset, bool enable_wildcard) const; // For each word in the Dawg, call the given (permanent) callback with the // text (UTF-8) version of the word. void iterate_words(const UNICHARSET &unicharset, TessCallback1<const WERD_CHOICE *> *cb) const; // For each word in the Dawg, call the given (permanent) callback with the // text (UTF-8) version of the word. void iterate_words(const UNICHARSET &unicharset, TessCallback1<const char *> *cb) const; // Pure virtual function that should be implemented by the derived classes. /// Returns the edge that corresponds to the letter out of this node. virtual EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const = 0; /// Fills the given NodeChildVector with all the unichar ids (and the /// corresponding EDGE_REFs) for which there is an edge out of this node. virtual void unichar_ids_of(NODE_REF node, NodeChildVector *vec, bool word_end) const = 0; /// Returns the next node visited by following the edge /// indicated by the given EDGE_REF. virtual NODE_REF next_node(EDGE_REF edge_ref) const = 0; /// Returns true if the edge indicated by the given EDGE_REF /// marks the end of a word. virtual bool end_of_word(EDGE_REF edge_ref) const = 0; /// Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF. virtual UNICHAR_ID edge_letter(EDGE_REF edge_ref) const = 0; /// Prints the contents of the node indicated by the given NODE_REF. /// At most max_num_edges will be printed. virtual void print_node(NODE_REF node, int max_num_edges) const = 0; /// Fills vec with unichar ids that represent the character classes /// of the given unichar_id. virtual void unichar_id_to_patterns(UNICHAR_ID unichar_id, const UNICHARSET &unicharset, GenericVector<UNICHAR_ID> *vec) const {}; /// Returns the given EDGE_REF if the EDGE_RECORD that it points to has /// a self loop and the given unichar_id matches the unichar_id stored in the /// EDGE_RECORD, returns NO_EDGE otherwise. virtual EDGE_REF pattern_loop_edge( EDGE_REF edge_ref, UNICHAR_ID unichar_id, bool word_end) const { return false; } protected: Dawg() {} /// Returns the next node visited by following this edge. inline NODE_REF next_node_from_edge_rec(const EDGE_RECORD &edge_rec) const { return ((edge_rec & next_node_mask_) >> next_node_start_bit_); } /// Returns the marker flag of this edge. inline bool marker_flag_from_edge_rec(const EDGE_RECORD &edge_rec) const { return (edge_rec & (MARKER_FLAG << flag_start_bit_)) != 0; } /// Returns the direction flag of this edge. inline int direction_from_edge_rec(const EDGE_RECORD &edge_rec) const { return ((edge_rec & (DIRECTION_FLAG << flag_start_bit_))) ? BACKWARD_EDGE : FORWARD_EDGE; } /// Returns true if this edge marks the end of a word. inline bool end_of_word_from_edge_rec(const EDGE_RECORD &edge_rec) const { return (edge_rec & (WERD_END_FLAG << flag_start_bit_)) != 0; } /// Returns UNICHAR_ID recorded in this edge. inline UNICHAR_ID unichar_id_from_edge_rec( const EDGE_RECORD &edge_rec) const { return ((edge_rec & letter_mask_) >> LETTER_START_BIT); } /// Sets the next node link for this edge in the Dawg. inline void set_next_node_in_edge_rec( EDGE_RECORD *edge_rec, EDGE_REF value) { *edge_rec &= (~next_node_mask_); *edge_rec |= ((value << next_node_start_bit_) & next_node_mask_); } /// Sets this edge record to be the last one in a sequence of edges. inline void set_marker_flag_in_edge_rec(EDGE_RECORD *edge_rec) { *edge_rec |= (MARKER_FLAG << flag_start_bit_); } /// Sequentially compares the given values of unichar ID, next node /// and word end marker with the values in the given EDGE_RECORD. /// Returns: 1 if at any step the given input value exceeds /// that of edge_rec (and all the values already /// checked are the same) /// 0 if edge_rec_match() returns true /// -1 otherwise inline int given_greater_than_edge_rec(NODE_REF next_node, bool word_end, UNICHAR_ID unichar_id, const EDGE_RECORD &edge_rec) const { UNICHAR_ID curr_unichar_id = unichar_id_from_edge_rec(edge_rec); NODE_REF curr_next_node = next_node_from_edge_rec(edge_rec); bool curr_word_end = end_of_word_from_edge_rec(edge_rec); if (edge_rec_match(next_node, word_end, unichar_id, curr_next_node, curr_word_end, curr_unichar_id)) return 0; if (unichar_id > curr_unichar_id) return 1; if (unichar_id == curr_unichar_id) { if (next_node > curr_next_node) return 1; if (next_node == curr_next_node) { if (word_end > curr_word_end) return 1; } } return -1; } /// Returns true if all the values are equal (any value matches /// next_node if next_node == NO_EDGE, any value matches word_end /// if word_end is false). inline bool edge_rec_match(NODE_REF next_node, bool word_end, UNICHAR_ID unichar_id, NODE_REF other_next_node, bool other_word_end, UNICHAR_ID other_unichar_id) const { return ((unichar_id == other_unichar_id) && (next_node == NO_EDGE || next_node == other_next_node) && (!word_end || (word_end == other_word_end))); } /// Sets type_, lang_, perm_, unicharset_size_. /// Initializes the values of various masks from unicharset_size_. void init(DawgType type, const STRING &lang, PermuterType perm, int unicharset_size, int debug_level); /// Matches all of the words that are represented by this string. /// If wilcard is set to something other than INVALID_UNICHAR_ID, /// the *'s in this string are interpreted as wildcards. /// WERD_CHOICE param is not passed by const so that wildcard searches /// can modify it and work without having to copy WERD_CHOICEs. bool match_words(WERD_CHOICE *word, inT32 index, NODE_REF node, UNICHAR_ID wildcard) const; // Recursively iterate over all words in a dawg (see public iterate_words). void iterate_words_rec(const WERD_CHOICE &word_so_far, NODE_REF to_explore, TessCallback1<const WERD_CHOICE *> *cb) const; // Member Variables. DawgType type_; STRING lang_; /// Permuter code that should be used if the word is found in this Dawg. PermuterType perm_; // Variables to construct various edge masks. Formerly: // #define NEXT_EDGE_MASK (inT64) 0xfffffff800000000i64 // #define FLAGS_MASK (inT64) 0x0000000700000000i64 // #define LETTER_MASK (inT64) 0x00000000ffffffffi64 int unicharset_size_; int flag_start_bit_; int next_node_start_bit_; uinT64 next_node_mask_; uinT64 flags_mask_; uinT64 letter_mask_; // Level of debug statements to print to stdout. int debug_level_; }; // // DawgPosition keeps track of where we are in the primary dawg we're searching // as well as where we may be in the "punctuation dawg" which may provide // surrounding context. // // Example: // punctuation dawg -- space is the "pattern character" // " " // no punctuation // "' '" // leading and trailing apostrophes // " '" // trailing apostrophe // word dawg: // "cat" // "cab" // "cat's" // // DawgPosition(dawg_index, dawg_ref, punc_index, punc_ref, rtp) // // DawgPosition(-1, NO_EDGE, p, pe, false) // We're in the punctuation dawg, no other dawg has been started. // (1) If there's a pattern edge as a punc dawg child of us, // for each punc-following dawg starting with ch, produce: // Result: DawgPosition(k, w, p', false) // (2) If there's a valid continuation in the punc dawg, produce: // Result: DawgPosition(-k, NO_EDGE, p', false) // // DawgPosition(k, w, -1, NO_EDGE, false) // We're in dawg k. Going back to punctuation dawg is not an option. // Follow ch in dawg k. // // DawgPosition(k, w, p, pe, false) // We're in dawg k. Continue in dawg k and/or go back to the punc dawg. // If ending, check that the punctuation dawg is also ok to end here. // // DawgPosition(k, w, p, pe true) // We're back in the punctuation dawg. Continuing there is the only option. struct DawgPosition { DawgPosition() : dawg_index(-1), dawg_ref(NO_EDGE), punc_ref(NO_EDGE), back_to_punc(false) {} DawgPosition(int dawg_idx, EDGE_REF dawgref, int punc_idx, EDGE_REF puncref, bool backtopunc) : dawg_index(dawg_idx), dawg_ref(dawgref), punc_index(punc_idx), punc_ref(puncref), back_to_punc(backtopunc) { } bool operator==(const DawgPosition &other) { return dawg_index == other.dawg_index && dawg_ref == other.dawg_ref && punc_index == other.punc_index && punc_ref == other.punc_ref && back_to_punc == other.back_to_punc; } inT8 dawg_index; EDGE_REF dawg_ref; inT8 punc_index; EDGE_REF punc_ref; // Have we returned to the punc dawg at the end of the word? bool back_to_punc; }; class DawgPositionVector : public GenericVector<DawgPosition> { public: /// Overload destructor, since clear() does not delete data_[] any more. ~DawgPositionVector() { if (size_reserved_ > 0) { delete[] data_; size_used_ = 0; size_reserved_ = 0; } } /// Overload clear() in order to avoid allocating/deallocating memory /// when clearing the vector and re-inserting entries into it later. void clear() { size_used_ = 0; } /// Adds an entry for the given dawg_index with the given node to the vec. /// Returns false if the same entry already exists in the vector, /// true otherwise. inline bool add_unique(const DawgPosition &new_pos, bool debug, const char *debug_msg) { for (int i = 0; i < size_used_; ++i) { if (data_[i] == new_pos) return false; } push_back(new_pos); if (debug) { tprintf("%s[%d, " REFFORMAT "] [punc: " REFFORMAT "%s]\n", debug_msg, new_pos.dawg_index, new_pos.dawg_ref, new_pos.punc_ref, new_pos.back_to_punc ? " returned" : ""); } return true; } }; // /// Concrete class that can operate on a compacted (squished) Dawg (read, /// search and write to file). This class is read-only in the sense that /// new words can not be added to an instance of SquishedDawg. /// The underlying representation of the nodes and edges in SquishedDawg /// is stored as a contiguous EDGE_ARRAY (read from file or given as an /// argument to the constructor). // class SquishedDawg : public Dawg { public: SquishedDawg(FILE *file, DawgType type, const STRING &lang, PermuterType perm, int debug_level) { read_squished_dawg(file, type, lang, perm, debug_level); num_forward_edges_in_node0 = num_forward_edges(0); } SquishedDawg(const char* filename, DawgType type, const STRING &lang, PermuterType perm, int debug_level) { FILE *file = fopen(filename, "rb"); if (file == NULL) { tprintf("Failed to open dawg file %s\n", filename); exit(1); } read_squished_dawg(file, type, lang, perm, debug_level); num_forward_edges_in_node0 = num_forward_edges(0); fclose(file); } SquishedDawg(EDGE_ARRAY edges, int num_edges, DawgType type, const STRING &lang, PermuterType perm, int unicharset_size, int debug_level) : edges_(edges), num_edges_(num_edges) { init(type, lang, perm, unicharset_size, debug_level); num_forward_edges_in_node0 = num_forward_edges(0); if (debug_level > 3) print_all("SquishedDawg:"); } ~SquishedDawg(); int NumEdges() { return num_edges_; } /// Returns the edge that corresponds to the letter out of this node. EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const; /// Fills the given NodeChildVector with all the unichar ids (and the /// corresponding EDGE_REFs) for which there is an edge out of this node. void unichar_ids_of(NODE_REF node, NodeChildVector *vec, bool word_end) const { EDGE_REF edge = node; if (!edge_occupied(edge) || edge == NO_EDGE) return; assert(forward_edge(edge)); // we don't expect any backward edges to do { // be present when this funciton is called if (!word_end || end_of_word_from_edge_rec(edges_[edge])) { vec->push_back(NodeChild(unichar_id_from_edge_rec(edges_[edge]), edge)); } } while (!last_edge(edge++)); } /// Returns the next node visited by following the edge /// indicated by the given EDGE_REF. NODE_REF next_node(EDGE_REF edge) const { return next_node_from_edge_rec((edges_[edge])); } /// Returns true if the edge indicated by the given EDGE_REF /// marks the end of a word. bool end_of_word(EDGE_REF edge_ref) const { return end_of_word_from_edge_rec((edges_[edge_ref])); } /// Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF. UNICHAR_ID edge_letter(EDGE_REF edge_ref) const { return unichar_id_from_edge_rec((edges_[edge_ref])); } /// Prints the contents of the node indicated by the given NODE_REF. /// At most max_num_edges will be printed. void print_node(NODE_REF node, int max_num_edges) const; /// Writes the squished/reduced Dawg to a file. void write_squished_dawg(FILE *file); /// Opens the file with the given filename and writes the /// squished/reduced Dawg to the file. void write_squished_dawg(const char *filename) { FILE *file = fopen(filename, "wb"); if (file == NULL) { tprintf("Error opening %s\n", filename); exit(1); } this->write_squished_dawg(file); fclose(file); } private: /// Sets the next node link for this edge. inline void set_next_node(EDGE_REF edge_ref, EDGE_REF value) { set_next_node_in_edge_rec(&(edges_[edge_ref]), value); } /// Sets the edge to be empty. inline void set_empty_edge(EDGE_REF edge_ref) { (edges_[edge_ref] = next_node_mask_); } /// Goes through all the edges and clears each one out. inline void clear_all_edges() { for (int edge = 0; edge < num_edges_; edge++) set_empty_edge(edge); } /// Clears the last flag of this edge. inline void clear_marker_flag(EDGE_REF edge_ref) { (edges_[edge_ref] &= ~(MARKER_FLAG << flag_start_bit_)); } /// Returns true if this edge is in the forward direction. inline bool forward_edge(EDGE_REF edge_ref) const { return (edge_occupied(edge_ref) && (FORWARD_EDGE == direction_from_edge_rec(edges_[edge_ref]))); } /// Returns true if this edge is in the backward direction. inline bool backward_edge(EDGE_REF edge_ref) const { return (edge_occupied(edge_ref) && (BACKWARD_EDGE == direction_from_edge_rec(edges_[edge_ref]))); } /// Returns true if the edge spot in this location is occupied. inline bool edge_occupied(EDGE_REF edge_ref) const { return (edges_[edge_ref] != next_node_mask_); } /// Returns true if this edge is the last edge in a sequence. inline bool last_edge(EDGE_REF edge_ref) const { return (edges_[edge_ref] & (MARKER_FLAG << flag_start_bit_)) != 0; } /// Counts and returns the number of forward edges in this node. inT32 num_forward_edges(NODE_REF node) const; /// Reads SquishedDawg from a file. void read_squished_dawg(FILE *file, DawgType type, const STRING &lang, PermuterType perm, int debug_level); /// Prints the contents of an edge indicated by the given EDGE_REF. void print_edge(EDGE_REF edge) const; /// Prints the contents of the SquishedDawg. void print_all(const char* msg) { tprintf("\n__________________________\n%s\n", msg); for (int i = 0; i < num_edges_; ++i) print_edge(i); tprintf("__________________________\n"); } /// Constructs a mapping from the memory node indices to disk node indices. NODE_MAP build_node_map(inT32 *num_nodes) const; // Member variables. EDGE_ARRAY edges_; int num_edges_; int num_forward_edges_in_node0; }; } // namespace tesseract #endif // DICT_DAWG_H_
1080228-arabicocr11
dict/dawg.h
C
asf20
21,935
/////////////////////////////////////////////////////////////////////// // File: dawg_cache.h // Description: A class that knows about loading and caching dawgs. // Author: David Eger // Created: Fri Jan 27 12:08:00 PST 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "dawg_cache.h" #include "dawg.h" #include "object_cache.h" #include "strngs.h" #include "tessdatamanager.h" namespace tesseract { struct DawgLoader { DawgLoader(const STRING &lang, const char *data_file_name, TessdataType tessdata_dawg_type, int dawg_debug_level) : lang_(lang), data_file_name_(data_file_name), tessdata_dawg_type_(tessdata_dawg_type), dawg_debug_level_(dawg_debug_level) {} Dawg *Load(); STRING lang_; const char *data_file_name_; TessdataType tessdata_dawg_type_; int dawg_debug_level_; }; Dawg *DawgCache::GetSquishedDawg( const STRING &lang, const char *data_file_name, TessdataType tessdata_dawg_type, int debug_level) { STRING data_id = data_file_name; data_id += kTessdataFileSuffixes[tessdata_dawg_type]; DawgLoader loader(lang, data_file_name, tessdata_dawg_type, debug_level); return dawgs_.Get(data_id, NewTessCallback(&loader, &DawgLoader::Load)); } Dawg *DawgLoader::Load() { TessdataManager data_loader; if (!data_loader.Init(data_file_name_, dawg_debug_level_)) { return NULL; } if (!data_loader.SeekToStart(tessdata_dawg_type_)) return NULL; FILE *fp = data_loader.GetDataFilePtr(); DawgType dawg_type; PermuterType perm_type; switch (tessdata_dawg_type_) { case TESSDATA_PUNC_DAWG: dawg_type = DAWG_TYPE_PUNCTUATION; perm_type = PUNC_PERM; break; case TESSDATA_SYSTEM_DAWG: dawg_type = DAWG_TYPE_WORD; perm_type = SYSTEM_DAWG_PERM; break; case TESSDATA_NUMBER_DAWG: dawg_type = DAWG_TYPE_NUMBER; perm_type = NUMBER_PERM; break; case TESSDATA_BIGRAM_DAWG: dawg_type = DAWG_TYPE_WORD; // doesn't actually matter perm_type = COMPOUND_PERM; // doesn't actually matter break; case TESSDATA_UNAMBIG_DAWG: dawg_type = DAWG_TYPE_WORD; perm_type = SYSTEM_DAWG_PERM; break; case TESSDATA_FREQ_DAWG: dawg_type = DAWG_TYPE_WORD; perm_type = FREQ_DAWG_PERM; break; default: data_loader.End(); return NULL; } SquishedDawg *retval = new SquishedDawg(fp, dawg_type, lang_, perm_type, dawg_debug_level_); data_loader.End(); return retval; } } // namespace tesseract
1080228-arabicocr11
dict/dawg_cache.cpp
C++
asf20
3,191
/* -*-C-*- ******************************************************************************** * * File: permdawg.c (Formerly permdawg.c) * Description: Scale word choices by a dictionary * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Tue Jul 9 15:43:18 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "cutil.h" #include "dawg.h" #include "freelist.h" #include "globals.h" #include "ndminx.h" #include "stopper.h" #include "tprintf.h" #include "params.h" #include <ctype.h> #include "dict.h" /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ namespace tesseract { /** * @name go_deeper_dawg_fxn * * If the choice being composed so far could be a dictionary word * keep exploring choices. */ void Dict::go_deeper_dawg_fxn( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, bool word_ending, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *void_more_args) { DawgArgs *more_args = reinterpret_cast<DawgArgs*>(void_more_args); word_ending = (char_choice_index == char_choices.size()-1); int word_index = word->length() - 1; if (best_choice->rating() < *limit) return; // Look up char in DAWG // If the current unichar is an ngram first try calling // letter_is_okay() for each unigram it contains separately. UNICHAR_ID orig_uch_id = word->unichar_id(word_index); bool checked_unigrams = false; if (getUnicharset().get_isngram(orig_uch_id)) { if (dawg_debug_level) { tprintf("checking unigrams in an ngram %s\n", getUnicharset().debug_str(orig_uch_id).string()); } int num_unigrams = 0; word->remove_last_unichar_id(); GenericVector<UNICHAR_ID> encoding; const char *ngram_str = getUnicharset().id_to_unichar(orig_uch_id); // Since the string came out of the unicharset, failure is impossible. ASSERT_HOST(getUnicharset().encode_string(ngram_str, true, &encoding, NULL, NULL)); bool unigrams_ok = true; // Construct DawgArgs that reflect the current state. DawgPositionVector unigram_active_dawgs = *(more_args->active_dawgs); DawgPositionVector unigram_updated_dawgs; DawgArgs unigram_dawg_args(&unigram_active_dawgs, &unigram_updated_dawgs, more_args->permuter); // Check unigrams in the ngram with letter_is_okay(). for (int i = 0; unigrams_ok && i < encoding.size(); ++i) { UNICHAR_ID uch_id = encoding[i]; ASSERT_HOST(uch_id != INVALID_UNICHAR_ID); ++num_unigrams; word->append_unichar_id(uch_id, 1, 0.0, 0.0); unigrams_ok = (this->*letter_is_okay_)( &unigram_dawg_args, word->unichar_id(word_index+num_unigrams-1), word_ending && i == encoding.size() - 1); (*unigram_dawg_args.active_dawgs) = *(unigram_dawg_args.updated_dawgs); if (dawg_debug_level) { tprintf("unigram %s is %s\n", getUnicharset().debug_str(uch_id).string(), unigrams_ok ? "OK" : "not OK"); } } // Restore the word and copy the updated dawg state if needed. while (num_unigrams-- > 0) word->remove_last_unichar_id(); word->append_unichar_id_space_allocated(orig_uch_id, 1, 0.0, 0.0); if (unigrams_ok) { checked_unigrams = true; more_args->permuter = unigram_dawg_args.permuter; *(more_args->updated_dawgs) = *(unigram_dawg_args.updated_dawgs); } } // Check which dawgs from the dawgs_ vector contain the word // up to and including the current unichar. if (checked_unigrams || (this->*letter_is_okay_)( more_args, word->unichar_id(word_index), word_ending)) { // Add a new word choice if (word_ending) { if (dawg_debug_level) { tprintf("found word = %s\n", word->debug_string().string()); } if (strcmp(output_ambig_words_file.string(), "") != 0) { if (output_ambig_words_file_ == NULL) { output_ambig_words_file_ = fopen(output_ambig_words_file.string(), "wb+"); if (output_ambig_words_file_ == NULL) { tprintf("Failed to open output_ambig_words_file %s\n", output_ambig_words_file.string()); exit(1); } STRING word_str; word->string_and_lengths(&word_str, NULL); word_str += " "; fprintf(output_ambig_words_file_, "%s", word_str.string()); } STRING word_str; word->string_and_lengths(&word_str, NULL); word_str += " "; fprintf(output_ambig_words_file_, "%s", word_str.string()); } WERD_CHOICE *adjusted_word = word; adjusted_word->set_permuter(more_args->permuter); update_best_choice(*adjusted_word, best_choice); } else { // search the next letter // Make updated_* point to the next entries in the DawgPositionVector // arrays (that were originally created in dawg_permute_and_select) ++(more_args->updated_dawgs); // Make active_dawgs and constraints point to the updated ones. ++(more_args->active_dawgs); permute_choices(debug, char_choices, char_choice_index + 1, prev_char_frag_info, word, certainties, limit, best_choice, attempts_left, more_args); // Restore previous state to explore another letter in this position. --(more_args->updated_dawgs); --(more_args->active_dawgs); } } else { if (dawg_debug_level) { tprintf("last unichar not OK at index %d in %s\n", word_index, word->debug_string().string()); } } } /** * dawg_permute_and_select * * Recursively explore all the possible character combinations in * the given char_choices. Use go_deeper_dawg_fxn() to search all the * dawgs in the dawgs_ vector in parallel and discard invalid words. * * Allocate and return a WERD_CHOICE with the best valid word found. */ WERD_CHOICE *Dict::dawg_permute_and_select( const BLOB_CHOICE_LIST_VECTOR &char_choices, float rating_limit) { WERD_CHOICE *best_choice = new WERD_CHOICE(&getUnicharset()); best_choice->make_bad(); best_choice->set_rating(rating_limit); if (char_choices.length() == 0 || char_choices.length() > MAX_WERD_LENGTH) return best_choice; DawgPositionVector *active_dawgs = new DawgPositionVector[char_choices.length() + 1]; init_active_dawgs(&(active_dawgs[0]), true); DawgArgs dawg_args(&(active_dawgs[0]), &(active_dawgs[1]), NO_PERM); WERD_CHOICE word(&getUnicharset(), MAX_WERD_LENGTH); float certainties[MAX_WERD_LENGTH]; this->go_deeper_fxn_ = &tesseract::Dict::go_deeper_dawg_fxn; int attempts_left = max_permuter_attempts; permute_choices((dawg_debug_level) ? "permute_dawg_debug" : NULL, char_choices, 0, NULL, &word, certainties, &rating_limit, best_choice, &attempts_left, &dawg_args); delete[] active_dawgs; return best_choice; } /** * permute_choices * * Call append_choices() for each BLOB_CHOICE in BLOB_CHOICE_LIST * with the given char_choice_index in char_choices. */ void Dict::permute_choices( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *more_args) { if (debug) { tprintf("%s permute_choices: char_choice_index=%d" " limit=%g rating=%g, certainty=%g word=%s\n", debug, char_choice_index, *limit, word->rating(), word->certainty(), word->debug_string().string()); } if (char_choice_index < char_choices.length()) { BLOB_CHOICE_IT blob_choice_it; blob_choice_it.set_to_list(char_choices.get(char_choice_index)); for (blob_choice_it.mark_cycle_pt(); !blob_choice_it.cycled_list(); blob_choice_it.forward()) { (*attempts_left)--; append_choices(debug, char_choices, *(blob_choice_it.data()), char_choice_index, prev_char_frag_info, word, certainties, limit, best_choice, attempts_left, more_args); if (*attempts_left <= 0) { if (debug) tprintf("permute_choices(): attempts_left is 0\n"); break; } } } } /** * append_choices * * Checks to see whether or not the next choice is worth appending to * the word being generated. If so then keeps going deeper into the word. * * This function assumes that Dict::go_deeper_fxn_ is set. */ void Dict::append_choices( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, const BLOB_CHOICE &blob_choice, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *more_args) { int word_ending = (char_choice_index == char_choices.length() - 1) ? true : false; // Deal with fragments. CHAR_FRAGMENT_INFO char_frag_info; if (!fragment_state_okay(blob_choice.unichar_id(), blob_choice.rating(), blob_choice.certainty(), prev_char_frag_info, debug, word_ending, &char_frag_info)) { return; // blob_choice must be an invalid fragment } // Search the next letter if this character is a fragment. if (char_frag_info.unichar_id == INVALID_UNICHAR_ID) { permute_choices(debug, char_choices, char_choice_index + 1, &char_frag_info, word, certainties, limit, best_choice, attempts_left, more_args); return; } // Add the next unichar. float old_rating = word->rating(); float old_certainty = word->certainty(); uinT8 old_permuter = word->permuter(); certainties[word->length()] = char_frag_info.certainty; word->append_unichar_id_space_allocated( char_frag_info.unichar_id, char_frag_info.num_fragments, char_frag_info.rating, char_frag_info.certainty); // Explore the next unichar. (this->*go_deeper_fxn_)(debug, char_choices, char_choice_index, &char_frag_info, word_ending, word, certainties, limit, best_choice, attempts_left, more_args); // Remove the unichar we added to explore other choices in it's place. word->remove_last_unichar_id(); word->set_rating(old_rating); word->set_certainty(old_certainty); word->set_permuter(old_permuter); } /** * @name fragment_state * * Given the current char choice and information about previously seen * fragments, determines whether adjacent character fragments are * present and whether they can be concatenated. * * The given prev_char_frag_info contains: * - fragment: if not NULL contains information about immediately * preceeding fragmented character choice * - num_fragments: number of fragments that have been used so far * to construct a character * - certainty: certainty of the current choice or minimum * certainty of all fragments concatenated so far * - rating: rating of the current choice or sum of fragment * ratings concatenated so far * * The output char_frag_info is filled in as follows: * - character: is set to be NULL if the choice is a non-matching * or non-ending fragment piece; is set to unichar of the given choice * if it represents a regular character or a matching ending fragment * - fragment,num_fragments,certainty,rating are set as described above * * @returns false if a non-matching fragment is discovered, true otherwise. */ bool Dict::fragment_state_okay(UNICHAR_ID curr_unichar_id, float curr_rating, float curr_certainty, const CHAR_FRAGMENT_INFO *prev_char_frag_info, const char *debug, int word_ending, CHAR_FRAGMENT_INFO *char_frag_info) { const CHAR_FRAGMENT *this_fragment = getUnicharset().get_fragment(curr_unichar_id); const CHAR_FRAGMENT *prev_fragment = prev_char_frag_info != NULL ? prev_char_frag_info->fragment : NULL; // Print debug info for fragments. if (debug && (prev_fragment || this_fragment)) { tprintf("%s check fragments: choice=%s word_ending=%d\n", debug, getUnicharset().debug_str(curr_unichar_id).string(), word_ending); if (prev_fragment) { tprintf("prev_fragment %s\n", prev_fragment->to_string().string()); } if (this_fragment) { tprintf("this_fragment %s\n", this_fragment->to_string().string()); } } char_frag_info->unichar_id = curr_unichar_id; char_frag_info->fragment = this_fragment; char_frag_info->rating = curr_rating; char_frag_info->certainty = curr_certainty; char_frag_info->num_fragments = 1; if (prev_fragment && !this_fragment) { if (debug) tprintf("Skip choice with incomplete fragment\n"); return false; } if (this_fragment) { // We are dealing with a fragment. char_frag_info->unichar_id = INVALID_UNICHAR_ID; if (prev_fragment) { if (!this_fragment->is_continuation_of(prev_fragment)) { if (debug) tprintf("Non-matching fragment piece\n"); return false; } if (this_fragment->is_ending()) { char_frag_info->unichar_id = getUnicharset().unichar_to_id(this_fragment->get_unichar()); char_frag_info->fragment = NULL; if (debug) { tprintf("Built character %s from fragments\n", getUnicharset().debug_str( char_frag_info->unichar_id).string()); } } else { if (debug) tprintf("Record fragment continuation\n"); char_frag_info->fragment = this_fragment; } // Update certainty and rating. char_frag_info->rating = prev_char_frag_info->rating + curr_rating; char_frag_info->num_fragments = prev_char_frag_info->num_fragments + 1; char_frag_info->certainty = MIN(curr_certainty, prev_char_frag_info->certainty); } else { if (this_fragment->is_beginning()) { if (debug) tprintf("Record fragment beginning\n"); } else { if (debug) { tprintf("Non-starting fragment piece with no prev_fragment\n"); } return false; } } } if (word_ending && char_frag_info->fragment) { if (debug) tprintf("Word can not end with a fragment\n"); return false; } return true; } } // namespace tesseract
1080228-arabicocr11
dict/permdawg.cpp
C
asf20
15,730
/* -*-C-*- ******************************************************************************** * File: hyphen.c (Formerly hyphen.c) * Description: Functions for maintaining information about hyphenated words. * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Thu Mar 14 11:09:43 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ #include "dict.h" namespace tesseract { // Unless the previous word was the last one on the line, and the current // one is not (thus it is the first one on the line), erase hyphen_word_, // clear hyphen_active_dawgs_, hyphen_constraints_ update last_word_on_line_. void Dict::reset_hyphen_vars(bool last_word_on_line) { if (!(last_word_on_line_ == true && last_word_on_line == false)) { if (hyphen_word_ != NULL) { delete hyphen_word_; hyphen_word_ = NULL; hyphen_active_dawgs_.clear(); } } if (hyphen_debug_level) { tprintf("reset_hyphen_vars: last_word_on_line %d -> %d\n", last_word_on_line_, last_word_on_line); } last_word_on_line_ = last_word_on_line; } // Update hyphen_word_, and copy the given DawgPositionVectors into // hyphen_active_dawgs_. void Dict::set_hyphen_word(const WERD_CHOICE &word, const DawgPositionVector &active_dawgs) { if (hyphen_word_ == NULL) { hyphen_word_ = new WERD_CHOICE(word.unicharset()); hyphen_word_->make_bad(); } if (hyphen_word_->rating() > word.rating()) { *hyphen_word_ = word; // Remove the last unichar id as it is a hyphen, and remove // any unichar_string/lengths that are present. hyphen_word_->remove_last_unichar_id(); hyphen_active_dawgs_ = active_dawgs; } if (hyphen_debug_level) { hyphen_word_->print("set_hyphen_word: "); } } } // namespace tesseract
1080228-arabicocr11
dict/hyphen.cpp
C
asf20
2,585
/////////////////////////////////////////////////////////////////////// // File: dict.cpp // Description: dict class. // 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. // /////////////////////////////////////////////////////////////////////// #include <stdio.h> #include "dict.h" #include "unicodes.h" #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif #include "tprintf.h" namespace tesseract { class Image; Dict::Dict(CCUtil* ccutil) : letter_is_okay_(&tesseract::Dict::def_letter_is_okay), probability_in_context_(&tesseract::Dict::def_probability_in_context), params_model_classify_(NULL), ccutil_(ccutil), STRING_MEMBER(user_words_file, "", "A filename of user-provided words.", getCCUtil()->params()), STRING_INIT_MEMBER(user_words_suffix, "", "A suffix of user-provided words located in tessdata.", getCCUtil()->params()), STRING_MEMBER(user_patterns_file, "", "A filename of user-provided patterns.", getCCUtil()->params()), STRING_INIT_MEMBER(user_patterns_suffix, "", "A suffix of user-provided patterns located in " "tessdata.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_system_dawg, true, "Load system word dawg.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_freq_dawg, true, "Load frequent word dawg.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_unambig_dawg, true, "Load unambiguous word dawg.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_punc_dawg, true, "Load dawg with punctuation" " patterns.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_number_dawg, true, "Load dawg with number" " patterns.", getCCUtil()->params()), BOOL_INIT_MEMBER(load_bigram_dawg, true, "Load dawg with special word " "bigrams.", getCCUtil()->params()), double_MEMBER(xheight_penalty_subscripts, 0.125, "Score penalty (0.1 = 10%) added if there are subscripts " "or superscripts in a word, but it is otherwise OK.", getCCUtil()->params()), double_MEMBER(xheight_penalty_inconsistent, 0.25, "Score penalty (0.1 = 10%) added if an xheight is " "inconsistent.", getCCUtil()->params()), double_MEMBER(segment_penalty_dict_frequent_word, 1.0, "Score multiplier for word matches which have good case and" "are frequent in the given language (lower is better).", getCCUtil()->params()), double_MEMBER(segment_penalty_dict_case_ok, 1.1, "Score multiplier for word matches that have good case " "(lower is better).", getCCUtil()->params()), double_MEMBER(segment_penalty_dict_case_bad, 1.3125, "Default score multiplier for word matches, which may have " "case issues (lower is better).", getCCUtil()->params()), double_MEMBER(segment_penalty_ngram_best_choice, 1.24, "Multipler to for the best choice from the ngram model.", getCCUtil()->params()), double_MEMBER(segment_penalty_dict_nonword, 1.25, "Score multiplier for glyph fragment segmentations which " "do not match a dictionary word (lower is better).", getCCUtil()->params()), double_MEMBER(segment_penalty_garbage, 1.50, "Score multiplier for poorly cased strings that are not in" " the dictionary and generally look like garbage (lower is" " better).", getCCUtil()->params()), STRING_MEMBER(output_ambig_words_file, "", "Output file for ambiguities found in the dictionary", getCCUtil()->params()), INT_MEMBER(dawg_debug_level, 0, "Set to 1 for general debug info" ", to 2 for more details, to 3 to see all the debug messages", getCCUtil()->params()), INT_MEMBER(hyphen_debug_level, 0, "Debug level for hyphenated words.", getCCUtil()->params()), INT_MEMBER(max_viterbi_list_size, 10, "Maximum size of viterbi list.", getCCUtil()->params()), BOOL_MEMBER(use_only_first_uft8_step, false, "Use only the first UTF8 step of the given string" " when computing log probabilities.", getCCUtil()->params()), double_MEMBER(certainty_scale, 20.0, "Certainty scaling factor", getCCUtil()->params()), double_MEMBER(stopper_nondict_certainty_base, -2.50, "Certainty threshold for non-dict words", getCCUtil()->params()), double_MEMBER(stopper_phase2_certainty_rejection_offset, 1.0, "Reject certainty offset", getCCUtil()->params()), INT_MEMBER(stopper_smallword_size, 2, "Size of dict word to be treated as non-dict word", getCCUtil()->params()), double_MEMBER(stopper_certainty_per_char, -0.50, "Certainty to add" " for each dict char above small word size.", getCCUtil()->params()), double_MEMBER(stopper_allowable_character_badness, 3.0, "Max certaintly variation allowed in a word (in sigma)", getCCUtil()->params()), INT_MEMBER(stopper_debug_level, 0, "Stopper debug level", getCCUtil()->params()), BOOL_MEMBER(stopper_no_acceptable_choices, false, "Make AcceptableChoice() always return false. Useful" " when there is a need to explore all segmentations", getCCUtil()->params()), BOOL_MEMBER(save_raw_choices, false, "Deprecated- backward compatablity only", getCCUtil()->params()), INT_MEMBER(tessedit_truncate_wordchoice_log, 10, "Max words to keep in list", getCCUtil()->params()), STRING_MEMBER(word_to_debug, "", "Word for which stopper debug" " information should be printed to stdout", getCCUtil()->params()), STRING_MEMBER(word_to_debug_lengths, "", "Lengths of unichars in word_to_debug", getCCUtil()->params()), INT_MEMBER(fragments_debug, 0, "Debug character fragments", getCCUtil()->params()), BOOL_MEMBER(segment_nonalphabetic_script, false, "Don't use any alphabetic-specific tricks." "Set to true in the traineddata config file for" " scripts that are cursive or inherently fixed-pitch", getCCUtil()->params()), BOOL_MEMBER(save_doc_words, 0, "Save Document Words", getCCUtil()->params()), double_MEMBER(doc_dict_pending_threshold, 0.0, "Worst certainty for using pending dictionary", getCCUtil()->params()), double_MEMBER(doc_dict_certainty_threshold, -2.25, "Worst certainty for words that can be inserted into the" "document dictionary", getCCUtil()->params()), INT_MEMBER(max_permuter_attempts, 10000, "Maximum number of different" " character choices to consider during permutation." " This limit is especially useful when user patterns" " are specified, since overly generic patterns can result in" " dawg search exploring an overly large number of options.", getCCUtil()->params()) { dang_ambigs_table_ = NULL; replace_ambigs_table_ = NULL; reject_offset_ = 0.0; go_deeper_fxn_ = NULL; hyphen_word_ = NULL; last_word_on_line_ = false; hyphen_unichar_id_ = INVALID_UNICHAR_ID; document_words_ = NULL; dawg_cache_ = NULL; dawg_cache_is_ours_ = false; pending_words_ = NULL; bigram_dawg_ = NULL; freq_dawg_ = NULL; punc_dawg_ = NULL; unambig_dawg_ = NULL; wordseg_rating_adjust_factor_ = -1.0f; output_ambig_words_file_ = NULL; } Dict::~Dict() { if (hyphen_word_ != NULL) delete hyphen_word_; if (output_ambig_words_file_ != NULL) fclose(output_ambig_words_file_); } DawgCache *Dict::GlobalDawgCache() { // We dynamically allocate this global cache (a singleton) so it will outlive // every Tesseract instance (even those that someone else might declare as // global statics). static DawgCache *cache = new DawgCache(); // evil global singleton return cache; } void Dict::Load(DawgCache *dawg_cache) { STRING name; STRING &lang = getCCUtil()->lang; if (dawgs_.length() != 0) this->End(); apostrophe_unichar_id_ = getUnicharset().unichar_to_id(kApostropheSymbol); question_unichar_id_ = getUnicharset().unichar_to_id(kQuestionSymbol); slash_unichar_id_ = getUnicharset().unichar_to_id(kSlashSymbol); hyphen_unichar_id_ = getUnicharset().unichar_to_id(kHyphenSymbol); if (dawg_cache != NULL) { dawg_cache_ = dawg_cache; dawg_cache_is_ours_ = false; } else { dawg_cache_ = new DawgCache(); dawg_cache_is_ours_ = true; } TessdataManager &tessdata_manager = getCCUtil()->tessdata_manager; const char *data_file_name = tessdata_manager.GetDataFileName().string(); // Load dawgs_. if (load_punc_dawg) { punc_dawg_ = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_PUNC_DAWG, dawg_debug_level); if (punc_dawg_) dawgs_ += punc_dawg_; } if (load_system_dawg) { Dawg *system_dawg = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_SYSTEM_DAWG, dawg_debug_level); if (system_dawg) dawgs_ += system_dawg; } if (load_number_dawg) { Dawg *number_dawg = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_NUMBER_DAWG, dawg_debug_level); if (number_dawg) dawgs_ += number_dawg; } if (load_bigram_dawg) { bigram_dawg_ = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_BIGRAM_DAWG, dawg_debug_level); } if (load_freq_dawg) { freq_dawg_ = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_FREQ_DAWG, dawg_debug_level); if (freq_dawg_) { dawgs_ += freq_dawg_; } } if (load_unambig_dawg) { unambig_dawg_ = dawg_cache_->GetSquishedDawg( lang, data_file_name, TESSDATA_UNAMBIG_DAWG, dawg_debug_level); if (unambig_dawg_) dawgs_ += unambig_dawg_; } if (((STRING &)user_words_suffix).length() > 0 || ((STRING &)user_words_file).length() > 0) { Trie *trie_ptr = new Trie(DAWG_TYPE_WORD, lang, USER_DAWG_PERM, getUnicharset().size(), dawg_debug_level); if (((STRING &)user_words_file).length() > 0) { name = user_words_file; } else { name = getCCUtil()->language_data_path_prefix; name += user_words_suffix; } if (!trie_ptr->read_and_add_word_list(name.string(), getUnicharset(), Trie::RRP_REVERSE_IF_HAS_RTL)) { tprintf("Error: failed to load %s\n", name.string()); delete trie_ptr; } else { dawgs_ += trie_ptr; } } if (((STRING &)user_patterns_suffix).length() > 0 || ((STRING &)user_patterns_file).length() > 0) { Trie *trie_ptr = new Trie(DAWG_TYPE_PATTERN, lang, USER_PATTERN_PERM, getUnicharset().size(), dawg_debug_level); trie_ptr->initialize_patterns(&(getUnicharset())); if (((STRING &)user_patterns_file).length() > 0) { name = user_patterns_file; } else { name = getCCUtil()->language_data_path_prefix; name += user_patterns_suffix; } if (!trie_ptr->read_pattern_list(name.string(), getUnicharset())) { tprintf("Error: failed to load %s\n", name.string()); delete trie_ptr; } else { dawgs_ += trie_ptr; } } document_words_ = new Trie(DAWG_TYPE_WORD, lang, DOC_DAWG_PERM, getUnicharset().size(), dawg_debug_level); dawgs_ += document_words_; // This dawg is temporary and should not be searched by letter_is_ok. pending_words_ = new Trie(DAWG_TYPE_WORD, lang, NO_PERM, getUnicharset().size(), dawg_debug_level); // Construct a list of corresponding successors for each dawg. Each entry i // in the successors_ vector is a vector of integers that represent the // indices into the dawgs_ vector of the successors for dawg i. successors_.reserve(dawgs_.length()); for (int i = 0; i < dawgs_.length(); ++i) { const Dawg *dawg = dawgs_[i]; SuccessorList *lst = new SuccessorList(); for (int j = 0; j < dawgs_.length(); ++j) { const Dawg *other = dawgs_[j]; if (dawg != NULL && other != NULL && (dawg->lang() == other->lang()) && kDawgSuccessors[dawg->type()][other->type()]) *lst += j; } successors_ += lst; } } void Dict::End() { if (dawgs_.length() == 0) return; // Not safe to call twice. for (int i = 0; i < dawgs_.size(); i++) { if (!dawg_cache_->FreeDawg(dawgs_[i])) { delete dawgs_[i]; } } dawg_cache_->FreeDawg(bigram_dawg_); if (dawg_cache_is_ours_) { delete dawg_cache_; dawg_cache_ = NULL; } successors_.delete_data_pointers(); dawgs_.clear(); successors_.clear(); document_words_ = NULL; if (pending_words_ != NULL) { delete pending_words_; pending_words_ = NULL; } } // Returns true if in light of the current state unichar_id is allowed // according to at least one of the dawgs in the dawgs_ vector. // See more extensive comments in dict.h where this function is declared. int Dict::def_letter_is_okay(void* void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const { DawgArgs *dawg_args = reinterpret_cast<DawgArgs*>(void_dawg_args); if (dawg_debug_level >= 3) { tprintf("def_letter_is_okay: current unichar=%s word_end=%d" " num active dawgs=%d\n", getUnicharset().debug_str(unichar_id).string(), word_end, dawg_args->active_dawgs->length()); } // Do not accept words that contain kPatternUnicharID. // (otherwise pattern dawgs would not function correctly). // Do not accept words containing INVALID_UNICHAR_IDs. if (unichar_id == Dawg::kPatternUnicharID || unichar_id == INVALID_UNICHAR_ID) { dawg_args->permuter = NO_PERM; return NO_PERM; } // Initialization. PermuterType curr_perm = NO_PERM; dawg_args->updated_dawgs->clear(); // Go over the active_dawgs vector and insert DawgPosition records // with the updated ref (an edge with the corresponding unichar id) into // dawg_args->updated_pos. for (int a = 0; a < dawg_args->active_dawgs->length(); ++a) { const DawgPosition &pos = (*dawg_args->active_dawgs)[a]; const Dawg *punc_dawg = pos.punc_index >= 0 ? dawgs_[pos.punc_index] : NULL; const Dawg *dawg = pos.dawg_index >= 0 ? dawgs_[pos.dawg_index] : NULL; if (!dawg && !punc_dawg) { // shouldn't happen. tprintf("Received DawgPosition with no dawg or punc_dawg. wth?\n"); continue; } if (!dawg) { // We're in the punctuation dawg. A core dawg has not been chosen. NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref); EDGE_REF punc_transition_edge = punc_dawg->edge_char_of( punc_node, Dawg::kPatternUnicharID, word_end); if (punc_transition_edge != NO_EDGE) { // Find all successors, and see which can transition. const SuccessorList &slist = *(successors_[pos.punc_index]); for (int s = 0; s < slist.length(); ++s) { int sdawg_index = slist[s]; const Dawg *sdawg = dawgs_[sdawg_index]; UNICHAR_ID ch = char_for_dawg(unichar_id, sdawg); EDGE_REF dawg_edge = sdawg->edge_char_of(0, ch, word_end); if (dawg_edge != NO_EDGE) { if (dawg_debug_level >=3) { tprintf("Letter found in dawg %d\n", sdawg_index); } dawg_args->updated_dawgs->add_unique( DawgPosition(sdawg_index, dawg_edge, pos.punc_index, punc_transition_edge, false), dawg_debug_level > 0, "Append transition from punc dawg to current dawgs: "); if (sdawg->permuter() > curr_perm) curr_perm = sdawg->permuter(); } } } EDGE_REF punc_edge = punc_dawg->edge_char_of(punc_node, unichar_id, word_end); if (punc_edge != NO_EDGE) { if (dawg_debug_level >=3) { tprintf("Letter found in punctuation dawg\n"); } dawg_args->updated_dawgs->add_unique( DawgPosition(-1, NO_EDGE, pos.punc_index, punc_edge, false), dawg_debug_level > 0, "Extend punctuation dawg: "); if (PUNC_PERM > curr_perm) curr_perm = PUNC_PERM; } continue; } if (punc_dawg && dawg->end_of_word(pos.dawg_ref)) { // We can end the main word here. // If we can continue on the punc ref, add that possibility. NODE_REF punc_node = GetStartingNode(punc_dawg, pos.punc_ref); EDGE_REF punc_edge = punc_node == NO_EDGE ? NO_EDGE : punc_dawg->edge_char_of(punc_node, unichar_id, word_end); if (punc_edge != NO_EDGE) { dawg_args->updated_dawgs->add_unique( DawgPosition(pos.dawg_index, pos.dawg_ref, pos.punc_index, punc_edge, true), dawg_debug_level > 0, "Return to punctuation dawg: "); if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter(); } } if (pos.back_to_punc) continue; // If we are dealing with the pattern dawg, look up all the // possible edges, not only for the exact unichar_id, but also // for all its character classes (alpha, digit, etc). if (dawg->type() == DAWG_TYPE_PATTERN) { ProcessPatternEdges(dawg, pos, unichar_id, word_end, dawg_args->updated_dawgs, &curr_perm); // There can't be any successors to dawg that is of type // DAWG_TYPE_PATTERN, so we are done examining this DawgPosition. continue; } // Find the edge out of the node for the unichar_id. NODE_REF node = GetStartingNode(dawg, pos.dawg_ref); EDGE_REF edge = (node == NO_EDGE) ? NO_EDGE : dawg->edge_char_of(node, char_for_dawg(unichar_id, dawg), word_end); if (dawg_debug_level >= 3) { tprintf("Active dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n", pos.dawg_index, node, edge); } if (edge != NO_EDGE) { // the unichar was found in the current dawg if (dawg_debug_level >=3) { tprintf("Letter found in dawg %d\n", pos.dawg_index); } if (word_end && punc_dawg && !punc_dawg->end_of_word(pos.punc_ref)) { if (dawg_debug_level >= 3) { tprintf("Punctuation constraint not satisfied at end of word.\n"); } continue; } if (dawg->permuter() > curr_perm) curr_perm = dawg->permuter(); dawg_args->updated_dawgs->add_unique( DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref, false), dawg_debug_level > 0, "Append current dawg to updated active dawgs: "); } } // end for // Update dawg_args->permuter if it used to be NO_PERM or became NO_PERM // or if we found the current letter in a non-punctuation dawg. This // allows preserving information on which dawg the "core" word came from. // Keep the old value of dawg_args->permuter if it is COMPOUND_PERM. if (dawg_args->permuter == NO_PERM || curr_perm == NO_PERM || (curr_perm != PUNC_PERM && dawg_args->permuter != COMPOUND_PERM)) { dawg_args->permuter = curr_perm; } if (dawg_debug_level >= 2) { tprintf("Returning %d for permuter code for this character.\n"); } return dawg_args->permuter; } void Dict::ProcessPatternEdges(const Dawg *dawg, const DawgPosition &pos, UNICHAR_ID unichar_id, bool word_end, DawgPositionVector *updated_dawgs, PermuterType *curr_perm) const { NODE_REF node = GetStartingNode(dawg, pos.dawg_ref); // Try to find the edge corresponding to the exact unichar_id and to all the // edges corresponding to the character class of unichar_id. GenericVector<UNICHAR_ID> unichar_id_patterns; unichar_id_patterns.push_back(unichar_id); dawg->unichar_id_to_patterns(unichar_id, getUnicharset(), &unichar_id_patterns); for (int i = 0; i < unichar_id_patterns.size(); ++i) { // On the first iteration check all the outgoing edges. // On the second iteration check all self-loops. for (int k = 0; k < 2; ++k) { EDGE_REF edge = (k == 0) ? dawg->edge_char_of(node, unichar_id_patterns[i], word_end) : dawg->pattern_loop_edge(pos.dawg_ref, unichar_id_patterns[i], word_end); if (edge == NO_EDGE) continue; if (dawg_debug_level >= 3) { tprintf("Pattern dawg: [%d, " REFFORMAT "] edge=" REFFORMAT "\n", pos.dawg_index, node, edge); tprintf("Letter found in pattern dawg %d\n", pos.dawg_index); } if (dawg->permuter() > *curr_perm) *curr_perm = dawg->permuter(); updated_dawgs->add_unique( DawgPosition(pos.dawg_index, edge, pos.punc_index, pos.punc_ref, pos.back_to_punc), dawg_debug_level > 0, "Append current dawg to updated active dawgs: "); } } } // Fill the given active_dawgs vector with dawgs that could contain the // beginning of the word. If hyphenated() returns true, copy the entries // from hyphen_active_dawgs_ instead. void Dict::init_active_dawgs(DawgPositionVector *active_dawgs, bool ambigs_mode) const { int i; if (hyphenated()) { *active_dawgs = hyphen_active_dawgs_; if (dawg_debug_level >= 3) { for (i = 0; i < hyphen_active_dawgs_.size(); ++i) { tprintf("Adding hyphen beginning dawg [%d, " REFFORMAT "]\n", hyphen_active_dawgs_[i].dawg_index, hyphen_active_dawgs_[i].dawg_ref); } } } else { default_dawgs(active_dawgs, ambigs_mode); } } void Dict::default_dawgs(DawgPositionVector *dawg_pos_vec, bool suppress_patterns) const { bool punc_dawg_available = (punc_dawg_ != NULL) && punc_dawg_->edge_char_of(0, Dawg::kPatternUnicharID, true) != NO_EDGE; for (int i = 0; i < dawgs_.length(); i++) { if (dawgs_[i] != NULL && !(suppress_patterns && (dawgs_[i])->type() == DAWG_TYPE_PATTERN)) { int dawg_ty = dawgs_[i]->type(); bool subsumed_by_punc = kDawgSuccessors[DAWG_TYPE_PUNCTUATION][dawg_ty]; if (dawg_ty == DAWG_TYPE_PUNCTUATION) { *dawg_pos_vec += DawgPosition(-1, NO_EDGE, i, NO_EDGE, false); if (dawg_debug_level >= 3) { tprintf("Adding beginning punc dawg [%d, " REFFORMAT "]\n", i, NO_EDGE); } } else if (!punc_dawg_available || !subsumed_by_punc) { *dawg_pos_vec += DawgPosition(i, NO_EDGE, -1, NO_EDGE, false); if (dawg_debug_level >= 3) { tprintf("Adding beginning dawg [%d, " REFFORMAT "]\n", i, NO_EDGE); } } } } } void Dict::add_document_word(const WERD_CHOICE &best_choice) { // Do not add hyphenated word parts to the document dawg. // hyphen_word_ will be non-NULL after the set_hyphen_word() is // called when the first part of the hyphenated word is // discovered and while the second part of the word is recognized. // hyphen_word_ is cleared in cc_recg() before the next word on // the line is recognized. if (hyphen_word_) return; char filename[CHARS_PER_LINE]; FILE *doc_word_file; int stringlen = best_choice.length(); if (valid_word(best_choice) || stringlen < 2) return; // Discard words that contain >= kDocDictMaxRepChars repeating unichars. if (best_choice.length() >= kDocDictMaxRepChars) { int num_rep_chars = 1; UNICHAR_ID uch_id = best_choice.unichar_id(0); for (int i = 1; i < best_choice.length(); ++i) { if (best_choice.unichar_id(i) != uch_id) { num_rep_chars = 1; uch_id = best_choice.unichar_id(i); } else { ++num_rep_chars; if (num_rep_chars == kDocDictMaxRepChars) return; } } } if (best_choice.certainty() < doc_dict_certainty_threshold || stringlen == 2) { if (best_choice.certainty() < doc_dict_pending_threshold) return; if (!pending_words_->word_in_dawg(best_choice)) { if (stringlen > 2 || (stringlen == 2 && getUnicharset().get_isupper(best_choice.unichar_id(0)) && getUnicharset().get_isupper(best_choice.unichar_id(1)))) { pending_words_->add_word_to_dawg(best_choice); } return; } } if (save_doc_words) { strcpy(filename, getCCUtil()->imagefile.string()); strcat(filename, ".doc"); doc_word_file = open_file (filename, "a"); fprintf(doc_word_file, "%s\n", best_choice.debug_string().string()); fclose(doc_word_file); } document_words_->add_word_to_dawg(best_choice); } void Dict::adjust_word(WERD_CHOICE *word, bool nonword, XHeightConsistencyEnum xheight_consistency, float additional_adjust, bool modify_rating, bool debug) { bool is_han = (getUnicharset().han_sid() != getUnicharset().null_sid() && word->GetTopScriptID() == getUnicharset().han_sid()); bool case_is_ok = (is_han || case_ok(*word, getUnicharset())); bool punc_is_ok = (is_han || !nonword || valid_punctuation(*word)); float adjust_factor = additional_adjust; float new_rating = word->rating(); new_rating += kRatingPad; const char *xheight_triggered = ""; if (word->length() > 1) { // Calculate x-height and y-offset consistency penalties. switch (xheight_consistency) { case XH_INCONSISTENT: adjust_factor += xheight_penalty_inconsistent; xheight_triggered = ", xhtBAD"; break; case XH_SUBNORMAL: adjust_factor += xheight_penalty_subscripts; xheight_triggered = ", xhtSUB"; break; case XH_GOOD: // leave the factor alone - all good! break; } // TODO(eger): if nonword is true, but there is a "core" thats' a dict // word, negate nonword status. } else { if (debug) { tprintf("Consistency could not be calculated.\n"); } } if (debug) { tprintf("%sWord: %s %4.2f%s", nonword ? "Non-" : "", word->unichar_string().string(), word->rating(), xheight_triggered); } if (nonword) { // non-dictionary word if (case_is_ok && punc_is_ok) { adjust_factor += segment_penalty_dict_nonword; new_rating *= adjust_factor; if (debug) tprintf(", W"); } else { adjust_factor += segment_penalty_garbage; new_rating *= adjust_factor; if (debug) { if (!case_is_ok) tprintf(", C"); if (!punc_is_ok) tprintf(", P"); } } } else { // dictionary word if (case_is_ok) { if (!is_han && freq_dawg_ != NULL && freq_dawg_->word_in_dawg(*word)) { word->set_permuter(FREQ_DAWG_PERM); adjust_factor += segment_penalty_dict_frequent_word; new_rating *= adjust_factor; if (debug) tprintf(", F"); } else { adjust_factor += segment_penalty_dict_case_ok; new_rating *= adjust_factor; if (debug) tprintf(", "); } } else { adjust_factor += segment_penalty_dict_case_bad; new_rating *= adjust_factor; if (debug) tprintf(", C"); } } new_rating -= kRatingPad; if (modify_rating) word->set_rating(new_rating); if (debug) tprintf(" %4.2f --> %4.2f\n", adjust_factor, new_rating); word->set_adjust_factor(adjust_factor); } int Dict::valid_word(const WERD_CHOICE &word, bool numbers_ok) const { const WERD_CHOICE *word_ptr = &word; WERD_CHOICE temp_word(word.unicharset()); if (hyphenated() && hyphen_word_->unicharset() == word.unicharset()) { copy_hyphen_info(&temp_word); temp_word += word; word_ptr = &temp_word; } if (word_ptr->length() == 0) return NO_PERM; // Allocate vectors for holding current and updated // active_dawgs and initialize them. DawgPositionVector *active_dawgs = new DawgPositionVector[2]; init_active_dawgs(&(active_dawgs[0]), false); DawgArgs dawg_args(&(active_dawgs[0]), &(active_dawgs[1]), NO_PERM); int last_index = word_ptr->length() - 1; // Call leter_is_okay for each letter in the word. for (int i = hyphen_base_size(); i <= last_index; ++i) { if (!((this->*letter_is_okay_)(&dawg_args, word_ptr->unichar_id(i), i == last_index))) break; // Swap active_dawgs, constraints with the corresponding updated vector. if (dawg_args.updated_dawgs == &(active_dawgs[1])) { dawg_args.updated_dawgs = &(active_dawgs[0]); ++(dawg_args.active_dawgs); } else { ++(dawg_args.updated_dawgs); dawg_args.active_dawgs = &(active_dawgs[0]); } } delete[] active_dawgs; return valid_word_permuter(dawg_args.permuter, numbers_ok) ? dawg_args.permuter : NO_PERM; } bool Dict::valid_bigram(const WERD_CHOICE &word1, const WERD_CHOICE &word2) const { if (bigram_dawg_ == NULL) return false; // Extract the core word from the middle of each word with any digits // replaced with question marks. int w1start, w1end, w2start, w2end; word1.punct_stripped(&w1start, &w1end); word2.punct_stripped(&w2start, &w2end); // We don't want to penalize a single guillemet, hyphen, etc. // But our bigram list doesn't have any information about punctuation. if (w1start >= w1end) return word1.length() < 3; if (w2start >= w2end) return word2.length() < 3; const UNICHARSET& uchset = getUnicharset(); GenericVector<UNICHAR_ID> bigram_string; bigram_string.reserve(w1end + w2end + 1); for (int i = w1start; i < w1end; i++) { const GenericVector<UNICHAR_ID>& normed_ids = getUnicharset().normed_ids(word1.unichar_id(i)); if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0])) bigram_string.push_back(question_unichar_id_); else bigram_string += normed_ids; } bigram_string.push_back(UNICHAR_SPACE); for (int i = w2start; i < w2end; i++) { const GenericVector<UNICHAR_ID>& normed_ids = getUnicharset().normed_ids(word2.unichar_id(i)); if (normed_ids.size() == 1 && uchset.get_isdigit(normed_ids[0])) bigram_string.push_back(question_unichar_id_); else bigram_string += normed_ids; } WERD_CHOICE normalized_word(&uchset, bigram_string.size()); for (int i = 0; i < bigram_string.size(); ++i) { normalized_word.append_unichar_id_space_allocated(bigram_string[i], 1, 0.0f, 0.0f); } return bigram_dawg_->word_in_dawg(normalized_word); } bool Dict::valid_punctuation(const WERD_CHOICE &word) { if (word.length() == 0) return NO_PERM; int i; WERD_CHOICE new_word(word.unicharset()); int last_index = word.length() - 1; int new_len = 0; for (i = 0; i <= last_index; ++i) { UNICHAR_ID unichar_id = (word.unichar_id(i)); if (getUnicharset().get_ispunctuation(unichar_id)) { new_word.append_unichar_id(unichar_id, 1, 0.0, 0.0); } else if (!getUnicharset().get_isalpha(unichar_id) && !getUnicharset().get_isdigit(unichar_id)) { return false; // neither punc, nor alpha, nor digit } else if ((new_len = new_word.length()) == 0 || new_word.unichar_id(new_len-1) != Dawg::kPatternUnicharID) { new_word.append_unichar_id(Dawg::kPatternUnicharID, 1, 0.0, 0.0); } } for (i = 0; i < dawgs_.size(); ++i) { if (dawgs_[i] != NULL && dawgs_[i]->type() == DAWG_TYPE_PUNCTUATION && dawgs_[i]->word_in_dawg(new_word)) return true; } return false; } } // namespace tesseract
1080228-arabicocr11
dict/dict.cpp
C++
asf20
33,224
AM_CPPFLAGS += -I$(top_srcdir)/cutil -I$(top_srcdir)/ccutil \ -I$(top_srcdir)/ccstruct -I$(top_srcdir)/viewer if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS \ -fvisibility=hidden -fvisibility-inlines-hidden endif noinst_HEADERS = \ dawg.h dawg_cache.h dict.h matchdefs.h \ stopper.h trie.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_dict.la else lib_LTLIBRARIES = libtesseract_dict.la libtesseract_dict_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_dict_la_LIBADD = \ ../ccutil/libtesseract_ccutil.la \ ../cutil/libtesseract_cutil.la \ ../ccstruct/libtesseract_ccstruct.la \ ../viewer/libtesseract_viewer.la endif libtesseract_dict_la_SOURCES = \ context.cpp \ dawg.cpp dawg_cache.cpp dict.cpp hyphen.cpp \ permdawg.cpp stopper.cpp trie.cpp
1080228-arabicocr11
dict/Makefile.am
Makefile
asf20
827
/****************************************************************************** ** Filename: stopper.h ** Purpose: Stopping criteria for word classifier. ** Author: Dan Johnson ** History: Wed May 1 09:42:57 1991, DSJ, Created. ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 STOPPER_H #define STOPPER_H /**---------------------------------------------------------------------------- Include Files and Type Defines ----------------------------------------------------------------------------**/ #include "genericvector.h" #include "params.h" #include "ratngs.h" #include "unichar.h" class WERD_CHOICE; typedef uinT8 BLOB_WIDTH; struct DANGERR_INFO { DANGERR_INFO() : begin(-1), end(-1), dangerous(false), correct_is_ngram(false), leftmost(INVALID_UNICHAR_ID) {} DANGERR_INFO(int b, int e, bool d, bool n, UNICHAR_ID l) : begin(b), end(e), dangerous(d), correct_is_ngram(n), leftmost(l) {} int begin; int end; bool dangerous; bool correct_is_ngram; UNICHAR_ID leftmost; // in the replacement, what's the leftmost character? }; typedef GenericVector<DANGERR_INFO> DANGERR; #endif
1080228-arabicocr11
dict/stopper.h
C++
asf20
1,797
/* -*-C-*- ******************************************************************************** * * File: trie.c (Formerly trie.c) * Description: Functions to build a trie data structure. * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri Jul 26 12:18:10 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4800) // int/bool warnings #endif #include "trie.h" #include "callcpp.h" #include "dawg.h" #include "dict.h" #include "freelist.h" #include "genericvector.h" #include "helpers.h" #include "kdpair.h" namespace tesseract { const char kDoNotReverse[] = "RRP_DO_NO_REVERSE"; const char kReverseIfHasRTL[] = "RRP_REVERSE_IF_HAS_RTL"; const char kForceReverse[] = "RRP_FORCE_REVERSE"; const char * const RTLReversePolicyNames[] = { kDoNotReverse, kReverseIfHasRTL, kForceReverse }; const char Trie::kAlphaPatternUnicode[] = "\u2000"; const char Trie::kDigitPatternUnicode[] = "\u2001"; const char Trie::kAlphanumPatternUnicode[] = "\u2002"; const char Trie::kPuncPatternUnicode[] = "\u2003"; const char Trie::kLowerPatternUnicode[] = "\u2004"; const char Trie::kUpperPatternUnicode[] = "\u2005"; const char *Trie::get_reverse_policy_name(RTLReversePolicy reverse_policy) { return RTLReversePolicyNames[reverse_policy]; } // Reset the Trie to empty. void Trie::clear() { nodes_.delete_data_pointers(); nodes_.clear(); root_back_freelist_.clear(); num_edges_ = 0; new_dawg_node(); // Need to allocate node 0. } bool Trie::edge_char_of(NODE_REF node_ref, NODE_REF next_node, int direction, bool word_end, UNICHAR_ID unichar_id, EDGE_RECORD **edge_ptr, EDGE_INDEX *edge_index) const { if (debug_level_ == 3) { tprintf("edge_char_of() given node_ref " REFFORMAT " next_node " REFFORMAT " direction %d word_end %d unichar_id %d, exploring node:\n", node_ref, next_node, direction, word_end, unichar_id); if (node_ref != NO_EDGE) { print_node(node_ref, nodes_[node_ref]->forward_edges.size()); } } if (node_ref == NO_EDGE) return false; assert(node_ref < nodes_.size()); EDGE_VECTOR &vec = (direction == FORWARD_EDGE) ? nodes_[node_ref]->forward_edges : nodes_[node_ref]->backward_edges; int vec_size = vec.size(); if (node_ref == 0 && direction == FORWARD_EDGE) { // binary search EDGE_INDEX start = 0; EDGE_INDEX end = vec_size - 1; EDGE_INDEX k; int compare; while (start <= end) { k = (start + end) >> 1; // (start + end) / 2 compare = given_greater_than_edge_rec(next_node, word_end, unichar_id, vec[k]); if (compare == 0) { // given == vec[k] *edge_ptr = &(vec[k]); *edge_index = k; return true; } else if (compare == 1) { // given > vec[k] start = k + 1; } else { // given < vec[k] end = k - 1; } } } else { // linear search for (int i = 0; i < vec_size; ++i) { EDGE_RECORD &edge_rec = vec[i]; if (edge_rec_match(next_node, word_end, unichar_id, next_node_from_edge_rec(edge_rec), end_of_word_from_edge_rec(edge_rec), unichar_id_from_edge_rec(edge_rec))) { *edge_ptr = &(edge_rec); *edge_index = i; return true; } } } return false; // not found } bool Trie::add_edge_linkage(NODE_REF node1, NODE_REF node2, bool marker_flag, int direction, bool word_end, UNICHAR_ID unichar_id) { EDGE_VECTOR *vec = (direction == FORWARD_EDGE) ? &(nodes_[node1]->forward_edges) : &(nodes_[node1]->backward_edges); int search_index; if (node1 == 0 && direction == FORWARD_EDGE) { search_index = 0; // find the index to make the add sorted while (search_index < vec->size() && given_greater_than_edge_rec(node2, word_end, unichar_id, (*vec)[search_index]) == 1) { search_index++; } } else { search_index = vec->size(); // add is unsorted, so index does not matter } EDGE_RECORD edge_rec; link_edge(&edge_rec, node2, marker_flag, direction, word_end, unichar_id); if (node1 == 0 && direction == BACKWARD_EDGE && !root_back_freelist_.empty()) { EDGE_INDEX edge_index = root_back_freelist_.pop_back(); (*vec)[edge_index] = edge_rec; } else if (search_index < vec->size()) { vec->insert(edge_rec, search_index); } else { vec->push_back(edge_rec); } if (debug_level_ > 1) { tprintf("new edge in nodes_[" REFFORMAT "]: ", node1); print_edge_rec(edge_rec); tprintf("\n"); } num_edges_++; return true; } void Trie::add_word_ending(EDGE_RECORD *edge_ptr, NODE_REF the_next_node, bool marker_flag, UNICHAR_ID unichar_id) { EDGE_RECORD *back_edge_ptr; EDGE_INDEX back_edge_index; ASSERT_HOST(edge_char_of(the_next_node, NO_EDGE, BACKWARD_EDGE, false, unichar_id, &back_edge_ptr, &back_edge_index)); if (marker_flag) { *back_edge_ptr |= (MARKER_FLAG << flag_start_bit_); *edge_ptr |= (MARKER_FLAG << flag_start_bit_); } // Mark both directions as end of word. *back_edge_ptr |= (WERD_END_FLAG << flag_start_bit_); *edge_ptr |= (WERD_END_FLAG << flag_start_bit_); } bool Trie::add_word_to_dawg(const WERD_CHOICE &word, const GenericVector<bool> *repetitions) { if (word.length() <= 0) return false; // can't add empty words if (repetitions != NULL) ASSERT_HOST(repetitions->size() == word.length()); // Make sure the word does not contain invalid unchar ids. for (int i = 0; i < word.length(); ++i) { if (word.unichar_id(i) < 0 || word.unichar_id(i) >= unicharset_size_) return false; } EDGE_RECORD *edge_ptr; NODE_REF last_node = 0; NODE_REF the_next_node; bool marker_flag = false; EDGE_INDEX edge_index; int i; inT32 still_finding_chars = true; inT32 word_end = false; bool add_failed = false; bool found; if (debug_level_ > 1) word.print("\nAdding word: "); UNICHAR_ID unichar_id; for (i = 0; i < word.length() - 1; ++i) { unichar_id = word.unichar_id(i); marker_flag = (repetitions != NULL) ? (*repetitions)[i] : false; if (debug_level_ > 1) tprintf("Adding letter %d\n", unichar_id); if (still_finding_chars) { found = edge_char_of(last_node, NO_EDGE, FORWARD_EDGE, word_end, unichar_id, &edge_ptr, &edge_index); if (found && debug_level_ > 1) { tprintf("exploring edge " REFFORMAT " in node " REFFORMAT "\n", edge_index, last_node); } if (!found) { still_finding_chars = false; } else if (next_node_from_edge_rec(*edge_ptr) == 0) { // We hit the end of an existing word, but the new word is longer. // In this case we have to disconnect the existing word from the // backwards root node, mark the current position as end-of-word // and add new nodes for the increased length. Disconnecting the // existing word from the backwards root node requires a linear // search, so it is much faster to add the longest words first, // to avoid having to come here. word_end = true; still_finding_chars = false; remove_edge(last_node, 0, word_end, unichar_id); } else { // We have to add a new branch here for the new word. if (marker_flag) set_marker_flag_in_edge_rec(edge_ptr); last_node = next_node_from_edge_rec(*edge_ptr); } } if (!still_finding_chars) { the_next_node = new_dawg_node(); if (debug_level_ > 1) tprintf("adding node " REFFORMAT "\n", the_next_node); if (the_next_node == 0) { add_failed = true; break; } if (!add_new_edge(last_node, the_next_node, marker_flag, word_end, unichar_id)) { add_failed = true; break; } word_end = false; last_node = the_next_node; } } the_next_node = 0; unichar_id = word.unichar_id(i); marker_flag = (repetitions != NULL) ? (*repetitions)[i] : false; if (debug_level_ > 1) tprintf("Adding letter %d\n", unichar_id); if (still_finding_chars && edge_char_of(last_node, NO_EDGE, FORWARD_EDGE, false, unichar_id, &edge_ptr, &edge_index)) { // An extension of this word already exists in the trie, so we // only have to add the ending flags in both directions. add_word_ending(edge_ptr, next_node_from_edge_rec(*edge_ptr), marker_flag, unichar_id); } else { // Add a link to node 0. All leaves connect to node 0 so the back links can // be used in reduction to a dawg. This root backward node has one edge // entry for every word, (except prefixes of longer words) so it is huge. if (!add_failed && !add_new_edge(last_node, the_next_node, marker_flag, true, unichar_id)) add_failed = true; } if (add_failed) { tprintf("Re-initializing document dictionary...\n"); clear(); return false; } else { return true; } } NODE_REF Trie::new_dawg_node() { TRIE_NODE_RECORD *node = new TRIE_NODE_RECORD(); if (node == NULL) return 0; // failed to create new node nodes_.push_back(node); return nodes_.length() - 1; } // Sort function to sort words by decreasing order of length. static int sort_strings_by_dec_length(const void* v1, const void* v2) { const STRING* s1 = reinterpret_cast<const STRING*>(v1); const STRING* s2 = reinterpret_cast<const STRING*>(v2); return s2->length() - s1->length(); } bool Trie::read_and_add_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse_policy) { GenericVector<STRING> word_list; if (!read_word_list(filename, unicharset, reverse_policy, &word_list)) return false; word_list.sort(sort_strings_by_dec_length); return add_word_list(word_list, unicharset); } bool Trie::read_word_list(const char *filename, const UNICHARSET &unicharset, Trie::RTLReversePolicy reverse_policy, GenericVector<STRING>* words) { FILE *word_file; char string[CHARS_PER_LINE]; int word_count = 0; word_file = fopen(filename, "rb"); if (word_file == NULL) return false; while (fgets(string, CHARS_PER_LINE, word_file) != NULL) { chomp_string(string); // remove newline WERD_CHOICE word(string, unicharset); if ((reverse_policy == RRP_REVERSE_IF_HAS_RTL && word.has_rtl_unichar_id()) || reverse_policy == RRP_FORCE_REVERSE) { word.reverse_and_mirror_unichar_ids(); } ++word_count; if (debug_level_ && word_count % 10000 == 0) tprintf("Read %d words so far\n", word_count); if (word.length() != 0 && !word.contains_unichar_id(INVALID_UNICHAR_ID)) { words->push_back(word.unichar_string()); } else if (debug_level_) { tprintf("Skipping invalid word %s\n", string); if (debug_level_ >= 3) word.print(); } } if (debug_level_) tprintf("Read %d words total.\n", word_count); fclose(word_file); return true; } bool Trie::add_word_list(const GenericVector<STRING>& words, const UNICHARSET &unicharset) { for (int i = 0; i < words.size(); ++i) { WERD_CHOICE word(words[i].string(), unicharset); if (!word_in_dawg(word)) { add_word_to_dawg(word); if (!word_in_dawg(word)) { tprintf("Error: word '%s' not in DAWG after adding it\n", words[i].string()); return false; } } } return true; } void Trie::initialize_patterns(UNICHARSET *unicharset) { unicharset->unichar_insert(kAlphaPatternUnicode); alpha_pattern_ = unicharset->unichar_to_id(kAlphaPatternUnicode); unicharset->unichar_insert(kDigitPatternUnicode); digit_pattern_ = unicharset->unichar_to_id(kDigitPatternUnicode); unicharset->unichar_insert(kAlphanumPatternUnicode); alphanum_pattern_ = unicharset->unichar_to_id(kAlphanumPatternUnicode); unicharset->unichar_insert(kPuncPatternUnicode); punc_pattern_ = unicharset->unichar_to_id(kPuncPatternUnicode); unicharset->unichar_insert(kLowerPatternUnicode); lower_pattern_ = unicharset->unichar_to_id(kLowerPatternUnicode); unicharset->unichar_insert(kUpperPatternUnicode); upper_pattern_ = unicharset->unichar_to_id(kUpperPatternUnicode); initialized_patterns_ = true; unicharset_size_ = unicharset->size(); } void Trie::unichar_id_to_patterns(UNICHAR_ID unichar_id, const UNICHARSET &unicharset, GenericVector<UNICHAR_ID> *vec) const { bool is_alpha = unicharset.get_isalpha(unichar_id); if (is_alpha) { vec->push_back(alpha_pattern_); vec->push_back(alphanum_pattern_); if (unicharset.get_islower(unichar_id)) { vec->push_back(lower_pattern_); } else if (unicharset.get_isupper(unichar_id)) { vec->push_back(upper_pattern_); } } if (unicharset.get_isdigit(unichar_id)) { vec->push_back(digit_pattern_); if (!is_alpha) vec->push_back(alphanum_pattern_); } if (unicharset.get_ispunctuation(unichar_id)) { vec->push_back(punc_pattern_); } } UNICHAR_ID Trie::character_class_to_pattern(char ch) { if (ch == 'c') { return alpha_pattern_; } else if (ch == 'd') { return digit_pattern_; } else if (ch == 'n') { return alphanum_pattern_; } else if (ch == 'p') { return punc_pattern_; } else if (ch == 'a') { return lower_pattern_; } else if (ch == 'A') { return upper_pattern_; } else { return INVALID_UNICHAR_ID; } } bool Trie::read_pattern_list(const char *filename, const UNICHARSET &unicharset) { if (!initialized_patterns_) { tprintf("please call initialize_patterns() before read_pattern_list()\n"); return false; } FILE *pattern_file = fopen(filename, "rb"); if (pattern_file == NULL) { tprintf("Error opening pattern file %s\n", filename); return false; } int pattern_count = 0; char string[CHARS_PER_LINE]; while (fgets(string, CHARS_PER_LINE, pattern_file) != NULL) { chomp_string(string); // remove newline // Parse the pattern and construct a unichar id vector. // Record the number of repetitions of each unichar in the parallel vector. WERD_CHOICE word(&unicharset); GenericVector<bool> repetitions_vec; const char *str_ptr = string; int step = unicharset.step(str_ptr); bool failed = false; while (step > 0) { UNICHAR_ID curr_unichar_id = INVALID_UNICHAR_ID; if (step == 1 && *str_ptr == '\\') { ++str_ptr; if (*str_ptr == '\\') { // regular '\' unichar that was escaped curr_unichar_id = unicharset.unichar_to_id(str_ptr, step); } else { if (word.length() < kSaneNumConcreteChars) { tprintf("Please provide at least %d concrete characters at the" " beginning of the pattern\n", kSaneNumConcreteChars); failed = true; break; } // Parse character class from expression. curr_unichar_id = character_class_to_pattern(*str_ptr); } } else { curr_unichar_id = unicharset.unichar_to_id(str_ptr, step); } if (curr_unichar_id == INVALID_UNICHAR_ID) { failed = true; break; // failed to parse this pattern } word.append_unichar_id(curr_unichar_id, 1, 0.0, 0.0); repetitions_vec.push_back(false); str_ptr += step; step = unicharset.step(str_ptr); // Check if there is a repetition pattern specified after this unichar. if (step == 1 && *str_ptr == '\\' && *(str_ptr+1) == '*') { repetitions_vec[repetitions_vec.size()-1] = true; str_ptr += 2; step = unicharset.step(str_ptr); } } if (failed) { tprintf("Invalid user pattern %s\n", string); continue; } // Insert the pattern into the trie. if (debug_level_ > 2) { tprintf("Inserting expanded user pattern %s\n", word.debug_string().string()); } if (!this->word_in_dawg(word)) { this->add_word_to_dawg(word, &repetitions_vec); if (!this->word_in_dawg(word)) { tprintf("Error: failed to insert pattern '%s'\n", string); } } ++pattern_count; } if (debug_level_) { tprintf("Read %d valid patterns from %s\n", pattern_count, filename); } fclose(pattern_file); return true; } void Trie::remove_edge_linkage(NODE_REF node1, NODE_REF node2, int direction, bool word_end, UNICHAR_ID unichar_id) { EDGE_RECORD *edge_ptr = NULL; EDGE_INDEX edge_index = 0; ASSERT_HOST(edge_char_of(node1, node2, direction, word_end, unichar_id, &edge_ptr, &edge_index)); if (debug_level_ > 1) { tprintf("removed edge in nodes_[" REFFORMAT "]: ", node1); print_edge_rec(*edge_ptr); tprintf("\n"); } if (direction == FORWARD_EDGE) { nodes_[node1]->forward_edges.remove(edge_index); } else if (node1 == 0) { KillEdge(&nodes_[node1]->backward_edges[edge_index]); root_back_freelist_.push_back(edge_index); } else { nodes_[node1]->backward_edges.remove(edge_index); } --num_edges_; } // Some optimizations employed in add_word_to_dawg and trie_to_dawg: // 1 Avoid insertion sorting or bubble sorting the tail root node // (back links on node 0, a list of all the leaves.). The node is // huge, and sorting it with n^2 time is terrible. // 2 Avoid using GenericVector::remove on the tail root node. // (a) During add of words to the trie, zero-out the unichars and // keep a freelist of spaces to re-use. // (b) During reduction, just zero-out the unichars of deleted back // links, skipping zero entries while searching. // 3 Avoid linear search of the tail root node. This has to be done when // a suffix is added to an existing word. Adding words by decreasing // length avoids this problem entirely. Words can still be added in // any order, but it is faster to add the longest first. SquishedDawg *Trie::trie_to_dawg() { root_back_freelist_.clear(); // Will be invalided by trie_to_dawg. if (debug_level_ > 2) { print_all("Before reduction:", MAX_NODE_EDGES_DISPLAY); } NODE_MARKER reduced_nodes = new bool[nodes_.size()]; for (int i = 0; i < nodes_.size(); i++) reduced_nodes[i] = 0; this->reduce_node_input(0, reduced_nodes); delete[] reduced_nodes; if (debug_level_ > 2) { print_all("After reduction:", MAX_NODE_EDGES_DISPLAY); } // Build a translation map from node indices in nodes_ vector to // their target indices in EDGE_ARRAY. NODE_REF *node_ref_map = new NODE_REF[nodes_.size() + 1]; int i, j; node_ref_map[0] = 0; for (i = 0; i < nodes_.size(); ++i) { node_ref_map[i+1] = node_ref_map[i] + nodes_[i]->forward_edges.size(); } int num_forward_edges = node_ref_map[i]; // Convert nodes_ vector into EDGE_ARRAY translating the next node references // in edges using node_ref_map. Empty nodes and backward edges are dropped. EDGE_ARRAY edge_array = (EDGE_ARRAY)memalloc(num_forward_edges * sizeof(EDGE_RECORD)); EDGE_ARRAY edge_array_ptr = edge_array; for (i = 0; i < nodes_.size(); ++i) { TRIE_NODE_RECORD *node_ptr = nodes_[i]; int end = node_ptr->forward_edges.size(); for (j = 0; j < end; ++j) { EDGE_RECORD &edge_rec = node_ptr->forward_edges[j]; NODE_REF node_ref = next_node_from_edge_rec(edge_rec); ASSERT_HOST(node_ref < nodes_.size()); UNICHAR_ID unichar_id = unichar_id_from_edge_rec(edge_rec); link_edge(edge_array_ptr, node_ref_map[node_ref], false, FORWARD_EDGE, end_of_word_from_edge_rec(edge_rec), unichar_id); if (j == end - 1) set_marker_flag_in_edge_rec(edge_array_ptr); ++edge_array_ptr; } } delete[] node_ref_map; return new SquishedDawg(edge_array, num_forward_edges, type_, lang_, perm_, unicharset_size_, debug_level_); } bool Trie::eliminate_redundant_edges(NODE_REF node, const EDGE_RECORD &edge1, const EDGE_RECORD &edge2) { if (debug_level_ > 1) { tprintf("\nCollapsing node %d:\n", node); print_node(node, MAX_NODE_EDGES_DISPLAY); tprintf("Candidate edges: "); print_edge_rec(edge1); tprintf(", "); print_edge_rec(edge2); tprintf("\n\n"); } NODE_REF next_node1 = next_node_from_edge_rec(edge1); NODE_REF next_node2 = next_node_from_edge_rec(edge2); TRIE_NODE_RECORD *next_node2_ptr = nodes_[next_node2]; // Translate all edges going to/from next_node2 to go to/from next_node1. EDGE_RECORD *edge_ptr = NULL; EDGE_INDEX edge_index; int i; // The backward link in node to next_node2 will be zeroed out by the caller. // Copy all the backward links in next_node2 to node next_node1 for (i = 0; i < next_node2_ptr->backward_edges.size(); ++i) { const EDGE_RECORD &bkw_edge = next_node2_ptr->backward_edges[i]; NODE_REF curr_next_node = next_node_from_edge_rec(bkw_edge); UNICHAR_ID curr_unichar_id = unichar_id_from_edge_rec(bkw_edge); int curr_word_end = end_of_word_from_edge_rec(bkw_edge); bool marker_flag = marker_flag_from_edge_rec(bkw_edge); add_edge_linkage(next_node1, curr_next_node, marker_flag, BACKWARD_EDGE, curr_word_end, curr_unichar_id); // Relocate the corresponding forward edge in curr_next_node ASSERT_HOST(edge_char_of(curr_next_node, next_node2, FORWARD_EDGE, curr_word_end, curr_unichar_id, &edge_ptr, &edge_index)); set_next_node_in_edge_rec(edge_ptr, next_node1); } int next_node2_num_edges = (next_node2_ptr->forward_edges.size() + next_node2_ptr->backward_edges.size()); if (debug_level_ > 1) { tprintf("removed %d edges from node " REFFORMAT "\n", next_node2_num_edges, next_node2); } next_node2_ptr->forward_edges.clear(); next_node2_ptr->backward_edges.clear(); num_edges_ -= next_node2_num_edges; return true; } bool Trie::reduce_lettered_edges(EDGE_INDEX edge_index, UNICHAR_ID unichar_id, NODE_REF node, EDGE_VECTOR* backward_edges, NODE_MARKER reduced_nodes) { if (debug_level_ > 1) tprintf("reduce_lettered_edges(edge=" REFFORMAT ")\n", edge_index); // Compare each of the edge pairs with the given unichar_id. bool did_something = false; for (int i = edge_index; i < backward_edges->size() - 1; ++i) { // Find the first edge that can be eliminated. UNICHAR_ID curr_unichar_id = INVALID_UNICHAR_ID; while (i < backward_edges->size()) { if (!DeadEdge((*backward_edges)[i])) { curr_unichar_id = unichar_id_from_edge_rec((*backward_edges)[i]); if (curr_unichar_id != unichar_id) return did_something; if (can_be_eliminated((*backward_edges)[i])) break; } ++i; } if (i == backward_edges->size()) break; const EDGE_RECORD &edge_rec = (*backward_edges)[i]; // Compare it to the rest of the edges with the given unichar_id. for (int j = i + 1; j < backward_edges->size(); ++j) { const EDGE_RECORD &next_edge_rec = (*backward_edges)[j]; if (DeadEdge(next_edge_rec)) continue; UNICHAR_ID next_id = unichar_id_from_edge_rec(next_edge_rec); if (next_id != unichar_id) break; if (end_of_word_from_edge_rec(next_edge_rec) == end_of_word_from_edge_rec(edge_rec) && can_be_eliminated(next_edge_rec) && eliminate_redundant_edges(node, edge_rec, next_edge_rec)) { reduced_nodes[next_node_from_edge_rec(edge_rec)] = 0; did_something = true; KillEdge(&(*backward_edges)[j]); } } } return did_something; } void Trie::sort_edges(EDGE_VECTOR *edges) { int num_edges = edges->size(); if (num_edges <= 1) return; GenericVector<KDPairInc<UNICHAR_ID, EDGE_RECORD> > sort_vec; sort_vec.reserve(num_edges); for (int i = 0; i < num_edges; ++i) { sort_vec.push_back(KDPairInc<UNICHAR_ID, EDGE_RECORD>( unichar_id_from_edge_rec((*edges)[i]), (*edges)[i])); } sort_vec.sort(); for (int i = 0; i < num_edges; ++i) (*edges)[i] = sort_vec[i].data; } void Trie::reduce_node_input(NODE_REF node, NODE_MARKER reduced_nodes) { EDGE_VECTOR &backward_edges = nodes_[node]->backward_edges; sort_edges(&backward_edges); if (debug_level_ > 1) { tprintf("reduce_node_input(node=" REFFORMAT ")\n", node); print_node(node, MAX_NODE_EDGES_DISPLAY); } EDGE_INDEX edge_index = 0; while (edge_index < backward_edges.size()) { if (DeadEdge(backward_edges[edge_index])) continue; UNICHAR_ID unichar_id = unichar_id_from_edge_rec(backward_edges[edge_index]); while (reduce_lettered_edges(edge_index, unichar_id, node, &backward_edges, reduced_nodes)); while (++edge_index < backward_edges.size()) { UNICHAR_ID id = unichar_id_from_edge_rec(backward_edges[edge_index]); if (!DeadEdge(backward_edges[edge_index]) && id != unichar_id) break; } } reduced_nodes[node] = true; // mark as reduced if (debug_level_ > 1) { tprintf("Node " REFFORMAT " after reduction:\n", node); print_node(node, MAX_NODE_EDGES_DISPLAY); } for (int i = 0; i < backward_edges.size(); ++i) { if (DeadEdge(backward_edges[i])) continue; NODE_REF next_node = next_node_from_edge_rec(backward_edges[i]); if (next_node != 0 && !reduced_nodes[next_node]) { reduce_node_input(next_node, reduced_nodes); } } } void Trie::print_node(NODE_REF node, int max_num_edges) const { if (node == NO_EDGE) return; // nothing to print TRIE_NODE_RECORD *node_ptr = nodes_[node]; int num_fwd = node_ptr->forward_edges.size(); int num_bkw = node_ptr->backward_edges.size(); EDGE_VECTOR *vec; for (int dir = 0; dir < 2; ++dir) { if (dir == 0) { vec = &(node_ptr->forward_edges); tprintf(REFFORMAT " (%d %d): ", node, num_fwd, num_bkw); } else { vec = &(node_ptr->backward_edges); tprintf("\t"); } int i; for (i = 0; (dir == 0 ? i < num_fwd : i < num_bkw) && i < max_num_edges; ++i) { if (DeadEdge((*vec)[i])) continue; print_edge_rec((*vec)[i]); tprintf(" "); } if (dir == 0 ? i < num_fwd : i < num_bkw) tprintf("..."); tprintf("\n"); } } } // namespace tesseract
1080228-arabicocr11
dict/trie.cpp
C
asf20
27,964
/****************************************************************************** ** Filename: matchdefs.h ** Purpose: Generic interface definitions for feature matchers. ** Author: Dan Johnson ** History: Fri Jan 19 09:21:25 1990, DSJ, Created. ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 MATCHDEFS_H #define MATCHDEFS_H /**---------------------------------------------------------------------------- Include Files and Type Defines ----------------------------------------------------------------------------**/ #include "host.h" #include <stdio.h> #include "unichar.h" /* define the maximum number of classes defined for any matcher and the maximum class id for any matcher. This must be changed if more different classes need to be classified */ #define MAX_NUM_CLASSES MAX_INT16 #define MAX_CLASS_ID (MAX_NUM_CLASSES - 1) /** a CLASS_ID is the ascii character to be associated with a class */ typedef UNICHAR_ID CLASS_ID; #define NO_CLASS (0) /** a PROTO_ID is the index of a prototype within it's class. Valid proto id's are 0 to N-1 where N is the number of prototypes that make up the class. */ typedef inT16 PROTO_ID; #define NO_PROTO (-1) /** FEATURE_ID is the index of a feature within a character description The feature id ranges from 0 to N-1 where N is the number of features in a character description. */ typedef uinT8 FEATURE_ID; #define NO_FEATURE 255 #define NOISE_FEATURE 254 #define MISSING_PROTO 254 #define MAX_NUM_FEAT 40 #define MAX_FEATURE_ID 250 /** a RATING is the match rating returned by a classifier. Higher is better. */ typedef FLOAT32 RATING; /** a CERTAINTY is an indication of the degree of confidence of the classifier. Higher is better. 0 means the match is as good as the mean of the matches seen in training. -1 means the match was one standard deviation worse than the training matches, etc. */ typedef FLOAT32 CERTAINTY; /** define a data structure to hold a single match result */ typedef struct { CLASS_ID Class; RATING Rating; CERTAINTY Certainty; } MATCH_RESULT; /** define a data structure for holding an array of match results */ typedef MATCH_RESULT SORTED_CLASSES[MAX_CLASS_ID + 1]; /*---------------------------------------------------------------------------- Public Function Prototypes ----------------------------------------------------------------------------*/ /** all feature matchers that are to be used with the high level classifier must support the following interface. The names will, of course, be unique for each different matcher. Note also that FEATURE_STRUCT is a data structure that is defined specifically for each feature extractor/matcher pair. */ /* misc test functions for proto id's and feature id's */ #define IsValidFeature(Fid) ((Fid) < MAX_FEATURE_ID) #define IsValidProto(Pid) ((Pid) >= 0) #if defined(__STDC__) || defined(__cplusplus) # define _ARGS(s) s #else # define _ARGS(s) () #endif /* matchdefs.c */ int CompareMatchResults _ARGS ((MATCH_RESULT * Result1, MATCH_RESULT * Result2)); void PrintMatchResult _ARGS ((FILE * File, MATCH_RESULT * MatchResult)); void PrintMatchResults _ARGS ((FILE * File, int N, MATCH_RESULT MatchResults[])); #undef _ARGS /*---------------------------------------------------------------------------- Global Data Definitions and Declarations ----------------------------------------------------------------------------*/ #endif
1080228-arabicocr11
dict/matchdefs.h
C
asf20
4,133
/* -*-C-*- ******************************************************************************** * * File: dawg.c (Formerly dawg.c) * Description: Use a Directed Accyclic Word Graph * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Wed Jul 24 16:59:16 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4800) // int/bool warnings #endif #include "dawg.h" #include "cutil.h" #include "dict.h" #include "emalloc.h" #include "freelist.h" #include "helpers.h" #include "strngs.h" #include "tesscallback.h" #include "tprintf.h" /*---------------------------------------------------------------------- F u n c t i o n s f o r D a w g ----------------------------------------------------------------------*/ namespace tesseract { bool Dawg::prefix_in_dawg(const WERD_CHOICE &word, bool requires_complete) const { if (word.length() == 0) return !requires_complete; NODE_REF node = 0; int end_index = word.length() - 1; for (int i = 0; i < end_index; i++) { EDGE_REF edge = edge_char_of(node, word.unichar_id(i), false); if (edge == NO_EDGE) { return false; } if ((node = next_node(edge)) == 0) { // This only happens if all words following this edge terminate -- // there are no larger words. See Trie::add_word_to_dawg() return false; } } // Now check the last character. return edge_char_of(node, word.unichar_id(end_index), requires_complete) != NO_EDGE; } bool Dawg::word_in_dawg(const WERD_CHOICE &word) const { return prefix_in_dawg(word, true); } int Dawg::check_for_words(const char *filename, const UNICHARSET &unicharset, bool enable_wildcard) const { if (filename == NULL) return 0; FILE *word_file; char string [CHARS_PER_LINE]; int misses = 0; UNICHAR_ID wildcard = unicharset.unichar_to_id(kWildcard); word_file = open_file (filename, "r"); while (fgets (string, CHARS_PER_LINE, word_file) != NULL) { chomp_string(string); // remove newline WERD_CHOICE word(string, unicharset); if (word.length() > 0 && !word.contains_unichar_id(INVALID_UNICHAR_ID)) { if (!match_words(&word, 0, 0, enable_wildcard ? wildcard : INVALID_UNICHAR_ID)) { tprintf("Missing word: %s\n", string); ++misses; } } else { tprintf("Failed to create a valid word from %s\n", string); } } fclose (word_file); // Make sure the user sees this with fprintf instead of tprintf. if (debug_level_) tprintf("Number of lost words=%d\n", misses); return misses; } void Dawg::iterate_words(const UNICHARSET &unicharset, TessCallback1<const WERD_CHOICE *> *cb) const { WERD_CHOICE word(&unicharset); iterate_words_rec(word, 0, cb); } void CallWithUTF8(TessCallback1<const char *> *cb, const WERD_CHOICE *wc) { STRING s; wc->string_and_lengths(&s, NULL); cb->Run(s.string()); } void Dawg::iterate_words(const UNICHARSET &unicharset, TessCallback1<const char *> *cb) const { TessCallback1<const WERD_CHOICE *> *shim = NewPermanentTessCallback(CallWithUTF8, cb); WERD_CHOICE word(&unicharset); iterate_words_rec(word, 0, shim); delete shim; } void Dawg::iterate_words_rec(const WERD_CHOICE &word_so_far, NODE_REF to_explore, TessCallback1<const WERD_CHOICE *> *cb) const { NodeChildVector children; this->unichar_ids_of(to_explore, &children, false); for (int i = 0; i < children.size(); i++) { WERD_CHOICE next_word(word_so_far); next_word.append_unichar_id(children[i].unichar_id, 1, 0.0, 0.0); if (this->end_of_word(children[i].edge_ref)) { cb->Run(&next_word); } NODE_REF next = next_node(children[i].edge_ref); if (next != 0) { iterate_words_rec(next_word, next, cb); } } } bool Dawg::match_words(WERD_CHOICE *word, inT32 index, NODE_REF node, UNICHAR_ID wildcard) const { EDGE_REF edge; inT32 word_end; if (wildcard != INVALID_UNICHAR_ID && word->unichar_id(index) == wildcard) { bool any_matched = false; NodeChildVector vec; this->unichar_ids_of(node, &vec, false); for (int i = 0; i < vec.size(); ++i) { word->set_unichar_id(vec[i].unichar_id, index); if (match_words(word, index, node, wildcard)) any_matched = true; } word->set_unichar_id(wildcard, index); return any_matched; } else { word_end = index == word->length() - 1; edge = edge_char_of(node, word->unichar_id(index), word_end); if (edge != NO_EDGE) { // normal edge in DAWG node = next_node(edge); if (word_end) { if (debug_level_ > 1) word->print("match_words() found: "); return true; } else if (node != 0) { return match_words(word, index+1, node, wildcard); } } } return false; } void Dawg::init(DawgType type, const STRING &lang, PermuterType perm, int unicharset_size, int debug_level) { type_ = type; lang_ = lang; perm_ = perm; ASSERT_HOST(unicharset_size > 0); unicharset_size_ = unicharset_size; // Set bit masks. We will use the value unicharset_size_ as a null char, so // the actual number of unichars is unicharset_size_ + 1. flag_start_bit_ = ceil(log(unicharset_size_ + 1.0) / log(2.0)); next_node_start_bit_ = flag_start_bit_ + NUM_FLAG_BITS; letter_mask_ = ~(~0ull << flag_start_bit_); next_node_mask_ = ~0ull << (flag_start_bit_ + NUM_FLAG_BITS); flags_mask_ = ~(letter_mask_ | next_node_mask_); debug_level_ = debug_level; } /*---------------------------------------------------------------------- F u n c t i o n s f o r S q u i s h e d D a w g ----------------------------------------------------------------------*/ SquishedDawg::~SquishedDawg() { memfree(edges_); } EDGE_REF SquishedDawg::edge_char_of(NODE_REF node, UNICHAR_ID unichar_id, bool word_end) const { EDGE_REF edge = node; if (node == 0) { // binary search EDGE_REF start = 0; EDGE_REF end = num_forward_edges_in_node0 - 1; int compare; while (start <= end) { edge = (start + end) >> 1; // (start + end) / 2 compare = given_greater_than_edge_rec(NO_EDGE, word_end, unichar_id, edges_[edge]); if (compare == 0) { // given == vec[k] return edge; } else if (compare == 1) { // given > vec[k] start = edge + 1; } else { // given < vec[k] end = edge - 1; } } } else { // linear search if (edge != NO_EDGE && edge_occupied(edge)) { do { if ((unichar_id_from_edge_rec(edges_[edge]) == unichar_id) && (!word_end || end_of_word_from_edge_rec(edges_[edge]))) return (edge); } while (!last_edge(edge++)); } } return (NO_EDGE); // not found } inT32 SquishedDawg::num_forward_edges(NODE_REF node) const { EDGE_REF edge = node; inT32 num = 0; if (forward_edge (edge)) { do { num++; } while (!last_edge(edge++)); } return (num); } void SquishedDawg::print_node(NODE_REF node, int max_num_edges) const { if (node == NO_EDGE) return; // nothing to print EDGE_REF edge = node; const char *forward_string = "FORWARD"; const char *backward_string = " "; const char *last_string = "LAST"; const char *not_last_string = " "; const char *eow_string = "EOW"; const char *not_eow_string = " "; const char *direction; const char *is_last; const char *eow; UNICHAR_ID unichar_id; if (edge_occupied(edge)) { do { direction = forward_edge(edge) ? forward_string : backward_string; is_last = last_edge(edge) ? last_string : not_last_string; eow = end_of_word(edge) ? eow_string : not_eow_string; unichar_id = edge_letter(edge); tprintf(REFFORMAT " : next = " REFFORMAT ", unichar_id = %d, %s %s %s\n", edge, next_node(edge), unichar_id, direction, is_last, eow); if (edge - node > max_num_edges) return; } while (!last_edge(edge++)); if (edge < num_edges_ && edge_occupied(edge) && backward_edge(edge)) { do { direction = forward_edge(edge) ? forward_string : backward_string; is_last = last_edge(edge) ? last_string : not_last_string; eow = end_of_word(edge) ? eow_string : not_eow_string; unichar_id = edge_letter(edge); tprintf(REFFORMAT " : next = " REFFORMAT ", unichar_id = %d, %s %s %s\n", edge, next_node(edge), unichar_id, direction, is_last, eow); if (edge - node > MAX_NODE_EDGES_DISPLAY) return; } while (!last_edge(edge++)); } } else { tprintf(REFFORMAT " : no edges in this node\n", node); } tprintf("\n"); } void SquishedDawg::print_edge(EDGE_REF edge) const { if (edge == NO_EDGE) { tprintf("NO_EDGE\n"); } else { tprintf(REFFORMAT " : next = " REFFORMAT ", unichar_id = '%d', %s %s %s\n", edge, next_node(edge), edge_letter(edge), (forward_edge(edge) ? "FORWARD" : " "), (last_edge(edge) ? "LAST" : " "), (end_of_word(edge) ? "EOW" : "")); } } void SquishedDawg::read_squished_dawg(FILE *file, DawgType type, const STRING &lang, PermuterType perm, int debug_level) { if (debug_level) tprintf("Reading squished dawg\n"); // Read the magic number and if it does not match kDawgMagicNumber // set swap to true to indicate that we need to switch endianness. inT16 magic; fread(&magic, sizeof(inT16), 1, file); bool swap = (magic != kDawgMagicNumber); int unicharset_size; fread(&unicharset_size, sizeof(inT32), 1, file); fread(&num_edges_, sizeof(inT32), 1, file); if (swap) { ReverseN(&unicharset_size, sizeof(unicharset_size)); ReverseN(&num_edges_, sizeof(num_edges_)); } ASSERT_HOST(num_edges_ > 0); // DAWG should not be empty Dawg::init(type, lang, perm, unicharset_size, debug_level); edges_ = (EDGE_ARRAY) memalloc(sizeof(EDGE_RECORD) * num_edges_); fread(&edges_[0], sizeof(EDGE_RECORD), num_edges_, file); EDGE_REF edge; if (swap) { for (edge = 0; edge < num_edges_; ++edge) { ReverseN(&edges_[edge], sizeof(edges_[edge])); } } if (debug_level > 2) { tprintf("type: %d lang: %s perm: %d unicharset_size: %d num_edges: %d\n", type_, lang_.string(), perm_, unicharset_size_, num_edges_); for (edge = 0; edge < num_edges_; ++edge) print_edge(edge); } } NODE_MAP SquishedDawg::build_node_map(inT32 *num_nodes) const { EDGE_REF edge; NODE_MAP node_map; inT32 node_counter; inT32 num_edges; node_map = (NODE_MAP) malloc(sizeof(EDGE_REF) * num_edges_); for (edge = 0; edge < num_edges_; edge++) // init all slots node_map [edge] = -1; node_counter = num_forward_edges(0); *num_nodes = 0; for (edge = 0; edge < num_edges_; edge++) { // search all slots if (forward_edge(edge)) { (*num_nodes)++; // count nodes links node_map[edge] = (edge ? node_counter : 0); num_edges = num_forward_edges(edge); if (edge != 0) node_counter += num_edges; edge += num_edges; if (edge >= num_edges_) break; if (backward_edge(edge)) while (!last_edge(edge++)); edge--; } } return (node_map); } void SquishedDawg::write_squished_dawg(FILE *file) { EDGE_REF edge; inT32 num_edges; inT32 node_count = 0; NODE_MAP node_map; EDGE_REF old_index; EDGE_RECORD temp_record; if (debug_level_) tprintf("write_squished_dawg\n"); node_map = build_node_map(&node_count); // Write the magic number to help detecting a change in endianness. inT16 magic = kDawgMagicNumber; fwrite(&magic, sizeof(inT16), 1, file); fwrite(&unicharset_size_, sizeof(inT32), 1, file); // Count the number of edges in this Dawg. num_edges = 0; for (edge=0; edge < num_edges_; edge++) if (forward_edge(edge)) num_edges++; fwrite(&num_edges, sizeof(inT32), 1, file); // write edge count to file if (debug_level_) { tprintf("%d nodes in DAWG\n", node_count); tprintf("%d edges in DAWG\n", num_edges); } for (edge = 0; edge < num_edges_; edge++) { if (forward_edge(edge)) { // write forward edges do { old_index = next_node_from_edge_rec(edges_[edge]); set_next_node(edge, node_map[old_index]); temp_record = edges_[edge]; fwrite(&(temp_record), sizeof(EDGE_RECORD), 1, file); set_next_node(edge, old_index); } while (!last_edge(edge++)); if (edge >= num_edges_) break; if (backward_edge(edge)) // skip back links while (!last_edge(edge++)); edge--; } } free(node_map); } } // namespace tesseract
1080228-arabicocr11
dict/dawg.cpp
C
asf20
14,326
/////////////////////////////////////////////////////////////////////// // File: dict.h // Description: dict class. // 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 TESSERACT_DICT_DICT_H_ #define TESSERACT_DICT_DICT_H_ #include "ambigs.h" #include "dawg.h" #include "dawg_cache.h" #include "host.h" #include "oldlist.h" #include "ratngs.h" #include "stopper.h" #include "trie.h" #include "unicharset.h" #include "params_training_featdef.h" class MATRIX; class WERD_RES; #define MAX_WERD_LENGTH (inT64) 128 #define NO_RATING -1 /** Struct used to hold temporary information about fragments. */ struct CHAR_FRAGMENT_INFO { UNICHAR_ID unichar_id; const CHAR_FRAGMENT *fragment; int num_fragments; float rating; float certainty; }; namespace tesseract { typedef GenericVector<Dawg *> DawgVector; // // Constants // static const int kRatingPad = 4; static const char kDictWildcard[] = "\u2606"; // WHITE STAR static const int kDictMaxWildcards = 2; // max wildcards for a word // TODO(daria): If hyphens are different in different languages and can be // inferred from training data we should load their values dynamically. static const char kHyphenSymbol[] = "-"; static const char kSlashSymbol[] = "/"; static const char kQuestionSymbol[] = "?"; static const char kApostropheSymbol[] = "'"; static const float kSimCertaintyScale = -10.0; // similarity matcher scaling static const float kSimCertaintyOffset = -10.0; // similarity matcher offset static const float kSimilarityFloor = 100.0; // worst E*L product to stop on static const int kDocDictMaxRepChars = 4; // Enum for describing whether the x-height for the word is consistent: // 0 - everything is good. // 1 - there are one or two secondary (but consistent) baselines // [think subscript and superscript], or there is an oversized // first character. // 2 - the word is inconsistent. enum XHeightConsistencyEnum {XH_GOOD, XH_SUBNORMAL, XH_INCONSISTENT}; struct DawgArgs { DawgArgs(DawgPositionVector *d, DawgPositionVector *up, PermuterType p) : active_dawgs(d), updated_dawgs(up), permuter(p) {} DawgPositionVector *active_dawgs; DawgPositionVector *updated_dawgs; PermuterType permuter; }; class Dict { public: Dict(CCUtil* image_ptr); ~Dict(); const CCUtil* getCCUtil() const { return ccutil_; } CCUtil* getCCUtil() { return ccutil_; } const UNICHARSET& getUnicharset() const { return getCCUtil()->unicharset; } UNICHARSET& getUnicharset() { return getCCUtil()->unicharset; } const UnicharAmbigs &getUnicharAmbigs() const { return getCCUtil()->unichar_ambigs; } // Returns true if unichar_id is a word compounding character like - or /. inline bool compound_marker(UNICHAR_ID unichar_id) { const GenericVector<UNICHAR_ID>& normed_ids = getUnicharset().normed_ids(unichar_id); return normed_ids.size() == 1 && (normed_ids[0] == hyphen_unichar_id_ || normed_ids[0] == slash_unichar_id_); } // Returns true if unichar_id is an apostrophe-like character that may // separate prefix/suffix words from a main body word. inline bool is_apostrophe(UNICHAR_ID unichar_id) { const GenericVector<UNICHAR_ID>& normed_ids = getUnicharset().normed_ids(unichar_id); return normed_ids.size() == 1 && normed_ids[0] == apostrophe_unichar_id_; } /* hyphen.cpp ************************************************************/ /// Returns true if we've recorded the beginning of a hyphenated word. inline bool hyphenated() const { return !last_word_on_line_ && hyphen_word_; } /// Size of the base word (the part on the line before) of a hyphenated word. inline int hyphen_base_size() const { return this->hyphenated() ? hyphen_word_->length() : 0; } /// If this word is hyphenated copy the base word (the part on /// the line before) of a hyphenated word into the given word. /// This function assumes that word is not NULL. inline void copy_hyphen_info(WERD_CHOICE *word) const { if (this->hyphenated()) { *word = *hyphen_word_; if (hyphen_debug_level) word->print("copy_hyphen_info: "); } } /// Check whether the word has a hyphen at the end. inline bool has_hyphen_end(UNICHAR_ID unichar_id, bool first_pos) const { if (!last_word_on_line_ || first_pos) return false; const GenericVector<UNICHAR_ID>& normed_ids = getUnicharset().normed_ids(unichar_id); return normed_ids.size() == 1 && normed_ids[0] == hyphen_unichar_id_; } /// Same as above, but check the unichar at the end of the word. inline bool has_hyphen_end(const WERD_CHOICE &word) const { int word_index = word.length() - 1; return has_hyphen_end(word.unichar_id(word_index), word_index == 0); } /// Unless the previous word was the last one on the line, and the current /// one is not (thus it is the first one on the line), erase hyphen_word_, /// clear hyphen_active_dawgs_, update last_word_on_line_. void reset_hyphen_vars(bool last_word_on_line); /// Update hyphen_word_, and copy the given DawgPositionVectors into /// hyphen_active_dawgs_ . void set_hyphen_word(const WERD_CHOICE &word, const DawgPositionVector &active_dawgs); /* permdawg.cpp ************************************************************/ // Note: Functions in permdawg.cpp are only used by NoDangerousAmbig(). // When this function is refactored, permdawg.cpp can be removed. /// Copies word into best_choice if its rating is smaller /// than that of best_choice. inline void update_best_choice(const WERD_CHOICE &word, WERD_CHOICE *best_choice) { if (word.rating() < best_choice->rating()) { *best_choice = word; } } /// Fill the given active_dawgs vector with dawgs that could contain the /// beginning of the word. If hyphenated() returns true, copy the entries /// from hyphen_active_dawgs_ instead. void init_active_dawgs(DawgPositionVector *active_dawgs, bool ambigs_mode) const; // Fill the given vector with the default collection of any-length dawgs void default_dawgs(DawgPositionVector *anylength_dawgs, bool suppress_patterns) const; /// Recursively explore all the possible character combinations in /// the given char_choices. Use go_deeper_dawg_fxn() to explore all the /// dawgs in the dawgs_ vector in parallel and discard invalid words. /// /// Allocate and return a WERD_CHOICE with the best valid word found. WERD_CHOICE *dawg_permute_and_select( const BLOB_CHOICE_LIST_VECTOR &char_choices, float rating_limit); /// If the choice being composed so far could be a dictionary word /// and we have not reached the end of the word keep exploring the /// char_choices further. void go_deeper_dawg_fxn( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, bool word_ending, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *void_more_args); /// Pointer to go_deeper function. void (Dict::*go_deeper_fxn_)(const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, bool word_ending, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *void_more_args); // // Helper functions for dawg_permute_and_select(). // void permute_choices( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *more_args); void append_choices( const char *debug, const BLOB_CHOICE_LIST_VECTOR &char_choices, const BLOB_CHOICE &blob_choice, int char_choice_index, const CHAR_FRAGMENT_INFO *prev_char_frag_info, WERD_CHOICE *word, float certainties[], float *limit, WERD_CHOICE *best_choice, int *attempts_left, void *more_args); bool fragment_state_okay(UNICHAR_ID curr_unichar_id, float curr_rating, float curr_certainty, const CHAR_FRAGMENT_INFO *prev_char_frag_info, const char *debug, int word_ending, CHAR_FRAGMENT_INFO *char_frag_info); /* stopper.cpp *************************************************************/ bool NoDangerousAmbig(WERD_CHOICE *BestChoice, DANGERR *fixpt, bool fix_replaceable, MATRIX* ratings); // Replaces the corresponding wrong ngram in werd_choice with the correct // one. The whole correct n-gram is inserted into the ratings matrix and // the werd_choice: no more fragments!. Rating and certainty of new entries // in matrix and werd_choice are the sum and mean of the wrong ngram // respectively. // E.g. for werd_choice mystring'' and ambiguity ''->": werd_choice becomes // mystring", with a new entry in the ratings matrix for ". void ReplaceAmbig(int wrong_ngram_begin_index, int wrong_ngram_size, UNICHAR_ID correct_ngram_id, WERD_CHOICE *werd_choice, MATRIX *ratings); /// Returns the length of the shortest alpha run in WordChoice. int LengthOfShortestAlphaRun(const WERD_CHOICE &WordChoice); /// Returns true if the certainty of the BestChoice word is within a /// reasonable range of the average certainties for the best choices for /// each character in the segmentation. This test is used to catch words /// in which one character is much worse than the other characters in the /// word (i.e. false will be returned in that case). The algorithm computes /// the mean and std deviation of the certainties in the word with the worst /// certainty thrown out. int UniformCertainties(const WERD_CHOICE& word); /// Returns true if the given best_choice is good enough to stop. bool AcceptableChoice(const WERD_CHOICE& best_choice, XHeightConsistencyEnum xheight_consistency); /// Returns false if the best choice for the current word is questionable /// and should be tried again on the second pass or should be flagged to /// the user. bool AcceptableResult(WERD_RES* word); void EndDangerousAmbigs(); /// Prints the current choices for this word to stdout. void DebugWordChoices(); /// Sets up stopper variables in preparation for the first pass. void SettupStopperPass1(); /// Sets up stopper variables in preparation for the second pass. void SettupStopperPass2(); /* context.cpp *************************************************************/ /// Check a string to see if it matches a set of lexical rules. int case_ok(const WERD_CHOICE &word, const UNICHARSET &unicharset); /// Returns true if the word looks like an absolute garbage /// (e.g. image mistakenly recognized as text). bool absolute_garbage(const WERD_CHOICE &word, const UNICHARSET &unicharset); /* dict.cpp ****************************************************************/ /// Initialize Dict class - load dawgs from [lang].traineddata and /// user-specified wordlist and parttern list. static DawgCache *GlobalDawgCache(); void Load(DawgCache *dawg_cache); void End(); // Resets the document dictionary analogous to ResetAdaptiveClassifier. void ResetDocumentDictionary() { if (pending_words_ != NULL) pending_words_->clear(); if (document_words_ != NULL) document_words_->clear(); } /** * Returns the maximal permuter code (from ccstruct/ratngs.h) if in light * of the current state the letter at word_index in the given word * is allowed according to at least one of the dawgs in dawgs_, * otherwise returns NO_PERM. * * The state is described by void_dawg_args, which are interpreted as * DawgArgs and contain relevant active dawg positions. * Each entry in the active_dawgs vector contains an index * into the dawgs_ vector and an EDGE_REF that indicates the last edge * followed in the dawg. It also may contain a position in the punctuation * dawg which describes surrounding punctuation (see struct DawgPosition). * * Input: * At word_index 0 dawg_args->active_dawgs should contain an entry for each * dawg that may start at the beginning of a word, with punc_ref and edge_ref * initialized to NO_EDGE. Since the punctuation dawg includes the empty * pattern " " (meaning anything without surrounding punctuation), having a * single entry for the punctuation dawg will cover all dawgs reachable * therefrom -- that includes all number and word dawgs. The only dawg * non-reachable from the punctuation_dawg is the pattern dawg. * If hyphen state needs to be applied, initial dawg_args->active_dawgs can * be copied from the saved hyphen state (maintained by Dict). * For word_index > 0 the corresponding state (active_dawgs and punc position) * can be obtained from dawg_args->updated_dawgs passed to * def_letter_is_okay for word_index-1. * Note: the function assumes that active_dawgs, nd updated_dawgs * member variables of dawg_args are not NULL. * * Output: * The function fills in dawg_args->updated_dawgs vector with the * entries for dawgs that contain the word up to the letter at word_index. * */ // int def_letter_is_okay(void* void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const; int (Dict::*letter_is_okay_)(void* void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const; /// Calls letter_is_okay_ member function. int LetterIsOkay(void* void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const { return (this->*letter_is_okay_)(void_dawg_args, unichar_id, word_end); } /// Probability in context function used by the ngram permuter. double (Dict::*probability_in_context_)(const char* lang, const char* context, int context_bytes, const char* character, int character_bytes); /// Calls probability_in_context_ member function. double ProbabilityInContext(const char* context, int context_bytes, const char* character, int character_bytes) { return (this->*probability_in_context_)( getCCUtil()->lang.string(), context, context_bytes, character, character_bytes); } /// Default (no-op) implementation of probability in context function. double def_probability_in_context( const char* lang, const char* context, int context_bytes, const char* character, int character_bytes) { (void) context; (void) context_bytes; (void) character; (void) character_bytes; return 0.0; } double ngram_probability_in_context(const char* lang, const char* context, int context_bytes, const char* character, int character_bytes); // Interface with params model. float (Dict::*params_model_classify_)(const char *lang, void *path); float ParamsModelClassify(const char *lang, void *path); // Call params_model_classify_ member function. float CallParamsModelClassify(void *path) { ASSERT_HOST(params_model_classify_ != NULL); // ASSERT_HOST -> assert return (this->*params_model_classify_)( getCCUtil()->lang.string(), path); } inline void SetWildcardID(UNICHAR_ID id) { wildcard_unichar_id_ = id; } inline const UNICHAR_ID WildcardID() const { return wildcard_unichar_id_; } /// Return the number of dawgs in the dawgs_ vector. inline const int NumDawgs() const { return dawgs_.size(); } /// Return i-th dawg pointer recorded in the dawgs_ vector. inline const Dawg *GetDawg(int index) const { return dawgs_[index]; } /// Return the points to the punctuation dawg. inline const Dawg *GetPuncDawg() const { return punc_dawg_; } /// Return the points to the unambiguous words dawg. inline const Dawg *GetUnambigDawg() const { return unambig_dawg_; } /// Returns the appropriate next node given the EDGE_REF. static inline NODE_REF GetStartingNode(const Dawg *dawg, EDGE_REF edge_ref) { if (edge_ref == NO_EDGE) return 0; // beginning to explore the dawg NODE_REF node = dawg->next_node(edge_ref); if (node == 0) node = NO_EDGE; // end of word return node; } // Given a unichar from a string and a given dawg, return the unichar // we should use to match in that dawg type. (for example, in the number // dawg, all numbers are transformed to kPatternUnicharId). inline UNICHAR_ID char_for_dawg(UNICHAR_ID ch, const Dawg *dawg) const { if (!dawg) return ch; switch (dawg->type()) { case DAWG_TYPE_NUMBER: return getUnicharset().get_isdigit(ch) ? Dawg::kPatternUnicharID : ch; default: return ch; } } /// For each of the character classes of the given unichar_id (and the /// unichar_id itself) finds the corresponding outgoing node or self-loop /// in the given dawg and (after checking that it is valid) records it in /// dawg_args->updated_ative_dawgs. Updates current_permuter if any valid /// edges were found. void ProcessPatternEdges(const Dawg *dawg, const DawgPosition &info, UNICHAR_ID unichar_id, bool word_end, DawgPositionVector *updated_dawgs, PermuterType *current_permuter) const; /// Read/Write/Access special purpose dawgs which contain words /// only of a certain length (used for phrase search for /// non-space-delimited languages). /// Check all the DAWGs to see if this word is in any of them. inline static bool valid_word_permuter(uinT8 perm, bool numbers_ok) { return (perm == SYSTEM_DAWG_PERM || perm == FREQ_DAWG_PERM || perm == DOC_DAWG_PERM || perm == USER_DAWG_PERM || perm == USER_PATTERN_PERM || perm == COMPOUND_PERM || (numbers_ok && perm == NUMBER_PERM)); } int valid_word(const WERD_CHOICE &word, bool numbers_ok) const; int valid_word(const WERD_CHOICE &word) const { return valid_word(word, false); // return NO_PERM for words with digits } int valid_word_or_number(const WERD_CHOICE &word) const { return valid_word(word, true); // return NUMBER_PERM for valid numbers } /// This function is used by api/tesseract_cube_combiner.cpp int valid_word(const char *string) const { WERD_CHOICE word(string, getUnicharset()); return valid_word(word); } // Do the two WERD_CHOICEs form a meaningful bigram? bool valid_bigram(const WERD_CHOICE &word1, const WERD_CHOICE &word2) const; /// Returns true if the word contains a valid punctuation pattern. /// Note: Since the domains of punctuation symbols and symblos /// used in numbers are not disjoint, a valid number might contain /// an invalid punctuation pattern (e.g. .99). bool valid_punctuation(const WERD_CHOICE &word); /// Returns true if a good answer is found for the unknown blob rating. int good_choice(const WERD_CHOICE &choice); /// Adds a word found on this document to the document specific dictionary. void add_document_word(const WERD_CHOICE &best_choice); /// Adjusts the rating of the given word. void adjust_word(WERD_CHOICE *word, bool nonword, XHeightConsistencyEnum xheight_consistency, float additional_adjust, bool modify_rating, bool debug); /// Set wordseg_rating_adjust_factor_ to the given value. inline void SetWordsegRatingAdjustFactor(float f) { wordseg_rating_adjust_factor_ = f; } private: /** Private member variables. */ CCUtil* ccutil_; /** * Table that stores ambiguities computed during training * (loaded when NoDangerousAmbigs() is called for the first time). * Each entry i in the table stores a set of amibiguities whose * wrong ngram starts with unichar id i. */ UnicharAmbigs *dang_ambigs_table_; /** Same as above, but for ambiguities with replace flag set. */ UnicharAmbigs *replace_ambigs_table_; /** Additional certainty padding allowed before a word is rejected. */ FLOAT32 reject_offset_; // Cached UNICHAR_IDs: UNICHAR_ID wildcard_unichar_id_; // kDictWildcard. UNICHAR_ID apostrophe_unichar_id_; // kApostropheSymbol. UNICHAR_ID question_unichar_id_; // kQuestionSymbol. UNICHAR_ID slash_unichar_id_; // kSlashSymbol. UNICHAR_ID hyphen_unichar_id_; // kHyphenSymbol. // Hyphen-related variables. WERD_CHOICE *hyphen_word_; DawgPositionVector hyphen_active_dawgs_; bool last_word_on_line_; // List of lists of "equivalent" UNICHAR_IDs for the purposes of dictionary // matching. The first member of each list is taken as canonical. For // example, the first list contains hyphens and dashes with the first symbol // being the ASCII hyphen minus. GenericVector<GenericVectorEqEq<UNICHAR_ID> > equivalent_symbols_; // Dawg Cache reference - this is who we ask to allocate/deallocate dawgs. DawgCache *dawg_cache_; bool dawg_cache_is_ours_; // we should delete our own dawg_cache_ // Dawgs. DawgVector dawgs_; SuccessorListsVector successors_; Trie *pending_words_; // bigram_dawg_ points to a dawg of two-word bigrams which always supercede if // any of them are present on the best choices list for a word pair. // the bigrams are stored as space-separated words where: // (1) leading and trailing punctuation has been removed from each word and // (2) any digits have been replaced with '?' marks. Dawg *bigram_dawg_; /// The following pointers are only cached for convenience. /// The dawgs will be deleted when dawgs_ vector is destroyed. // TODO(daria): need to support multiple languages in the future, // so maybe will need to maintain a list of dawgs of each kind. Dawg *freq_dawg_; Dawg *unambig_dawg_; Dawg *punc_dawg_; Trie *document_words_; /// Current segmentation cost adjust factor for word rating. /// See comments in incorporate_segcost. float wordseg_rating_adjust_factor_; // File for recording ambiguities discovered during dictionary search. FILE *output_ambig_words_file_; public: /// Variable members. /// These have to be declared and initialized after image_ptr_, which contains /// the pointer to the params vector - the member of its base CCUtil class. STRING_VAR_H(user_words_file, "", "A filename of user-provided words."); STRING_VAR_H(user_words_suffix, "", "A suffix of user-provided words located in tessdata."); STRING_VAR_H(user_patterns_file, "", "A filename of user-provided patterns."); STRING_VAR_H(user_patterns_suffix, "", "A suffix of user-provided patterns located in tessdata."); BOOL_VAR_H(load_system_dawg, true, "Load system word dawg."); BOOL_VAR_H(load_freq_dawg, true, "Load frequent word dawg."); BOOL_VAR_H(load_unambig_dawg, true, "Load unambiguous word dawg."); BOOL_VAR_H(load_punc_dawg, true, "Load dawg with punctuation patterns."); BOOL_VAR_H(load_number_dawg, true, "Load dawg with number patterns."); BOOL_VAR_H(load_bigram_dawg, true, "Load dawg with special word bigrams."); double_VAR_H(xheight_penalty_subscripts, 0.125, "Score penalty (0.1 = 10%) added if there are subscripts " "or superscripts in a word, but it is otherwise OK."); double_VAR_H(xheight_penalty_inconsistent, 0.25, "Score penalty (0.1 = 10%) added if an xheight is " "inconsistent."); double_VAR_H(segment_penalty_dict_frequent_word, 1.0, "Score multiplier for word matches which have good case and" "are frequent in the given language (lower is better)."); double_VAR_H(segment_penalty_dict_case_ok, 1.1, "Score multiplier for word matches that have good case " "(lower is better)."); double_VAR_H(segment_penalty_dict_case_bad, 1.3125, "Default score multiplier for word matches, which may have " "case issues (lower is better)."); // TODO(daria): remove this param when ngram permuter is deprecated. double_VAR_H(segment_penalty_ngram_best_choice, 1.24, "Multipler to for the best choice from the ngram model."); double_VAR_H(segment_penalty_dict_nonword, 1.25, "Score multiplier for glyph fragment segmentations which " "do not match a dictionary word (lower is better)."); double_VAR_H(segment_penalty_garbage, 1.50, "Score multiplier for poorly cased strings that are not in" " the dictionary and generally look like garbage (lower is" " better)."); STRING_VAR_H(output_ambig_words_file, "", "Output file for ambiguities found in the dictionary"); INT_VAR_H(dawg_debug_level, 0, "Set to 1 for general debug info" ", to 2 for more details, to 3 to see all the debug messages"); INT_VAR_H(hyphen_debug_level, 0, "Debug level for hyphenated words."); INT_VAR_H(max_viterbi_list_size, 10, "Maximum size of viterbi list."); BOOL_VAR_H(use_only_first_uft8_step, false, "Use only the first UTF8 step of the given string" " when computing log probabilities."); double_VAR_H(certainty_scale, 20.0, "Certainty scaling factor"); double_VAR_H(stopper_nondict_certainty_base, -2.50, "Certainty threshold for non-dict words"); double_VAR_H(stopper_phase2_certainty_rejection_offset, 1.0, "Reject certainty offset"); INT_VAR_H(stopper_smallword_size, 2, "Size of dict word to be treated as non-dict word"); double_VAR_H(stopper_certainty_per_char, -0.50, "Certainty to add for each dict char above small word size."); double_VAR_H(stopper_allowable_character_badness, 3.0, "Max certaintly variation allowed in a word (in sigma)"); INT_VAR_H(stopper_debug_level, 0, "Stopper debug level"); BOOL_VAR_H(stopper_no_acceptable_choices, false, "Make AcceptableChoice() always return false. Useful" " when there is a need to explore all segmentations"); BOOL_VAR_H(save_raw_choices, false, "Deprecated- backward compatability only"); INT_VAR_H(tessedit_truncate_wordchoice_log, 10, "Max words to keep in list"); STRING_VAR_H(word_to_debug, "", "Word for which stopper debug information" " should be printed to stdout"); STRING_VAR_H(word_to_debug_lengths, "", "Lengths of unichars in word_to_debug"); INT_VAR_H(fragments_debug, 0, "Debug character fragments"); BOOL_VAR_H(segment_nonalphabetic_script, false, "Don't use any alphabetic-specific tricks." "Set to true in the traineddata config file for" " scripts that are cursive or inherently fixed-pitch"); BOOL_VAR_H(save_doc_words, 0, "Save Document Words"); double_VAR_H(doc_dict_pending_threshold, 0.0, "Worst certainty for using pending dictionary"); double_VAR_H(doc_dict_certainty_threshold, -2.25, "Worst certainty" " for words that can be inserted into the document dictionary"); INT_VAR_H(max_permuter_attempts, 10000, "Maximum number of different" " character choices to consider during permutation." " This limit is especially useful when user patterns" " are specified, since overly generic patterns can result in" " dawg search exploring an overly large number of options."); }; } // namespace tesseract #endif // THIRD_PARTY_TESSERACT_DICT_DICT_H_
1080228-arabicocr11
dict/dict.h
C++
asf20
29,187
/////////////////////////////////////////////////////////////////////// // File: dawg_cache.h // Description: A class that knows about loading and caching dawgs. // Author: David Eger // Created: Fri Jan 27 12:08:00 PST 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_DICT_DAWG_CACHE_H_ #define TESSERACT_DICT_DAWG_CACHE_H_ #include "dawg.h" #include "object_cache.h" #include "strngs.h" #include "tessdatamanager.h" namespace tesseract { class DawgCache { public: Dawg *GetSquishedDawg( const STRING &lang, const char *data_file_name, TessdataType tessdata_dawg_type, int debug_level); // If we manage the given dawg, decrement its count, // and possibly delete it if the count reaches zero. // If dawg is unknown to us, return false. bool FreeDawg(Dawg *dawg) { return dawgs_.Free(dawg); } // Free up any currently unused dawgs. void DeleteUnusedDawgs() { dawgs_.DeleteUnusedObjects(); } private: ObjectCache<Dawg> dawgs_; }; } // namespace tesseract #endif // TESSERACT_DICT_DAWG_CACHE_H_
1080228-arabicocr11
dict/dawg_cache.h
C++
asf20
1,706
SUBDIRS = com scrollview_path = @datadir@/tessdata JAVAC = javac JAR = jar if !GRAPHICS_DISABLED SCROLLVIEW_FILES = \ $(srcdir)/com/google/scrollview/ui/SVAbstractMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVCheckboxMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVEmptyMenuItem.java \ $(srcdir)/com/google/scrollview/events/SVEvent.java \ $(srcdir)/com/google/scrollview/events/SVEventHandler.java \ $(srcdir)/com/google/scrollview/events/SVEventType.java \ $(srcdir)/com/google/scrollview/ui/SVImageHandler.java \ $(srcdir)/com/google/scrollview/ui/SVMenuBar.java \ $(srcdir)/com/google/scrollview/ui/SVMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVPopupMenu.java \ $(srcdir)/com/google/scrollview/ui/SVSubMenuItem.java \ $(srcdir)/com/google/scrollview/ui/SVWindow.java \ $(srcdir)/com/google/scrollview/ScrollView.java SCROLLVIEW_CLASSES = \ com/google/scrollview/ui/SVAbstractMenuItem.class \ com/google/scrollview/ui/SVCheckboxMenuItem.class \ com/google/scrollview/ui/SVEmptyMenuItem.class \ com/google/scrollview/events/SVEvent.class \ com/google/scrollview/events/SVEventHandler.class \ com/google/scrollview/events/SVEventType.class \ com/google/scrollview/ui/SVImageHandler.class \ com/google/scrollview/ui/SVMenuBar.class \ com/google/scrollview/ui/SVMenuItem.class \ com/google/scrollview/ui/SVPopupMenu.class \ com/google/scrollview/ui/SVSubMenuItem.class \ com/google/scrollview/ui/SVWindow.class \ com/google/scrollview/ScrollView.class SCROLLVIEW_LIBS = \ $(srcdir)/piccolo2d-core-3.0.jar \ $(srcdir)/piccolo2d-extras-3.0.jar CLASSPATH = $(srcdir)/piccolo2d-core-3.0.jar:$(srcdir)/piccolo2d-extras-3.0.jar ScrollView.jar : $(SCROLLVIEW_CLASSES) $(JAR) cf $@ com/google/scrollview/*.class \ com/google/scrollview/events/*.class com/google/scrollview/ui/*.class $(SCROLLVIEW_CLASSES) : $(SCROLLVIEW_FILES) $(JAVAC) -encoding UTF8 -sourcepath $(srcdir) -classpath $(CLASSPATH) $(SCROLLVIEW_FILES) -d $(builddir) .PHONY: install-jars install-jars : ScrollView.jar @if [ ! -d $(scrollview_path) ]; then mkdir -p $(scrollview_path); fi; $(INSTALL) -m 644 $(SCROLLVIEW_LIBS) $(scrollview_path); $(INSTALL) -m 644 ScrollView.jar $(scrollview_path); @echo "Don't forget to set eviroment variable SCROLLVIEW_PATH to $(scrollview_path)"; uninstall: rm -f $(scrollview_path)/*.jar endif clean : rm -f ScrollView.jar *.class $(srcdir)/*.class # all-am does nothing, to make the java part optional. all all-am install :
1080228-arabicocr11
java/Makefile.am
Makefile
asf20
2,501
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview; import com.google.scrollview.events.SVEvent; import com.google.scrollview.ui.SVImageHandler; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.regex.Pattern; /** * The ScrollView class is the main class which gets started from the command * line. It sets up LUA and handles the network processing. * @author wanke@google.com */ public class ScrollView { /** The port our server listens at. */ public static int SERVER_PORT = 8461; /** * All SVWindow objects share the same connection stream. The socket is needed * to detect when the connection got closed, in/out are used to send and * receive messages. */ private static Socket socket; private static PrintStream out; public static BufferedReader in; public static float polylineXCoords[]; // The coords being received. public static float polylineYCoords[]; // The coords being received. public static int polylineSize; // The size of the coords arrays. public static int polylineScanned; // The size read so far. private static ArrayList<SVWindow> windows; // The id to SVWindow map. private static Pattern intPattern; // For checking integer arguments. private static Pattern floatPattern; // For checking float arguments. /** Keeps track of the number of messages received. */ static int nrInputLines = 0; /** Prints all received messages to the console if true. */ static boolean debugViewNetworkTraffic = false; /** Add a new message to the outgoing queue */ public static void addMessage(SVEvent e) { if (debugViewNetworkTraffic) { System.out.println("(S->c) " + e.toString()); } String str = e.toString(); // Send the whole thing as UTF8. try { byte [] utf8 = str.getBytes("UTF8"); out.write(utf8, 0, utf8.length); } catch (java.io.UnsupportedEncodingException ex) { System.out.println("Oops... can't encode to UTF8... Exiting"); System.exit(0); } out.println(); // Flush the output and check for errors. boolean error = out.checkError(); if (error) { System.out.println("Connection error. Quitting ScrollView Server..."); System.exit(0); } } /** Read one message from client (assuming there are any). */ public static String receiveMessage() throws IOException { return in.readLine(); } /** * The main program loop. Basically loops trough receiving messages and * processing them and then sending messages (if there are any). */ private static void IOLoop() { String inputLine; try { while (!socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown() && socket.isConnected() && socket.isBound()) { inputLine = receiveMessage(); nrInputLines++; if (debugViewNetworkTraffic) { System.out.println("(c->S," + nrInputLines + ")" + inputLine); } if (polylineSize > polylineScanned) { // We are processing a polyline. // Read pairs of coordinates separated by commas. boolean first = true; for (String coordStr : inputLine.split(",")) { int coord = Integer.parseInt(coordStr); if (first) { polylineXCoords[polylineScanned] = coord; } else { polylineYCoords[polylineScanned++] = coord; } first = !first; } assert first; } else { // Process this normally. processInput(inputLine); } } } // Some connection error catch (IOException e) { System.out.println("Connection error. Quitting ScrollView Server..."); } System.exit(0); } // Parse a comma-separated list of arguments into ArrayLists of the // possible types. Each type is stored in order, but the order // distinction between types is lost. // Note that the format is highly constrained to what the client used // to send to LUA: // Quoted string -> String. // true or false -> Boolean. // %f format number -> Float (no %e allowed) // Sequence of digits -> Integer // Nothing else allowed. private static void parseArguments(String argList, ArrayList<Integer> intList, ArrayList<Float> floatList, ArrayList<String> stringList, ArrayList<Boolean> boolList) { // str is only non-null if an argument starts with a single or double // quote. str is set back to null on completion of the string with a // matching quote. If the string contains a comma then str will stay // non-null across multiple argStr values until a matching closing quote. // Backslash escaped quotes do not count as terminating the string. String str = null; for (String argStr : argList.split(",")) { if (str != null) { // Last string was incomplete. Append argStr to it and restore comma. // Execute str += "," + argStr in Java. int length = str.length() + 1 + argStr.length(); StringBuilder appended = new StringBuilder(length); appended.append(str); appended.append(","); appended.append(argStr); str = appended.toString(); } else if (argStr.length() == 0) { continue; } else { char quote = argStr.charAt(0); // If it begins with a quote then it is a string, but may not // end this time if it contained a comma. if (quote == '\'' || quote == '"') { str = argStr; } } if (str != null) { // It began with a quote. Check that it still does. assert str.charAt(0) == '\'' || str.charAt(0) == '"'; int len = str.length(); if (len > 1 && str.charAt(len - 1) == str.charAt(0)) { // We have an ending quote of the right type. Now check that // it is not escaped. Must have an even number of slashes before. int slash = len - 1; while (slash > 0 && str.charAt(slash - 1) == '\\') --slash; if ((len - 1 - slash) % 2 == 0) { // It is now complete. Chop off the quotes and save. // TODO(rays) remove the first backslash of each pair. stringList.add(str.substring(1, len - 1)); str = null; } } // If str is not null here, then we have a string with a comma in it. // Append , and the next argument at the next iteration, but check // that str is null after the loop terminates in case it was an // unterminated string. } else if (floatPattern.matcher(argStr).matches()) { // It is a float. floatList.add(Float.parseFloat(argStr)); } else if (argStr.equals("true")) { boolList.add(true); } else if (argStr.equals("false")) { boolList.add(false); } else if (intPattern.matcher(argStr).matches()) { // Only contains digits so must be an int. intList.add(Integer.parseInt(argStr)); } // else ignore all incompatible arguments for forward compatibility. } // All strings must have been terminated. assert str == null; } /** Executes the LUA command parsed as parameter. */ private static void processInput(String inputLine) { if (inputLine == null) { return; } // Execute a function encoded as a LUA statement! Yuk! if (inputLine.charAt(0) == 'w') { // This is a method call on a window. Parse it. String noWLine = inputLine.substring(1); String[] idStrs = noWLine.split("[ :]", 2); int windowID = Integer.parseInt(idStrs[0]); // Find the parentheses. int start = inputLine.indexOf('('); int end = inputLine.lastIndexOf(')'); // Parse the args. ArrayList<Integer> intList = new ArrayList<Integer>(4); ArrayList<Float> floatList = new ArrayList<Float>(2); ArrayList<String> stringList = new ArrayList<String>(4); ArrayList<Boolean> boolList = new ArrayList<Boolean>(3); parseArguments(inputLine.substring(start + 1, end), intList, floatList, stringList, boolList); int colon = inputLine.indexOf(':'); if (colon > 1 && colon < start) { // This is a regular function call. Look for the name and call it. String func = inputLine.substring(colon + 1, start); if (func.equals("drawLine")) { windows.get(windowID).drawLine(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("createPolyline")) { windows.get(windowID).createPolyline(intList.get(0)); } else if (func.equals("drawPolyline")) { windows.get(windowID).drawPolyline(); } else if (func.equals("drawRectangle")) { windows.get(windowID).drawRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("setVisible")) { windows.get(windowID).setVisible(boolList.get(0)); } else if (func.equals("setAlwaysOnTop")) { windows.get(windowID).setAlwaysOnTop(boolList.get(0)); } else if (func.equals("addMessage")) { windows.get(windowID).addMessage(stringList.get(0)); } else if (func.equals("addMessageBox")) { windows.get(windowID).addMessageBox(); } else if (func.equals("clear")) { windows.get(windowID).clear(); } else if (func.equals("setStrokeWidth")) { windows.get(windowID).setStrokeWidth(floatList.get(0)); } else if (func.equals("drawEllipse")) { windows.get(windowID).drawEllipse(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("pen")) { if (intList.size() == 4) { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).pen(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("brush")) { if (intList.size() == 4) { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else { windows.get(windowID).brush(intList.get(0), intList.get(1), intList.get(2)); } } else if (func.equals("textAttributes")) { windows.get(windowID).textAttributes(stringList.get(0), intList.get(0), boolList.get(0), boolList.get(1), boolList.get(2)); } else if (func.equals("drawText")) { windows.get(windowID).drawText(intList.get(0), intList.get(1), stringList.get(0)); } else if (func.equals("addMenuBarItem")) { if (boolList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0), boolList.get(0)); } else if (intList.size() > 0) { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1), intList.get(0)); } else { windows.get(windowID).addMenuBarItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("addPopupMenuItem")) { if (stringList.size() == 4) { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1), intList.get(0), stringList.get(2), stringList.get(3)); } else { windows.get(windowID).addPopupMenuItem(stringList.get(0), stringList.get(1)); } } else if (func.equals("update")) { windows.get(windowID).update(); } else if (func.equals("showInputDialog")) { windows.get(windowID).showInputDialog(stringList.get(0)); } else if (func.equals("showYesNoDialog")) { windows.get(windowID).showYesNoDialog(stringList.get(0)); } else if (func.equals("zoomRectangle")) { windows.get(windowID).zoomRectangle(intList.get(0), intList.get(1), intList.get(2), intList.get(3)); } else if (func.equals("readImage")) { PImage image = SVImageHandler.readImage(intList.get(2), in); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("drawImage")) { PImage image = new PImage(stringList.get(0)); windows.get(windowID).drawImage(image, intList.get(0), intList.get(1)); } else if (func.equals("destroy")) { windows.get(windowID).destroy(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } else { // No colon. Check for create window. if (idStrs[1].startsWith("= luajava.newInstance")) { while (windows.size() <= windowID) { windows.add(null); } windows.set(windowID, new SVWindow(stringList.get(1), intList.get(0), intList.get(1), intList.get(2), intList.get(3), intList.get(4), intList.get(5), intList.get(6))); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } } else if (inputLine.startsWith("svmain")) { // Startup or end. Startup is a lua bind, which is now a no-op. if (inputLine.startsWith("svmain:exit")) { exit(); } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } // else for forward compatibility purposes, silently ignore any // unrecognized function call. } /** Called from the client to make the server exit. */ public static void exit() { System.exit(0); } /** * The main function. Sets up LUA and the server connection and then calls the * IOLoop. */ public static void main(String[] args) { if (args.length > 0) { SERVER_PORT = Integer.parseInt(args[0]); } windows = new ArrayList<SVWindow>(100); intPattern = Pattern.compile("[0-9-][0-9]*"); floatPattern = Pattern.compile("[0-9-][0-9]*\\.[0-9]*"); try { // Open a socket to listen on. ServerSocket serverSocket = new ServerSocket(SERVER_PORT); System.out.println("Socket started on port " + SERVER_PORT); // Wait (blocking) for an incoming connection socket = serverSocket.accept(); System.out.println("Client connected"); // Setup the streams out = new PrintStream(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8")); } catch (IOException e) { // Something went wrong and we were unable to set up a connection. This is // pretty // much a fatal error. // Note: The server does not get restarted automatically if this happens. e.printStackTrace(); System.exit(1); } // Enter the main program loop. IOLoop(); } }
1080228-arabicocr11
java/com/google/scrollview/ScrollView.java
Java
asf20
17,077
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.events; /** * These are the defined events which can happen in ScrollView and be * transferred to the client. They are same events as on the client side part of * ScrollView (defined in ScrollView.h). * * @author wanke@google.com */ public enum SVEventType { SVET_DESTROY, // Window has been destroyed by user. SVET_EXIT, // User has destroyed the last window by clicking on the 'X' SVET_CLICK, // Any button pressed thats not a popup trigger. SVET_SELECTION, // Left button selection. SVET_INPUT, // Any kind of input SVET_MOUSE, // The mouse has moved with a button pressed. SVET_MOTION, // The mouse has moved with no button pressed. SVET_HOVER, // The mouse has stayed still for a second. SVET_POPUP, // A command selected through a popup menu SVET_MENU; // A command selected through the menubar }
1080228-arabicocr11
java/com/google/scrollview/events/SVEventType.java
Java
asf20
1,457
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.events; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import org.piccolo2d.PCamera; import org.piccolo2d.PNode; import org.piccolo2d.event.PBasicInputEventHandler; import org.piccolo2d.event.PInputEvent; import org.piccolo2d.nodes.PPath; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.Timer; /** * The ScrollViewEventHandler takes care of any events which might happen on the * canvas and converts them to an according SVEvent, which is (using the * processEvent method) then added to a message queue. All events from the * message queue get sent gradually * * @author wanke@google.com */ public class SVEventHandler extends PBasicInputEventHandler implements ActionListener, KeyListener, WindowListener { /** Necessary to wait for a defined period of time (for SVET_HOVER). */ public Timer timer; /** The window which the event corresponds to. */ private SVWindow svWindow; /** These are used to determine a selection size (for SVET_SELECTION). */ private int lastX = 0; private int lastY = 0; /** * These are used in case we want to transmit our position, but do not get it * because it was no MouseEvent, in particular SVET_HOVER and SVET_INPUT. */ private int lastXMove = 0; private int lastYMove = 0; /** For Drawing a rubber-band rectangle for selection */ private int startX = 0; private int startY = 0; private float rubberBandTransparency = 0.5f; private PNode selection = null; /** The string entered since the last enter. Since the client * end eats all newlines, we can't use the newline * character, so use ! for now, as it cannot be entered * directly anyway and therefore can never show up for real. */ private String keyStr = "!"; /** Setup the timer. */ public SVEventHandler(SVWindow wdw) { timer = new Timer(1000, this); svWindow = wdw; } /** * Store the newest x,y values, add the message to the queue and restart the * timer. */ private void processEvent(SVEvent e) { lastXMove = e.x; lastYMove = e.y; ScrollView.addMessage(e); timer.restart(); } /** Show the associated popup menu at (x,y) (relative position of the window). */ private void showPopup(PInputEvent e) { double x = e.getCanvasPosition().getX(); double y = e.getCanvasPosition().getY(); if (svWindow.svPuMenu != null) { svWindow.svPuMenu.show(svWindow, (int) x, (int) y); } } /** The mouse is clicked - create an SVET_CLICK event. */ @Override public void mouseClicked(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_CLICK, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } } /** * The mouse key is pressed (and keeps getting pressed). * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise save the * position (in case it is a selection). */ @Override public void mousePressed(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { lastX = (int) e.getPosition().getX(); lastY = (int) e.getPosition().getY(); timer.restart(); } } /** The mouse is getting dragged - create an SVET_MOUSE event. */ @Override public void mouseDragged(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOUSE, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); // Paint a selection rectangle. if (selection == null) { startX = (int) e.getPosition().getX(); startY = (int) e.getPosition().getY(); selection = PPath.createRectangle(startX, startY, 1, 1); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } else { int right = Math.max(startX, (int) e.getPosition().getX()); int left = Math.min(startX, (int) e.getPosition().getX()); int bottom = Math.max(startY, (int) e.getPosition().getY()); int top = Math.min(startY, (int) e.getPosition().getY()); svWindow.canvas.getLayer().removeChild(selection); selection = PPath.createRectangle(left, top, right - left, bottom - top); selection.setPaint(Color.YELLOW); selection.setTransparency(rubberBandTransparency); svWindow.canvas.getLayer().addChild(selection); } } /** * The mouse was released. * Depending on the OS, show a popup menu (if the button pressed is associated * with popup menus, like the RMB under windows&linux) or otherwise create an * SVET_SELECTION event. */ @Override public void mouseReleased(PInputEvent e) { if (e.isPopupTrigger()) { showPopup(e); } else { processEvent(new SVEvent(SVEventType.SVET_SELECTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), (int) e .getPosition().getX() - lastX, (int) e.getPosition().getY() - lastY, null)); } if (selection != null) { svWindow.canvas.getLayer().removeChild(selection); selection = null; } } /** * The mouse wheel is used to zoom in and out of the viewport and center on * the (x,y) position the mouse is currently on. */ @Override public void mouseWheelRotated(PInputEvent e) { PCamera lc = svWindow.canvas.getCamera(); double sf = SVWindow.SCALING_FACTOR; if (e.getWheelRotation() < 0) { sf = 1 / sf; } lc.scaleViewAboutPoint(lc.getScale() / sf, e.getPosition().getX(), e .getPosition().getY()); } /** * The mouse was moved - create an SVET_MOTION event. NOTE: This obviously * creates a lot of traffic and, depending on the type of application, could * quite possibly be disabled. */ @Override public void mouseMoved(PInputEvent e) { processEvent(new SVEvent(SVEventType.SVET_MOTION, svWindow, (int) e .getPosition().getX(), (int) e.getPosition().getY(), 0, 0, null)); } /** * The mouse entered the window. * Start the timer, which will then emit SVET_HOVER events every X ms. */ @Override public void mouseEntered(PInputEvent e) { timer.restart(); } /** * The mouse exited the window * Stop the timer, so no more SVET_HOVER events will emit. */ @Override public void mouseExited(PInputEvent e) { timer.stop(); } /** * The only associated object with this is the timer, so we use it to send a * SVET_HOVER event. */ public void actionPerformed(ActionEvent e) { processEvent(new SVEvent(SVEventType.SVET_HOVER, svWindow, lastXMove, lastYMove, 0, 0, null)); } /** * A key was pressed - create an SVET_INPUT event. * * NOTE: Might be useful to specify hotkeys. * * Implementation note: The keyListener provided by Piccolo seems to be * broken, so we use the AWT listener directly. * There are never any keyTyped events received either so we are * stuck with physical keys, which is very ugly. */ public void keyPressed(KeyEvent e) { char keyCh = e.getKeyChar(); if (keyCh == '\r' || keyCh == '\n' || keyCh == '\0' || keyCh == '?') { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, keyStr)); // Send newline characters as '!' as '!' can never be a keypressed // and the client eats all newline characters. keyStr = "!"; } else { processEvent(new SVEvent(SVEventType.SVET_INPUT, svWindow, lastXMove, lastYMove, 0, 0, String.valueOf(keyCh))); keyStr += keyCh; } } /** * A window is closed (by the 'x') - create an SVET_DESTROY event. If it was * the last open Window, also send an SVET_EXIT event (but do not exit unless * the client says so). */ public void windowClosing(WindowEvent e) { processEvent(new SVEvent(SVEventType.SVET_DESTROY, svWindow, lastXMove, lastYMove, 0, 0, null)); e.getWindow().dispose(); SVWindow.nrWindows--; if (SVWindow.nrWindows == 0) { processEvent(new SVEvent(SVEventType.SVET_EXIT, svWindow, lastXMove, lastYMove, 0, 0, null)); } } /** These are all events we do not care about and throw away */ public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } }
1080228-arabicocr11
java/com/google/scrollview/events/SVEventHandler.java
Java
asf20
9,751
SUBDIRS = EXTRA_DIST = \ SVEvent.java SVEventHandler.java \ SVEventType.java
1080228-arabicocr11
java/com/google/scrollview/events/Makefile.am
Makefile
asf20
86
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.events; import com.google.scrollview.ui.SVWindow; /** * The SVEvent is a structure which holds the actual values of a message to be * transmitted. It corresponds to the client structure defined in scrollview.h * * @author wanke@google.com */ public class SVEvent { SVEventType type; // What kind of event. SVWindow window; // Window event relates to. int x; // Coords of click or selection. int y; int xSize; // Size of selection. int ySize; int commandId; String parameter; // Any string that might have been passed as argument. /** * A "normal" SVEvent. * * @param t The type of the event as specified in SVEventType (e.g. * SVET_CLICK) * @param w The window the event corresponds to * @param x1 X position of the mouse at the time of the event * @param y1 Y position of the mouse at the time of the event * @param x2 X selection size at the time of the event * @param y2 Y selection size at the time of the event * @param p A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType t, SVWindow w, int x1, int y1, int x2, int y2, String p) { type = t; window = w; x = x1; y = y1; xSize = x2; ySize = y2; commandId = 0; parameter = p; } /** * An event which issues a command (like clicking on a item in the menubar). * * @param eventtype The type of the event as specified in SVEventType * (usually SVET_MENU or SVET_POPUP) * @param svWindow The window the event corresponds to * @param commandid The associated id with the command (given by the client * on construction of the item) * @param value A parameter associated with the event (e.g. keyboard input) */ public SVEvent(SVEventType eventtype, SVWindow svWindow, int commandid, String value) { type = eventtype; window = svWindow; parameter = value; x = 0; y = 0; xSize = 0; ySize = 0; commandId = commandid; } /** * This is the string representation of the message, which is what will * actually be transferred over the network. */ @Override public String toString() { return (window.hash + "," + type.ordinal() + "," + x + "," + y + "," + xSize + "," + ySize + "," + commandId + "," + parameter); } }
1080228-arabicocr11
java/com/google/scrollview/events/SVEvent.java
Java
asf20
2,949
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventHandler; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuBar; import com.google.scrollview.ui.SVPopupMenu; import org.piccolo2d.PCamera; import org.piccolo2d.PCanvas; import org.piccolo2d.PLayer; import org.piccolo2d.extras.swing.PScrollPane; import org.piccolo2d.nodes.PImage; import org.piccolo2d.nodes.PPath; import org.piccolo2d.nodes.PText; import org.piccolo2d.util.PPaintContext; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.TextArea; import java.awt.geom.IllegalPathStateException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; /** * The SVWindow is the top-level ui class. It should get instantiated whenever * the user intends to create a new window. It contains helper functions to draw * on the canvas, add new menu items, show modal dialogs etc. * * @author wanke@google.com */ public class SVWindow extends JFrame { /** * Constants defining the maximum initial size of the window. */ private static final int MAX_WINDOW_X = 1000; private static final int MAX_WINDOW_Y = 800; /* Constant defining the (approx) height of the default message box*/ private static final int DEF_MESSAGEBOX_HEIGHT = 200; /** Constant defining the "speed" at which to zoom in and out. */ public static final double SCALING_FACTOR = 2; /** The top level layer we add our PNodes to (root node). */ PLayer layer; /** The current color of the pen. It is used to draw edges, text, etc. */ Color currentPenColor; /** * The current color of the brush. It is used to draw the interior of * primitives. */ Color currentBrushColor; /** The system name of the current font we are using (e.g. * "Times New Roman"). */ Font currentFont; /** The stroke width to be used. */ // This really needs to be a fixed width stroke as the basic stroke is // anti-aliased and gets too faint, but the piccolo fixed width stroke // is too buggy and generates missing initial moveto in path definition // errors with a IllegalPathStateException that cannot be caught because // it is in the automatic repaint function. If we can fix the exceptions // in piccolo, then we can use the following instead of BasicStroke: // import edu.umd.cs.piccolox.util.PFixedWidthStroke; // PFixedWidthStroke stroke = new PFixedWidthStroke(0.5f); // Instead we use the BasicStroke and turn off anti-aliasing. BasicStroke stroke = new BasicStroke(0.5f); /** * A unique representation for the window, also known by the client. It is * used when sending messages from server to client to identify him. */ public int hash; /** * The total number of created Windows. If this ever reaches 0 (apart from the * beginning), quit the server. */ public static int nrWindows = 0; /** * The Canvas, MessageBox, EventHandler, Menubar and Popupmenu associated with * this window. */ private SVEventHandler svEventHandler = null; private SVMenuBar svMenuBar = null; private TextArea ta = null; public SVPopupMenu svPuMenu = null; public PCanvas canvas; private int winSizeX; private int winSizeY; /** Set the brush to an RGB color */ public void brush(int red, int green, int blue) { brush(red, green, blue, 255); } /** Set the brush to an RGBA color */ public void brush(int red, int green, int blue, int alpha) { // If alpha is zero, use a null brush to save rendering time. if (alpha == 0) { currentBrushColor = null; } else { currentBrushColor = new Color(red, green, blue, alpha); } } /** Erase all content from the window, but do not destroy it. */ public void clear() { // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // removeAllChildren() from that thread and releases the latch. final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); SwingUtilities.invokeLater(new Runnable() { public void run() { layer.removeAllChildren(); repaint(); latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { } } /** * Start setting up a new polyline. The server will now expect * polyline data until the polyline is complete. * * @param length number of coordinate pairs */ public void createPolyline(int length) { ScrollView.polylineXCoords = new float[length]; ScrollView.polylineYCoords = new float[length]; ScrollView.polylineSize = length; ScrollView.polylineScanned = 0; } /** * Draw the now complete polyline. */ public void drawPolyline() { int numCoords = ScrollView.polylineXCoords.length; if (numCoords < 2) { return; } PPath pn = PPath.createLine(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0], ScrollView.polylineXCoords[1], ScrollView.polylineYCoords[1]); pn.reset(); pn.moveTo(ScrollView.polylineXCoords[0], ScrollView.polylineYCoords[0]); for (int p = 1; p < numCoords; ++p) { pn.lineTo(ScrollView.polylineXCoords[p], ScrollView.polylineYCoords[p]); } pn.closePath(); ScrollView.polylineSize = 0; pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Don't fill the polygon - this is just a polyline. pn.setStroke(stroke); layer.addChild(pn); } /** * Construct a new SVWindow and set it visible. * * @param name Title of the window. * @param hash Unique internal representation. This has to be the same as * defined by the client, as they use this to refer to the windows. * @param posX X position of where to draw the window (upper left). * @param posY Y position of where to draw the window (upper left). * @param sizeX The width of the window. * @param sizeY The height of the window. * @param canvasSizeX The canvas width of the window. * @param canvasSizeY The canvas height of the window. */ public SVWindow(String name, int hash, int posX, int posY, int sizeX, int sizeY, int canvasSizeX, int canvasSizeY) { super(name); // Provide defaults for sizes. if (sizeX == 0) sizeX = canvasSizeX; if (sizeY == 0) sizeY = canvasSizeY; if (canvasSizeX == 0) canvasSizeX = sizeX; if (canvasSizeY == 0) canvasSizeY = sizeY; // Initialize variables nrWindows++; this.hash = hash; this.svEventHandler = new SVEventHandler(this); this.currentPenColor = Color.BLACK; this.currentBrushColor = Color.BLACK; this.currentFont = new Font("Times New Roman", Font.PLAIN, 12); // Determine the initial size and zoom factor of the window. // If the window is too big, rescale it and zoom out. int shrinkfactor = 1; if (sizeX > MAX_WINDOW_X) { shrinkfactor = (sizeX + MAX_WINDOW_X - 1) / MAX_WINDOW_X; } if (sizeY / shrinkfactor > MAX_WINDOW_Y) { shrinkfactor = (sizeY + MAX_WINDOW_Y - 1) / MAX_WINDOW_Y; } winSizeX = sizeX / shrinkfactor; winSizeY = sizeY / shrinkfactor; double initialScalingfactor = 1.0 / shrinkfactor; if (winSizeX > canvasSizeX || winSizeY > canvasSizeY) { initialScalingfactor = Math.min(1.0 * winSizeX / canvasSizeX, 1.0 * winSizeY / canvasSizeY); } // Setup the actual window (its size, camera, title, etc.) if (canvas == null) { canvas = new PCanvas(); getContentPane().add(canvas, BorderLayout.CENTER); } layer = canvas.getLayer(); canvas.setBackground(Color.BLACK); // Disable anitaliasing to make the lines more visible. canvas.setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); validate(); canvas.requestFocus(); // Manipulation of Piccolo's scene graph should be done from Swings // event dispatch thread since Piccolo is not thread safe. This code calls // initialize() from that thread once the PFrame is initialized, so you are // safe to start working with Piccolo in the initialize() method. SwingUtilities.invokeLater(new Runnable() { public void run() { repaint(); } }); setSize(winSizeX, winSizeY); setLocation(posX, posY); setTitle(name); // Add a Scrollpane to be able to scroll within the canvas PScrollPane scrollPane = new PScrollPane(canvas); getContentPane().add(scrollPane); scrollPane.setWheelScrollingEnabled(false); PCamera lc = canvas.getCamera(); lc.scaleViewAboutPoint(initialScalingfactor, 0, 0); // Disable the default event handlers and add our own. addWindowListener(svEventHandler); canvas.removeInputEventListener(canvas.getPanEventHandler()); canvas.removeInputEventListener(canvas.getZoomEventHandler()); canvas.addInputEventListener(svEventHandler); canvas.addKeyListener(svEventHandler); // Make the window visible. validate(); setVisible(true); } /** * Convenience function to add a message box to the window which can be used * to output debug information. */ public void addMessageBox() { if (ta == null) { ta = new TextArea(); ta.setEditable(false); getContentPane().add(ta, BorderLayout.SOUTH); } // We need to make the window bigger to accomodate the message box. winSizeY += DEF_MESSAGEBOX_HEIGHT; setSize(winSizeX, winSizeY); } /** * Allows you to specify the thickness with which to draw lines, recantgles * and ellipses. * @param width The new thickness. */ public void setStrokeWidth(float width) { // If this worked we wouldn't need the antialiased rendering off. // stroke = new PFixedWidthStroke(width); stroke = new BasicStroke(width); } /** * Draw an ellipse at (x,y) with given width and height, using the * current stroke, the current brush color to fill it and the * current pen color for the outline. */ public void drawEllipse(int x, int y, int width, int height) { PPath pn = PPath.createEllipse(x, y, width, height); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw the image with the given name at (x,y). Any image loaded stays in * memory, so if you intend to redraw an image, you do not have to use * createImage again. */ public void drawImage(PImage img, int xPos, int yPos) { img.setX(xPos); img.setY(yPos); layer.addChild(img); } /** * Draw a line from (x1,y1) to (x2,y2) using the current pen color and stroke. */ public void drawLine(int x1, int y1, int x2, int y2) { PPath pn = PPath.createLine(x1, y1, x2, y2); pn.setStrokePaint(currentPenColor); pn.setPaint(null); // Null paint may render faster than the default. pn.setStroke(stroke); pn.moveTo(x1, y1); pn.lineTo(x2, y2); layer.addChild(pn); } /** * Draw a rectangle given the two points (x1,y1) and (x2,y2) using the current * stroke, pen color for the border and the brush to fill the * interior. */ public void drawRectangle(int x1, int y1, int x2, int y2) { if (x1 > x2) { int t = x1; x1 = x2; x2 = t; } if (y1 > y2) { int t = y1; y1 = y2; y2 = t; } PPath pn = PPath.createRectangle(x1, y1, x2 - x1, y2 - y1); pn.setStrokePaint(currentPenColor); pn.setStroke(stroke); pn.setPaint(currentBrushColor); layer.addChild(pn); } /** * Draw some text at (x,y) using the current pen color and text attributes. If * the current font does NOT support at least one character, it tries to find * a font which is capable of displaying it and use that to render the text. * Note: If the font says it can render a glyph, but in reality it turns out * to be crap, there is nothing we can do about it. */ public void drawText(int x, int y, String text) { int unreadableCharAt = -1; char[] chars = text.toCharArray(); PText pt = new PText(text); pt.setTextPaint(currentPenColor); pt.setFont(currentFont); // Check to see if every character can be displayed by the current font. for (int i = 0; i < chars.length; i++) { if (!currentFont.canDisplay(chars[i])) { // Set to the first not displayable character. unreadableCharAt = i; break; } } // Have to find some working font and use it for this text entry. if (unreadableCharAt != -1) { Font[] allfonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (int j = 0; j < allfonts.length; j++) { if (allfonts[j].canDisplay(chars[unreadableCharAt])) { Font tempFont = new Font(allfonts[j].getFontName(), currentFont.getStyle(), currentFont.getSize()); pt.setFont(tempFont); break; } } } pt.setX(x); pt.setY(y); layer.addChild(pt); } /** Set the pen color to an RGB value */ public void pen(int red, int green, int blue) { pen(red, green, blue, 255); } /** Set the pen color to an RGBA value */ public void pen(int red, int green, int blue, int alpha) { currentPenColor = new Color(red, green, blue, alpha); } /** * Define how to display text. Note: underlined is not currently not supported */ public void textAttributes(String font, int pixelSize, boolean bold, boolean italic, boolean underlined) { // For legacy reasons convert "Times" to "Times New Roman" if (font.equals("Times")) { font = "Times New Roman"; } int style = Font.PLAIN; if (bold) { style += Font.BOLD; } if (italic) { style += Font.ITALIC; } currentFont = new Font(font, style, pixelSize); } /** * Zoom the window to the rectangle given the two points (x1,y1) * and (x2,y2), which must be greater than (x1,y1). */ public void zoomRectangle(int x1, int y1, int x2, int y2) { if (x2 > x1 && y2 > y1) { winSizeX = getWidth(); winSizeY = getHeight(); int width = x2 - x1; int height = y2 - y1; // Since piccolo doesn't do this well either, pad with a margin // all the way around. int wmargin = width / 2; int hmargin = height / 2; double scalefactor = Math.min(winSizeX / (2.0 * wmargin + width), winSizeY / (2.0 * hmargin + height)); PCamera lc = canvas.getCamera(); lc.scaleView(scalefactor / lc.getViewScale()); lc.animateViewToPanToBounds(new Rectangle(x1 - hmargin, y1 - hmargin, 2 * wmargin + width, 2 * hmargin + height), 0); } } /** * Flush buffers and update display. * * Only actually reacts if there are no more messages in the stack, to prevent * the canvas from flickering. */ public void update() { // TODO(rays) fix bugs in piccolo or use something else. // The repaint function generates many // exceptions for no good reason. We catch and ignore as many as we // can here, but most of them are generated by the system repaints // caused by resizing/exposing parts of the window etc, and they // generate unwanted stack traces that have to be piped to /dev/null // (on linux). try { repaint(); } catch (NullPointerException e) { // Do nothing so the output isn't full of stack traces. } catch (IllegalPathStateException e) { // Do nothing so the output isn't full of stack traces. } } /** Adds a checkbox entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id, boolean checked) { svMenuBar.add(parent, name, id, checked); } /** Adds a submenu to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name) { addMenuBarItem(parent, name, -1); } /** Adds a new entry to the menubar, c.f. SVMenubar.add(...) */ public void addMenuBarItem(String parent, String name, int id) { if (svMenuBar == null) { svMenuBar = new SVMenuBar(this); } svMenuBar.add(parent, name, id); } /** Add a message to the message box. */ public void addMessage(String message) { if (ta != null) { ta.append(message + "\n"); } else { System.out.println(message + "\n"); } } /** * This method converts a string which might contain hexadecimal values to a * string which contains the respective unicode counterparts. * * For example, Hall0x0094chen returns Hall<o umlaut>chen * encoded as utf8. * * @param input The original string, containing 0x values * @return The converted string which has the replaced unicode symbols */ private static String convertIntegerStringToUnicodeString(String input) { StringBuffer sb = new StringBuffer(input); Pattern numbers = Pattern.compile("0x[0-9a-fA-F]{4}"); Matcher matcher = numbers.matcher(sb); while (matcher.find()) { // Find the next match which resembles a hexadecimal value and convert it // to // its char value char a = (char) (Integer.decode(matcher.group()).intValue()); // Replace the original with the new character sb.replace(matcher.start(), matcher.end(), String.valueOf(a)); // Start again, since our positions have switched matcher.reset(); } return sb.toString(); } /** * Show a modal input dialog. The answer by the dialog is then send to the * client, together with the associated menu id, as SVET_POPUP * * @param msg The text that is displayed in the dialog. * @param def The default value of the dialog. * @param id The associated commandId * @param evtype The event this is associated with (usually SVET_MENU * or SVET_POPUP) */ public void showInputDialog(String msg, String def, int id, SVEventType evtype) { svEventHandler.timer.stop(); String tmp = (String) JOptionPane.showInputDialog(this, msg, "", JOptionPane.QUESTION_MESSAGE, null, null, def); if (tmp != null) { tmp = convertIntegerStringToUnicodeString(tmp); SVEvent res = new SVEvent(evtype, this, id, tmp); ScrollView.addMessage(res); } svEventHandler.timer.restart(); } /** * Shows a modal input dialog to the user. The return value is automatically * sent to the client as SVET_INPUT event (with command id -1). * * @param msg The text of the dialog. */ public void showInputDialog(String msg) { showInputDialog(msg, null, -1, SVEventType.SVET_INPUT); } /** * Shows a dialog presenting "Yes" and "No" as answers and returns either a * "y" or "n" to the client. * * @param msg The text that is displayed in the dialog. */ public void showYesNoDialog(String msg) { // res returns 0 on yes, 1 on no. Seems to be a bit counterintuitive int res = JOptionPane.showOptionDialog(this, msg, "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); SVEvent e = null; if (res == 0) { e = new SVEvent(SVEventType.SVET_INPUT, this, 0, 0, 0, 0, "y"); } else if (res == 1) { e = new SVEvent(SVEventType.SVET_INPUT, this, 0, 0, 0, 0, "n"); } ScrollView.addMessage(e); } /** Adds a submenu to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, -1); } /** Adds a new menu entry to the popup menu, c.f. SVPopupMenu.add(...) */ public void addPopupMenuItem(String parent, String name, int cmdEvent, String value, String desc) { if (svPuMenu == null) { svPuMenu = new SVPopupMenu(this); } svPuMenu.add(parent, name, cmdEvent, value, desc); } /** Destroys a window. */ public void destroy() { ScrollView.addMessage(new SVEvent(SVEventType.SVET_DESTROY, this, 0, "SVET_DESTROY")); setVisible(false); // dispose(); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVWindow.java
Java
asf20
21,454
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JCheckBoxMenuItem; /** * Constructs a new menulistitem which possesses a flag that can be toggled. */ class SVCheckboxMenuItem extends SVAbstractMenuItem { public String value = null; public String desc = null; public boolean bvalue; SVCheckboxMenuItem(int id, String name, boolean val) { super(id, name, new JCheckBoxMenuItem(name, val)); bvalue = val; } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Checkbox entry - trigger and send event. if (bvalue) { bvalue = false; } else { bvalue = true; } SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return Boolean.toString(bvalue); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVCheckboxMenuItem.java
Java
asf20
1,999
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVWindow; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * The SVMenuBar class provides the functionality to add a menubar to * ScrollView. Each menubar item gets associated with a (client-defined) * command-id, which SVMenuBar will return upon clicking it. * * @author wanke@google.com * */ public class SVMenuBar implements ActionListener { /** The root entry to add items to. */ private JMenuBar root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVMenuBar and place it at the top of the ScrollView window. * * @param scrollView The window our menubar belongs to. */ public SVMenuBar(SVWindow scrollView) { root = new JMenuBar(); svWindow = scrollView; items = new HashMap<String, SVAbstractMenuItem>(); svWindow.setJMenuBar(root); } /** * A click on one of the items in our menubar has occured. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem. SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_MENU); } /** * Add a new entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new checkbox entry to the menubar. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param b Whether the entry is initally flagged. * */ public void add(String parent, String name, int id, boolean b) { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVCheckboxMenuItem(id, name, b); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVMenuBar.java
Java
asf20
4,360
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenu; import javax.swing.JMenuItem; abstract class SVAbstractMenuItem { JMenuItem mi; public String name; public int id; /** * Sets the basic attributes for name, id and the corresponding swing item */ SVAbstractMenuItem(int id, String name, JMenuItem jmi) { this.mi = jmi; this.name = name; this.id = id; } /** Returns the actual value of the MenuListItem. */ public String getValue() { return null; } /** Adds a child entry to the submenu. */ public void add(SVAbstractMenuItem mli) { } /** Adds a child menu to the submenu (or root node). */ public void add(JMenu jli) { } /** * What to do when user clicks on this item. * @param window The window the event happened. * @param eventType What kind of event will be associated * (usually SVET_POPUP or SVET_MENU). */ public void performAction(SVWindow window, SVEventType eventType) {} }
1080228-arabicocr11
java/com/google/scrollview/ui/SVAbstractMenuItem.java
Java
asf20
1,936
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; import com.google.scrollview.events.SVEventType; import com.google.scrollview.ui.SVMenuItem; import com.google.scrollview.ui.SVWindow; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JMenu; import javax.swing.JPopupMenu; /** * The SVPopupMenu class provides the functionality to add a popup menu to * ScrollView. Each popup menu item gets associated with a (client-defined) * command-id, which SVPopupMenu will return upon clicking it. * * @author wanke@google.com * */ public class SVPopupMenu implements ActionListener { /** The root entry to add items to. */ private JPopupMenu root; /** Contains a map of item name to its actual entry. */ private HashMap<String, SVAbstractMenuItem> items; /** The window the menubar belongs to. */ private SVWindow svWindow; /** * Create a new SVPopupMenu and associate it with a ScrollView window. * * @param sv The window our popup menu belongs to. */ SVPopupMenu(SVWindow sv) { root = new JPopupMenu(); svWindow = sv; items = new HashMap<String, SVAbstractMenuItem>(); } /** * Add a new entry to the menubar. For these items, the server will poll the * client to ask what to do. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. */ public void add(String parent, String name, int id) { // A duplicate entry - we just throw it away, since its already in. if (items.get(name) != null) { return; } // A new submenu at the top-level if (parent.equals("")) { JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); root.add(jli); } // A new sub-submenu else if (id == -1) { SVAbstractMenuItem jmi = items.get(parent); JMenu jli = new JMenu(name); SVAbstractMenuItem mli = new SVSubMenuItem(name, jli); items.put(name, mli); jmi.add(jli); } // A new child entry. Add to appropriate parent. else { SVAbstractMenuItem jmi = items.get(parent); if (jmi == null) { System.out.println("ERROR: Unknown parent " + parent); System.exit(1); } SVAbstractMenuItem mli = new SVEmptyMenuItem(id, name); mli.mi.addActionListener(this); items.put(name, mli); jmi.add(mli); } } /** * Add a new entry to the menubar. In this case, we also know its value and * possibly even have a description. For these items, the server will not poll * the client to ask what to do, but just show an input dialog and send a * message with the new value. * * @param parent The menu we add our new entry to (should have been defined * before). If the parent is "", we will add the entry to the root * (top-level) * @param name The caption of the new entry. * @param id The Id of the new entry. If it is -1, the entry will be treated * as a menu. * @param value The value of the new entry. * @param desc The description of the new entry. */ public void add(String parent, String name, int id, String value, String desc) { SVAbstractMenuItem jmi = items.get(parent); SVMenuItem mli = new SVMenuItem(id, name, value, desc); mli.mi.addActionListener(this); items.put(name, mli); if (jmi == null) { // add to root root.add(mli.mi); } else { // add to parent jmi.add(mli); } } /** * A click on one of the items in our menubar has occured. Forward it * to the item itself to let it decide what happens. */ public void actionPerformed(ActionEvent e) { // Get the corresponding menuitem SVAbstractMenuItem svm = items.get(e.getActionCommand()); svm.performAction(svWindow, SVEventType.SVET_POPUP); } /** * Gets called by the SVEventHandler of the window to actually show the * content of the popup menu. */ public void show(Component Invoker, int x, int y) { root.show(Invoker, x, y); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVPopupMenu.java
Java
asf20
4,925
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import javax.swing.JMenu; /** Constructs a new submenu which can hold other entries. */ class SVSubMenuItem extends SVAbstractMenuItem { public SVSubMenuItem(String name, JMenu jli) { super(-1, name, jli); } /** Adds a child entry to the submenu. */ @Override public void add(SVAbstractMenuItem mli) { mi.add(mli.mi); } /** Adds a child menu to the submenu (or root node). */ @Override public void add(JMenu jli) { mi.add(jli); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVSubMenuItem.java
Java
asf20
1,426
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which also has a value and a description. For * these, we will not have to ask the server what the value is when the user * wants to change it, but can just call the client with the new value. */ class SVMenuItem extends SVAbstractMenuItem { public String value = null; public String desc = null; SVMenuItem(int id, String name, String v, String d) { super(id, name, new JMenuItem(name)); value = v; desc = d; } /** * Ask the user for new input for a variable and send it. * Depending on whether there is a description given for the entry, show * the description in the dialog or just show the name. */ @Override public void performAction(SVWindow window, SVEventType eventType) { if (desc != null) { window.showInputDialog(desc, value, id, eventType); } else { window.showInputDialog(name, value, id, eventType); } } /** Returns the actual value of the MenuListItem. */ @Override public String getValue() { return value; } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVMenuItem.java
Java
asf20
2,086
SUBDIRS = EXTRA_DIST = \ SVAbstractMenuItem.java \ SVCheckboxMenuItem.java SVEmptyMenuItem.java \ SVImageHandler.java SVMenuBar.java \ SVMenuItem.java SVPopupMenu.java SVSubMenuItem.java SVWindow.java
1080228-arabicocr11
java/com/google/scrollview/ui/Makefile.am
Makefile
asf20
218
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; /** * A MenuListItem is any sort of menu entry. This can either be within a popup * menu or within a menubar. It can either be a submenu (only name and * command-id) or a name with an associated value and possibly description. They * can also have new entries added (if they are submenus). * * @author wanke@google.com */ import com.google.scrollview.ScrollView; import com.google.scrollview.events.SVEvent; import com.google.scrollview.events.SVEventType; import javax.swing.JMenuItem; /** * Constructs a new menulistitem which just has an ID and a name attached to * it. In this case, we will have to ask for the value of the item and its * description if it gets called. */ class SVEmptyMenuItem extends SVAbstractMenuItem { SVEmptyMenuItem(int id, String name) { super(id, name, new JMenuItem(name)); } /** What to do when user clicks on this item. */ @Override public void performAction(SVWindow window, SVEventType eventType) { // Send an event indicating that someone clicked on an entry. // Value will be null here. SVEvent svme = new SVEvent(eventType, window, id, getValue()); ScrollView.addMessage(svme); } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVEmptyMenuItem.java
Java
asf20
1,801
// Copyright 2007 Google Inc. All Rights Reserved. // // 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. package com.google.scrollview.ui; import org.piccolo2d.nodes.PImage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; /** * The ScrollViewImageHandler is a helper class which takes care of image * processing. It is used to construct an Image from the message-stream and * basically consists of a number of utility functions to process the input * stream. * * @author wanke@google.com */ public class SVImageHandler { /* All methods are static, so we forbid to construct SVImageHandler objects */ private SVImageHandler() { } /** * Reads size bytes from the stream in and interprets it as an image file, * encoded as png, and then text-encoded as base 64, returning the decoded * bitmap. * * @param size The size of the image file. * @param in The input stream from which to read the bytes. */ public static PImage readImage(int size, BufferedReader in) { char[] charbuffer = new char[size]; int numRead = 0; while (numRead < size) { int newRead = -1; try { newRead = in.read(charbuffer, numRead, size - numRead); } catch (IOException e) { System.out.println("Failed to read image data from socket:" + e.getMessage()); return null; } if (newRead < 0) { return null; } numRead += newRead; } if (numRead != size) { System.out.println("Failed to read image data from socket"); return null; } // Convert the character data to binary. byte[] binarydata = DatatypeConverter.parseBase64Binary(new String(charbuffer)); // Convert the binary data to a byte stream and parse to image. ByteArrayInputStream byteStream = new ByteArrayInputStream(binarydata); try { PImage img = new PImage(ImageIO.read(byteStream)); return img; } catch (IOException e) { System.out.println("Failed to decode image data from socket" + e.getMessage()); } return null; } }
1080228-arabicocr11
java/com/google/scrollview/ui/SVImageHandler.java
Java
asf20
2,658
SUBDIRS = events ui EXTRA_DIST = \ ScrollView.java
1080228-arabicocr11
java/com/google/scrollview/Makefile.am
Makefile
asf20
56
SUBDIRS = scrollview
1080228-arabicocr11
java/com/google/Makefile.am
Makefile
asf20
21
SUBDIRS = google
1080228-arabicocr11
java/com/Makefile.am
Makefile
asf20
17
/********************************************************************** * File: tfacepp.cpp (Formerly tface++.c) * Description: C++ side of the C/C++ Tess/Editor interface. * Author: Ray Smith * Created: Thu Apr 23 15:39:23 BST 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4305) // int/float warnings #pragma warning(disable:4800) // int/bool warnings #endif #include <math.h> #include "blamer.h" #include "errcode.h" #include "ratngs.h" #include "reject.h" #include "tesseractclass.h" #include "werd.h" #define MAX_UNDIVIDED_LENGTH 24 /********************************************************************** * recog_word * * Convert the word to tess form and pass it to the tess segmenter. * Convert the output back to editor form. **********************************************************************/ namespace tesseract { void Tesseract::recog_word(WERD_RES *word) { if (wordrec_skip_no_truth_words && (word->blamer_bundle == NULL || word->blamer_bundle->incorrect_result_reason() == IRR_NO_TRUTH)) { if (classify_debug_level) tprintf("No truth for word - skipping\n"); word->tess_failed = true; return; } ASSERT_HOST(!word->chopped_word->blobs.empty()); recog_word_recursive(word); word->SetupBoxWord(); if (word->best_choice->length() != word->box_word->length()) { tprintf("recog_word ASSERT FAIL String:\"%s\"; " "Strlen=%d; #Blobs=%d\n", word->best_choice->debug_string().string(), word->best_choice->length(), word->box_word->length()); } ASSERT_HOST(word->best_choice->length() == word->box_word->length()); // Check that the ratings matrix size matches the sum of all the // segmentation states. if (!word->StatesAllValid()) { tprintf("Not all words have valid states relative to ratings matrix!!"); word->DebugWordChoices(true, NULL); ASSERT_HOST(word->StatesAllValid()); } if (tessedit_override_permuter) { /* Override the permuter type if a straight dictionary check disagrees. */ uinT8 perm_type = word->best_choice->permuter(); if ((perm_type != SYSTEM_DAWG_PERM) && (perm_type != FREQ_DAWG_PERM) && (perm_type != USER_DAWG_PERM)) { uinT8 real_dict_perm_type = dict_word(*word->best_choice); if (((real_dict_perm_type == SYSTEM_DAWG_PERM) || (real_dict_perm_type == FREQ_DAWG_PERM) || (real_dict_perm_type == USER_DAWG_PERM)) && (alpha_count(word->best_choice->unichar_string().string(), word->best_choice->unichar_lengths().string()) > 0)) { word->best_choice->set_permuter(real_dict_perm_type); // use dict perm } } if (tessedit_rejection_debug && perm_type != word->best_choice->permuter()) { tprintf("Permuter Type Flipped from %d to %d\n", perm_type, word->best_choice->permuter()); } } // Factored out from control.cpp ASSERT_HOST((word->best_choice == NULL) == (word->raw_choice == NULL)); if (word->best_choice == NULL || word->best_choice->length() == 0 || static_cast<int>(strspn(word->best_choice->unichar_string().string(), " ")) == word->best_choice->length()) { word->tess_failed = true; word->reject_map.initialise(word->box_word->length()); word->reject_map.rej_word_tess_failure(); } else { word->tess_failed = false; } } /********************************************************************** * recog_word_recursive * * Convert the word to tess form and pass it to the tess segmenter. * Convert the output back to editor form. **********************************************************************/ void Tesseract::recog_word_recursive(WERD_RES *word) { int word_length = word->chopped_word->NumBlobs(); // no of blobs if (word_length > MAX_UNDIVIDED_LENGTH) { return split_and_recog_word(word); } cc_recog(word); word_length = word->rebuild_word->NumBlobs(); // No of blobs in output. // Do sanity checks and minor fixes on best_choice. if (word->best_choice->length() > word_length) { word->best_choice->make_bad(); // should never happen tprintf("recog_word: Discarded long string \"%s\"" " (%d characters vs %d blobs)\n", word->best_choice->unichar_string().string(), word->best_choice->length(), word_length); tprintf("Word is at:"); word->word->bounding_box().print(); } if (word->best_choice->length() < word_length) { UNICHAR_ID space_id = unicharset.unichar_to_id(" "); while (word->best_choice->length() < word_length) { word->best_choice->append_unichar_id(space_id, 1, 0.0, word->best_choice->certainty()); } } } /********************************************************************** * split_and_recog_word * * Split the word into 2 smaller pieces at the largest gap. * Recognize the pieces and stick the results back together. **********************************************************************/ void Tesseract::split_and_recog_word(WERD_RES *word) { // Find the biggest blob gap in the chopped_word. int bestgap = -MAX_INT32; int split_index = 0; for (int b = 1; b < word->chopped_word->NumBlobs(); ++b) { TBOX prev_box = word->chopped_word->blobs[b - 1]->bounding_box(); TBOX blob_box = word->chopped_word->blobs[b]->bounding_box(); int gap = blob_box.left() - prev_box.right(); if (gap > bestgap) { bestgap = gap; split_index = b; } } ASSERT_HOST(split_index > 0); WERD_RES *word2 = NULL; BlamerBundle *orig_bb = NULL; split_word(word, split_index, &word2, &orig_bb); // Recognize the first part of the word. recog_word_recursive(word); // Recognize the second part of the word. recog_word_recursive(word2); join_words(word, word2, orig_bb); } /********************************************************************** * split_word * * Split a given WERD_RES in place into two smaller words for recognition. * split_pt is the index of the first blob to go in the second word. * The underlying word is left alone, only the TWERD (and subsequent data) * are split up. orig_blamer_bundle is set to the original blamer bundle, * and will now be owned by the caller. New blamer bundles are forged for the * two pieces. **********************************************************************/ void Tesseract::split_word(WERD_RES *word, int split_pt, WERD_RES **right_piece, BlamerBundle **orig_blamer_bundle) const { ASSERT_HOST(split_pt >0 && split_pt < word->chopped_word->NumBlobs()); // Save a copy of the blamer bundle so we can try to reconstruct it below. BlamerBundle *orig_bb = word->blamer_bundle ? new BlamerBundle(*word->blamer_bundle) : NULL; WERD_RES *word2 = new WERD_RES(*word); // blow away the copied chopped_word, as we want to work with // the blobs from the input chopped_word so seam_arrays can be merged. TWERD *chopped = word->chopped_word; TWERD *chopped2 = new TWERD; chopped2->blobs.reserve(chopped->NumBlobs() - split_pt); for (int i = split_pt; i < chopped->NumBlobs(); ++i) { chopped2->blobs.push_back(chopped->blobs[i]); } chopped->blobs.truncate(split_pt); word->chopped_word = NULL; delete word2->chopped_word; word2->chopped_word = NULL; const UNICHARSET &unicharset = *word->uch_set; word->ClearResults(); word2->ClearResults(); word->chopped_word = chopped; word2->chopped_word = chopped2; word->SetupBasicsFromChoppedWord(unicharset); word2->SetupBasicsFromChoppedWord(unicharset); // Try to adjust the blamer bundle. if (orig_bb != NULL) { // TODO(rays) Looks like a leak to me. // orig_bb should take, rather than copy. word->blamer_bundle = new BlamerBundle(); word2->blamer_bundle = new BlamerBundle(); orig_bb->SplitBundle(chopped->blobs.back()->bounding_box().right(), word2->chopped_word->blobs[0]->bounding_box().left(), wordrec_debug_blamer, word->blamer_bundle, word2->blamer_bundle); } *right_piece = word2; *orig_blamer_bundle = orig_bb; } /********************************************************************** * join_words * * The opposite of split_word(): * join word2 (including any recognized data / seam array / etc) * onto the right of word and then delete word2. * Also, if orig_bb is provided, stitch it back into word. **********************************************************************/ void Tesseract::join_words(WERD_RES *word, WERD_RES *word2, BlamerBundle *orig_bb) const { TBOX prev_box = word->chopped_word->blobs.back()->bounding_box(); TBOX blob_box = word2->chopped_word->blobs[0]->bounding_box(); // Tack the word2 outputs onto the end of the word outputs. word->chopped_word->blobs += word2->chopped_word->blobs; word->rebuild_word->blobs += word2->rebuild_word->blobs; word2->chopped_word->blobs.clear(); word2->rebuild_word->blobs.clear(); TPOINT split_pt; split_pt.x = (prev_box.right() + blob_box.left()) / 2; split_pt.y = (prev_box.top() + prev_box.bottom() + blob_box.top() + blob_box.bottom()) / 4; // Move the word2 seams onto the end of the word1 seam_array. // Since the seam list is one element short, an empty seam marking the // end of the last blob in the first word is needed first. word->seam_array.push_back(new SEAM(0.0f, split_pt, NULL, NULL, NULL)); word->seam_array += word2->seam_array; word2->seam_array.truncate(0); // Fix widths and gaps. word->blob_widths += word2->blob_widths; word->blob_gaps += word2->blob_gaps; // Fix the ratings matrix. int rat1 = word->ratings->dimension(); int rat2 = word2->ratings->dimension(); word->ratings->AttachOnCorner(word2->ratings); ASSERT_HOST(word->ratings->dimension() == rat1 + rat2); word->best_state += word2->best_state; // Append the word choices. *word->raw_choice += *word2->raw_choice; // How many alt choices from each should we try to get? const int kAltsPerPiece = 2; // When do we start throwing away extra alt choices? const int kTooManyAltChoices = 100; // Construct the cartesian product of the best_choices of word(1) and word2. WERD_CHOICE_LIST joined_choices; WERD_CHOICE_IT jc_it(&joined_choices); WERD_CHOICE_IT bc1_it(&word->best_choices); WERD_CHOICE_IT bc2_it(&word2->best_choices); int num_word1_choices = word->best_choices.length(); int total_joined_choices = num_word1_choices; // Nota Bene: For the main loop here, we operate only on the 2nd and greater // word2 choices, and put them in the joined_choices list. The 1st word2 // choice gets added to the original word1 choices in-place after we have // finished with them. int bc2_index = 1; for (bc2_it.forward(); !bc2_it.at_first(); bc2_it.forward(), ++bc2_index) { if (total_joined_choices >= kTooManyAltChoices && bc2_index > kAltsPerPiece) break; int bc1_index = 0; for (bc1_it.move_to_first(); bc1_index < num_word1_choices; ++bc1_index, bc1_it.forward()) { if (total_joined_choices >= kTooManyAltChoices && bc1_index > kAltsPerPiece) break; WERD_CHOICE *wc = new WERD_CHOICE(*bc1_it.data()); *wc += *bc2_it.data(); jc_it.add_after_then_move(wc); ++total_joined_choices; } } // Now that we've filled in as many alternates as we want, paste the best // choice for word2 onto the original word alt_choices. bc1_it.move_to_first(); bc2_it.move_to_first(); for (bc1_it.mark_cycle_pt(); !bc1_it.cycled_list(); bc1_it.forward()) { *bc1_it.data() += *bc2_it.data(); } bc1_it.move_to_last(); bc1_it.add_list_after(&joined_choices); // Restore the pointer to original blamer bundle and combine blamer // information recorded in the splits. if (orig_bb != NULL) { orig_bb->JoinBlames(*word->blamer_bundle, *word2->blamer_bundle, wordrec_debug_blamer); delete word->blamer_bundle; word->blamer_bundle = orig_bb; } word->SetupBoxWord(); word->reject_map.initialise(word->box_word->length()); delete word2; } } // namespace tesseract
1080228-arabicocr11
ccmain/tfacepp.cpp
C++
asf20
13,093
/********************************************************************** * File: paragraphs.h * Description: Paragraph Detection data structures. * Author: David Eger * Created: 25 February 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_PARAGRAPHS_H_ #define TESSERACT_CCMAIN_PARAGRAPHS_H_ #include "rect.h" #include "ocrpara.h" #include "genericvector.h" #include "strngs.h" class WERD; class UNICHARSET; namespace tesseract { class MutableIterator; // This structure captures all information needed about a text line for the // purposes of paragraph detection. It is meant to be exceedingly light-weight // so that we can easily test paragraph detection independent of the rest of // Tesseract. class RowInfo { public: // Constant data derived from Tesseract output. STRING text; // the full UTF-8 text of the line. bool ltr; // whether the majority of the text is left-to-right // TODO(eger) make this more fine-grained. bool has_leaders; // does the line contain leader dots (.....)? bool has_drop_cap; // does the line have a drop cap? int pix_ldistance; // distance to the left pblock boundary in pixels int pix_rdistance; // distance to the right pblock boundary in pixels float pix_xheight; // guessed xheight for the line int average_interword_space; // average space between words in pixels. int num_words; TBOX lword_box; // in normalized (horiz text rows) space TBOX rword_box; // in normalized (horiz text rows) space STRING lword_text; // the UTF-8 text of the leftmost werd STRING rword_text; // the UTF-8 text of the rightmost werd // The text of a paragraph typically starts with the start of an idea and // ends with the end of an idea. Here we define paragraph as something that // may have a first line indent and a body indent which may be different. // Typical words that start an idea are: // 1. Words in western scripts that start with // a capital letter, for example "The" // 2. Bulleted or numbered list items, for // example "2." // Typical words which end an idea are words ending in punctuation marks. In // this vocabulary, each list item is represented as a paragraph. bool lword_indicates_list_item; bool lword_likely_starts_idea; bool lword_likely_ends_idea; bool rword_indicates_list_item; bool rword_likely_starts_idea; bool rword_likely_ends_idea; }; // Main entry point for Paragraph Detection Algorithm. // // Given a set of equally spaced textlines (described by row_infos), // Split them into paragraphs. See http://goto/paragraphstalk // // Output: // row_owners - one pointer for each row, to the paragraph it belongs to. // paragraphs - this is the actual list of PARA objects. // models - the list of paragraph models referenced by the PARA objects. // caller is responsible for deleting the models. void DetectParagraphs(int debug_level, GenericVector<RowInfo> *row_infos, GenericVector<PARA *> *row_owners, PARA_LIST *paragraphs, GenericVector<ParagraphModel *> *models); // Given a MutableIterator to the start of a block, run DetectParagraphs on // that block and commit the results to the underlying ROW and BLOCK structs, // saving the ParagraphModels in models. Caller owns the models. // We use unicharset during the function to answer questions such as "is the // first letter of this word upper case?" void DetectParagraphs(int debug_level, bool after_text_recognition, const MutableIterator *block_start, GenericVector<ParagraphModel *> *models); } // namespace #endif // TESSERACT_CCMAIN_PARAGRAPHS_H_
1080228-arabicocr11
ccmain/paragraphs.h
C++
asf20
4,456
/****************************************************************** * File: superscript.cpp * Description: Correction pass to fix superscripts and subscripts. * Author: David Eger * Created: Mon Mar 12 14:05:00 PDT 2012 * * (C) Copyright 2012, Google, Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "normalis.h" #include "tesseractclass.h" static int LeadingUnicharsToChopped(WERD_RES *word, int num_unichars) { int num_chopped = 0; for (int i = 0; i < num_unichars; i++) num_chopped += word->best_state[i]; return num_chopped; } static int TrailingUnicharsToChopped(WERD_RES *word, int num_unichars) { int num_chopped = 0; for (int i = 0; i < num_unichars; i++) num_chopped += word->best_state[word->best_state.size() - 1 - i]; return num_chopped; } namespace tesseract { /** * Given a recognized blob, see if a contiguous collection of sub-pieces * (chopped blobs) starting at its left might qualify as being a subscript * or superscript letter based only on y position. Also do this for the * right side. */ void YOutlierPieces(WERD_RES *word, int rebuilt_blob_index, int super_y_bottom, int sub_y_top, ScriptPos *leading_pos, int *num_leading_outliers, ScriptPos *trailing_pos, int *num_trailing_outliers) { ScriptPos sp_unused1, sp_unused2; int unused1, unused2; if (!leading_pos) leading_pos = &sp_unused1; if (!num_leading_outliers) num_leading_outliers = &unused1; if (!trailing_pos) trailing_pos = &sp_unused2; if (!num_trailing_outliers) num_trailing_outliers = &unused2; *num_leading_outliers = *num_trailing_outliers = 0; *leading_pos = *trailing_pos = SP_NORMAL; int chopped_start = LeadingUnicharsToChopped(word, rebuilt_blob_index); int num_chopped_pieces = word->best_state[rebuilt_blob_index]; ScriptPos last_pos = SP_NORMAL; int trailing_outliers = 0; for (int i = 0; i < num_chopped_pieces; i++) { TBOX box = word->chopped_word->blobs[chopped_start + i]->bounding_box(); ScriptPos pos = SP_NORMAL; if (box.bottom() >= super_y_bottom) { pos = SP_SUPERSCRIPT; } else if (box.top() <= sub_y_top) { pos = SP_SUBSCRIPT; } if (pos == SP_NORMAL) { if (trailing_outliers == i) { *num_leading_outliers = trailing_outliers; *leading_pos = last_pos; } trailing_outliers = 0; } else { if (pos == last_pos) { trailing_outliers++; } else { trailing_outliers = 1; } } last_pos = pos; } *num_trailing_outliers = trailing_outliers; *trailing_pos = last_pos; } /** * Attempt to split off any high (or low) bits at the ends of the word with poor * certainty and recognize them separately. If the certainty gets much better * and other sanity checks pass, acccept. * * This superscript fix is meant to be called in the second pass of recognition * when we have tried once and already have a preliminary answer for word. * * @return Whether we modified the given word. */ bool Tesseract::SubAndSuperscriptFix(WERD_RES *word) { if (word->tess_failed || word->word->flag(W_REP_CHAR) || !word->best_choice) { return false; } int num_leading, num_trailing; ScriptPos sp_leading, sp_trailing; float leading_certainty, trailing_certainty; float avg_certainty, unlikely_threshold; // Calculate the number of whole suspicious characters at the edges. GetSubAndSuperscriptCandidates( word, &num_leading, &sp_leading, &leading_certainty, &num_trailing, &sp_trailing, &trailing_certainty, &avg_certainty, &unlikely_threshold); const char *leading_pos = sp_leading == SP_SUBSCRIPT ? "sub" : "super"; const char *trailing_pos = sp_trailing == SP_SUBSCRIPT ? "sub" : "super"; int num_blobs = word->best_choice->length(); // Calculate the remainder (partial characters) at the edges. // This accounts for us having classified the best version of // a word as [speaker?'] when it was instead [speaker.^{21}] // (that is we accidentally thought the 2 was attached to the period). int num_remainder_leading = 0, num_remainder_trailing = 0; if (num_leading + num_trailing < num_blobs && unlikely_threshold < 0.0) { int super_y_bottom = kBlnBaselineOffset + kBlnXHeight * superscript_min_y_bottom; int sub_y_top = kBlnBaselineOffset + kBlnXHeight * subscript_max_y_top; int last_word_char = num_blobs - 1 - num_trailing; float last_char_certainty = word->best_choice->certainty(last_word_char); if (word->best_choice->unichar_id(last_word_char) != 0 && last_char_certainty <= unlikely_threshold) { ScriptPos rpos; YOutlierPieces(word, last_word_char, super_y_bottom, sub_y_top, NULL, NULL, &rpos, &num_remainder_trailing); if (num_trailing > 0 && rpos != sp_trailing) num_remainder_trailing = 0; if (num_remainder_trailing > 0 && last_char_certainty < trailing_certainty) { trailing_certainty = last_char_certainty; } } bool another_blob_available = (num_remainder_trailing == 0) || num_leading + num_trailing + 1 < num_blobs; int first_char_certainty = word->best_choice->certainty(num_leading); if (another_blob_available && word->best_choice->unichar_id(num_leading) != 0 && first_char_certainty <= unlikely_threshold) { ScriptPos lpos; YOutlierPieces(word, num_leading, super_y_bottom, sub_y_top, &lpos, &num_remainder_leading, NULL, NULL); if (num_leading > 0 && lpos != sp_leading) num_remainder_leading = 0; if (num_remainder_leading > 0 && first_char_certainty < leading_certainty) { leading_certainty = first_char_certainty; } } } // If nothing to do, bail now. if (num_leading + num_trailing + num_remainder_leading + num_remainder_trailing == 0) { return false; } if (superscript_debug >= 1) { tprintf("Candidate for superscript detection: %s (", word->best_choice->unichar_string().string()); if (num_leading || num_remainder_leading) { tprintf("%d.%d %s-leading ", num_leading, num_remainder_leading, leading_pos); } if (num_trailing || num_remainder_trailing) { tprintf("%d.%d %s-trailing ", num_trailing, num_remainder_trailing, trailing_pos); } tprintf(")\n"); } if (superscript_debug >= 3) { word->best_choice->print(); } if (superscript_debug >= 2) { tprintf(" Certainties -- Average: %.2f Unlikely thresh: %.2f ", avg_certainty, unlikely_threshold); if (num_leading) tprintf("Orig. leading (min): %.2f ", leading_certainty); if (num_trailing) tprintf("Orig. trailing (min): %.2f ", trailing_certainty); tprintf("\n"); } // We've now calculated the number of rebuilt blobs we want to carve off. // However, split_word() works from TBLOBs in chopped_word, so we need to // convert to those. int num_chopped_leading = LeadingUnicharsToChopped(word, num_leading) + num_remainder_leading; int num_chopped_trailing = TrailingUnicharsToChopped(word, num_trailing) + num_remainder_trailing; int retry_leading = 0; int retry_trailing = 0; bool is_good = false; WERD_RES *revised = TrySuperscriptSplits( num_chopped_leading, leading_certainty, sp_leading, num_chopped_trailing, trailing_certainty, sp_trailing, word, &is_good, &retry_leading, &retry_trailing); if (is_good) { word->ConsumeWordResults(revised); } else if (retry_leading || retry_trailing) { int retry_chopped_leading = LeadingUnicharsToChopped(revised, retry_leading); int retry_chopped_trailing = TrailingUnicharsToChopped(revised, retry_trailing); WERD_RES *revised2 = TrySuperscriptSplits( retry_chopped_leading, leading_certainty, sp_leading, retry_chopped_trailing, trailing_certainty, sp_trailing, revised, &is_good, &retry_leading, &retry_trailing); if (is_good) { word->ConsumeWordResults(revised2); } delete revised2; } delete revised; return is_good; } /** * Determine how many characters (rebuilt blobs) on each end of a given word * might plausibly be superscripts so SubAndSuperscriptFix can try to * re-recognize them. Even if we find no whole blobs at either end, * we will set *unlikely_threshold to a certainty that might be used to * select "bad enough" outlier characters. If *unlikely_threshold is set to 0, * though, there's really no hope. * * @param[in] word The word to examine. * @param[out] num_rebuilt_leading the number of rebuilt blobs at the start * of the word which are all up or down and * seem badly classified. * @param[out] leading_pos "super" or "sub" (for debugging) * @param[out] leading_certainty the worst certainty in the leading blobs. * @param[out] num_rebuilt_trailing the number of rebuilt blobs at the end * of the word which are all up or down and * seem badly classified. * @param[out] trailing_pos "super" or "sub" (for debugging) * @param[out] trailing_certainty the worst certainty in the trailing blobs. * @param[out] avg_certainty the average certainty of "normal" blobs in * the word. * @param[out] unlikely_threshold the threshold (on certainty) we used to * select "bad enough" outlier characters. */ void Tesseract::GetSubAndSuperscriptCandidates(const WERD_RES *word, int *num_rebuilt_leading, ScriptPos *leading_pos, float *leading_certainty, int *num_rebuilt_trailing, ScriptPos *trailing_pos, float *trailing_certainty, float *avg_certainty, float *unlikely_threshold) { *avg_certainty = *unlikely_threshold = 0.0f; *num_rebuilt_leading = *num_rebuilt_trailing = 0; *leading_certainty = *trailing_certainty = 0.0f; int super_y_bottom = kBlnBaselineOffset + kBlnXHeight * superscript_min_y_bottom; int sub_y_top = kBlnBaselineOffset + kBlnXHeight * subscript_max_y_top; // Step one: Get an average certainty for "normally placed" characters. // Counts here are of blobs in the rebuild_word / unichars in best_choice. *leading_pos = *trailing_pos = SP_NORMAL; int leading_outliers = 0; int trailing_outliers = 0; int num_normal = 0; float normal_certainty_total = 0.0f; float worst_normal_certainty = 0.0f; ScriptPos last_pos = SP_NORMAL; int num_blobs = word->rebuild_word->NumBlobs(); for (int b = 0; b < num_blobs; ++b) { TBOX box = word->rebuild_word->blobs[b]->bounding_box(); ScriptPos pos = SP_NORMAL; if (box.bottom() >= super_y_bottom) { pos = SP_SUPERSCRIPT; } else if (box.top() <= sub_y_top) { pos = SP_SUBSCRIPT; } if (pos == SP_NORMAL) { if (word->best_choice->unichar_id(b) != 0) { float char_certainty = word->best_choice->certainty(b); if (char_certainty < worst_normal_certainty) { worst_normal_certainty = char_certainty; } num_normal++; normal_certainty_total += char_certainty; } if (trailing_outliers == b) { leading_outliers = trailing_outliers; *leading_pos = last_pos; } trailing_outliers = 0; } else { if (last_pos == pos) { trailing_outliers++; } else { trailing_outliers = 1; } } last_pos = pos; } *trailing_pos = last_pos; if (num_normal >= 3) { // throw out the worst as an outlier. num_normal--; normal_certainty_total -= worst_normal_certainty; } if (num_normal > 0) { *avg_certainty = normal_certainty_total / num_normal; *unlikely_threshold = superscript_worse_certainty * (*avg_certainty); } if (num_normal == 0 || (leading_outliers == 0 && trailing_outliers == 0)) { return; } // Step two: Try to split off bits of the word that are both outliers // and have much lower certainty than average // Calculate num_leading and leading_certainty. for (*leading_certainty = 0.0f, *num_rebuilt_leading = 0; *num_rebuilt_leading < leading_outliers; (*num_rebuilt_leading)++) { float char_certainty = word->best_choice->certainty(*num_rebuilt_leading); if (char_certainty > *unlikely_threshold) { break; } if (char_certainty < *leading_certainty) { *leading_certainty = char_certainty; } } // Calculate num_trailing and trailing_certainty. for (*trailing_certainty = 0.0f, *num_rebuilt_trailing = 0; *num_rebuilt_trailing < trailing_outliers; (*num_rebuilt_trailing)++) { int blob_idx = num_blobs - 1 - *num_rebuilt_trailing; float char_certainty = word->best_choice->certainty(blob_idx); if (char_certainty > *unlikely_threshold) { break; } if (char_certainty < *trailing_certainty) { *trailing_certainty = char_certainty; } } } /** * Try splitting off the given number of (chopped) blobs from the front and * back of the given word and recognizing the pieces. * * @param[in] num_chopped_leading how many chopped blobs from the left * end of the word to chop off and try recognizing as a * superscript (or subscript) * @param[in] leading_certainty the (minimum) certainty had by the * characters in the original leading section. * @param[in] leading_pos "super" or "sub" (for debugging) * @param[in] num_chopped_trailing how many chopped blobs from the right * end of the word to chop off and try recognizing as a * superscript (or subscript) * @param[in] trailing_certainty the (minimum) certainty had by the * characters in the original trailing section. * @param[in] trailing_pos "super" or "sub" (for debugging) * @param[in] word the word to try to chop up. * @param[out] is_good do we believe our result? * @param[out] retry_rebuild_leading, retry_rebuild_trailing * If non-zero, and !is_good, then the caller may have luck trying * to split the returned word with this number of (rebuilt) leading * and trailing blobs / unichars. * @return A word which is the result of re-recognizing as asked. */ WERD_RES *Tesseract::TrySuperscriptSplits( int num_chopped_leading, float leading_certainty, ScriptPos leading_pos, int num_chopped_trailing, float trailing_certainty, ScriptPos trailing_pos, WERD_RES *word, bool *is_good, int *retry_rebuild_leading, int *retry_rebuild_trailing) { int num_chopped = word->chopped_word->NumBlobs(); *retry_rebuild_leading = *retry_rebuild_trailing = 0; // Chop apart the word into up to three pieces. BlamerBundle *bb0 = NULL; BlamerBundle *bb1 = NULL; WERD_RES *prefix = NULL; WERD_RES *core = NULL; WERD_RES *suffix = NULL; if (num_chopped_leading > 0) { prefix = new WERD_RES(*word); split_word(prefix, num_chopped_leading, &core, &bb0); } else { core = new WERD_RES(*word); } if (num_chopped_trailing > 0) { int split_pt = num_chopped - num_chopped_trailing - num_chopped_leading; split_word(core, split_pt, &suffix, &bb1); } // Recognize the pieces in turn. int saved_cp_multiplier = classify_class_pruner_multiplier; int saved_im_multiplier = classify_integer_matcher_multiplier; if (prefix) { // Turn off Tesseract's y-position penalties for the leading superscript. classify_class_pruner_multiplier.set_value(0); classify_integer_matcher_multiplier.set_value(0); // Adjust our expectations about the baseline for this prefix. if (superscript_debug >= 3) { tprintf(" recognizing first %d chopped blobs\n", num_chopped_leading); } recog_word_recursive(prefix); if (superscript_debug >= 2) { tprintf(" The leading bits look like %s %s\n", ScriptPosToString(leading_pos), prefix->best_choice->unichar_string().string()); } // Restore the normal y-position penalties. classify_class_pruner_multiplier.set_value(saved_cp_multiplier); classify_integer_matcher_multiplier.set_value(saved_im_multiplier); } if (superscript_debug >= 3) { tprintf(" recognizing middle %d chopped blobs\n", num_chopped - num_chopped_leading - num_chopped_trailing); } if (suffix) { // Turn off Tesseract's y-position penalties for the trailing superscript. classify_class_pruner_multiplier.set_value(0); classify_integer_matcher_multiplier.set_value(0); if (superscript_debug >= 3) { tprintf(" recognizing last %d chopped blobs\n", num_chopped_trailing); } recog_word_recursive(suffix); if (superscript_debug >= 2) { tprintf(" The trailing bits look like %s %s\n", ScriptPosToString(trailing_pos), suffix->best_choice->unichar_string().string()); } // Restore the normal y-position penalties. classify_class_pruner_multiplier.set_value(saved_cp_multiplier); classify_integer_matcher_multiplier.set_value(saved_im_multiplier); } // Evaluate whether we think the results are believably better // than what we already had. bool good_prefix = !prefix || BelievableSuperscript( superscript_debug >= 1, *prefix, superscript_bettered_certainty * leading_certainty, retry_rebuild_leading, NULL); bool good_suffix = !suffix || BelievableSuperscript( superscript_debug >= 1, *suffix, superscript_bettered_certainty * trailing_certainty, NULL, retry_rebuild_trailing); *is_good = good_prefix && good_suffix; if (!*is_good && !*retry_rebuild_leading && !*retry_rebuild_trailing) { // None of it is any good. Quit now. delete core; delete prefix; delete suffix; return NULL; } recog_word_recursive(core); // Now paste the results together into core. if (suffix) { suffix->SetAllScriptPositions(trailing_pos); join_words(core, suffix, bb1); } if (prefix) { prefix->SetAllScriptPositions(leading_pos); join_words(prefix, core, bb0); core = prefix; prefix = NULL; } if (superscript_debug >= 1) { tprintf("%s superscript fix: %s\n", *is_good ? "ACCEPT" : "REJECT", core->best_choice->unichar_string().string()); } return core; } /** * Return whether this is believable superscript or subscript text. * * We insist that: * + there are no punctuation marks. * + there are no italics. * + no normal-sized character is smaller than superscript_scaledown_ratio * of what it ought to be, and * + each character is at least as certain as certainty_threshold. * * @param[in] debug If true, spew debug output * @param[in] word The word whose best_choice we're evaluating * @param[in] certainty_threshold If any of the characters have less * certainty than this, reject. * @param[out] left_ok How many left-side characters were ok? * @param[out] right_ok How many right-side characters were ok? * @return Whether the complete best choice is believable as a superscript. */ bool Tesseract::BelievableSuperscript(bool debug, const WERD_RES &word, float certainty_threshold, int *left_ok, int *right_ok) const { int initial_ok_run_count = 0; int ok_run_count = 0; float worst_certainty = 0.0f; const WERD_CHOICE &wc = *word.best_choice; const UnicityTable<FontInfo>& fontinfo_table = get_fontinfo_table(); for (int i = 0; i < wc.length(); i++) { TBLOB *blob = word.rebuild_word->blobs[i]; UNICHAR_ID unichar_id = wc.unichar_id(i); float char_certainty = wc.certainty(i); bool bad_certainty = char_certainty < certainty_threshold; bool is_punc = wc.unicharset()->get_ispunctuation(unichar_id); bool is_italic = word.fontinfo && word.fontinfo->is_italic(); BLOB_CHOICE *choice = word.GetBlobChoice(i); if (choice && fontinfo_table.size() > 0) { // Get better information from the specific choice, if available. int font_id1 = choice->fontinfo_id(); bool font1_is_italic = font_id1 >= 0 ? fontinfo_table.get(font_id1).is_italic() : false; int font_id2 = choice->fontinfo_id2(); is_italic = font1_is_italic && (font_id2 < 0 || fontinfo_table.get(font_id2).is_italic()); } float height_fraction = 1.0f; float char_height = blob->bounding_box().height(); float normal_height = char_height; if (wc.unicharset()->top_bottom_useful()) { int min_bot, max_bot, min_top, max_top; wc.unicharset()->get_top_bottom(unichar_id, &min_bot, &max_bot, &min_top, &max_top); float hi_height = max_top - max_bot; float lo_height = min_top - min_bot; normal_height = (hi_height + lo_height) / 2; if (normal_height >= kBlnXHeight) { // Only ding characters that we have decent information for because // they're supposed to be normal sized, not tiny specks or dashes. height_fraction = char_height / normal_height; } } bool bad_height = height_fraction < superscript_scaledown_ratio; if (debug) { if (is_italic) { tprintf(" Rejecting: superscript is italic.\n"); } if (is_punc) { tprintf(" Rejecting: punctuation present.\n"); } const char *char_str = wc.unicharset()->id_to_unichar(unichar_id); if (bad_certainty) { tprintf(" Rejecting: don't believe character %s with certainty %.2f " "which is less than threshold %.2f\n", char_str, char_certainty, certainty_threshold); } if (bad_height) { tprintf(" Rejecting: character %s seems too small @ %.2f versus " "expected %.2f\n", char_str, char_height, normal_height); } } if (bad_certainty || bad_height || is_punc || is_italic) { if (ok_run_count == i) { initial_ok_run_count = ok_run_count; } ok_run_count = 0; } else { ok_run_count++; } if (char_certainty < worst_certainty) { worst_certainty = char_certainty; } } bool all_ok = ok_run_count == wc.length(); if (all_ok && debug) { tprintf(" Accept: worst revised certainty is %.2f\n", worst_certainty); } if (!all_ok) { if (left_ok) *left_ok = initial_ok_run_count; if (right_ok) *right_ok = ok_run_count; } return all_ok; } } // namespace tesseract
1080228-arabicocr11
ccmain/superscript.cpp
C++
asf20
23,795
/********************************************************************** * File: cube_reco_context.h * Description: Declaration of the Cube Recognition Context Class * Author: Ahmad Abdulkader * Created: 2007 * * (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. * **********************************************************************/ // The CubeRecoContext class abstracts the Cube OCR Engine. Typically a process // (or a thread) would create one CubeRecoContext object per language. // The CubeRecoContext object also provides methods to get and set the // different attribues of the Cube OCR Engine. #ifndef CUBE_RECO_CONTEXT_H #define CUBE_RECO_CONTEXT_H #include <string> #include "neural_net.h" #include "lang_model.h" #include "classifier_base.h" #include "feature_base.h" #include "char_set.h" #include "word_size_model.h" #include "char_bigrams.h" #include "word_unigrams.h" namespace tesseract { class Tesseract; class TessdataManager; class CubeRecoContext { public: // Reading order enum type enum ReadOrder { L2R, R2L }; // Instantiate using a Tesseract object CubeRecoContext(Tesseract *tess_obj); ~CubeRecoContext(); // accessor functions inline const string & Lang() const { return lang_; } inline CharSet *CharacterSet() const { return char_set_; } const UNICHARSET *TessUnicharset() const { return tess_unicharset_; } inline CharClassifier *Classifier() const { return char_classifier_; } inline WordSizeModel *SizeModel() const { return word_size_model_; } inline CharBigrams *Bigrams() const { return char_bigrams_; } inline WordUnigrams *WordUnigramsObj() const { return word_unigrams_; } inline TuningParams *Params() const { return params_; } inline LangModel *LangMod() const { return lang_mod_; } // the reading order of the language inline ReadOrder ReadingOrder() const { return ((lang_ == "ara") ? R2L : L2R); } // does the language support case inline bool HasCase() const { return (lang_ != "ara" && lang_ != "hin"); } inline bool Cursive() const { return (lang_ == "ara"); } inline bool HasItalics() const { return (lang_ != "ara" && lang_ != "hin"); } inline bool Contextual() const { return (lang_ == "ara"); } // RecoContext runtime flags accessor functions inline bool SizeNormalization() const { return size_normalization_; } inline bool NoisyInput() const { return noisy_input_; } inline bool OOD() const { return lang_mod_->OOD(); } inline bool Numeric() const { return lang_mod_->Numeric(); } inline bool WordList() const { return lang_mod_->WordList(); } inline bool Punc() const { return lang_mod_->Punc(); } inline bool CaseSensitive() const { return char_classifier_->CaseSensitive(); } inline void SetSizeNormalization(bool size_normalization) { size_normalization_ = size_normalization; } inline void SetNoisyInput(bool noisy_input) { noisy_input_ = noisy_input; } inline void SetOOD(bool ood_enabled) { lang_mod_->SetOOD(ood_enabled); } inline void SetNumeric(bool numeric_enabled) { lang_mod_->SetNumeric(numeric_enabled); } inline void SetWordList(bool word_list_enabled) { lang_mod_->SetWordList(word_list_enabled); } inline void SetPunc(bool punc_enabled) { lang_mod_->SetPunc(punc_enabled); } inline void SetCaseSensitive(bool case_sensitive) { char_classifier_->SetCaseSensitive(case_sensitive); } inline tesseract::Tesseract *TesseractObject() const { return tess_obj_; } // Returns the path of the data files bool GetDataFilePath(string *path) const; // Creates a CubeRecoContext object using a tesseract object. Data // files are loaded via the tessdata_manager, and the tesseract // unicharset is provided in order to map Cube's unicharset to // Tesseract's in the case where the two unicharsets differ. static CubeRecoContext *Create(Tesseract *tess_obj, TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset); private: bool loaded_; string lang_; CharSet *char_set_; UNICHARSET *tess_unicharset_; WordSizeModel *word_size_model_; CharClassifier *char_classifier_; CharBigrams *char_bigrams_; WordUnigrams *word_unigrams_; TuningParams *params_; LangModel *lang_mod_; Tesseract *tess_obj_; // CubeRecoContext does not own this pointer bool size_normalization_; bool noisy_input_; // Loads and initialized all the necessary components of a // CubeRecoContext. See .cpp for more details. bool Load(TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset); }; } #endif // CUBE_RECO_CONTEXT_H
1080228-arabicocr11
ccmain/cube_reco_context.h
C++
asf20
5,236
/********************************************************************** * File: pagewalk.cpp (Formerly walkers.c) * Description: Block list processors * Author: Phil Cheatle * Created: Thu Oct 10 16:25:24 BST 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. * **********************************************************************/ #include "pageres.h" #include "tesseractclass.h" /** * process_selected_words() * * Walk the current block list applying the specified word processor function * to each word that overlaps the selection_box. */ namespace tesseract { void Tesseract::process_selected_words( PAGE_RES* page_res, // blocks to check TBOX & selection_box, BOOL8(tesseract::Tesseract::*word_processor)(PAGE_RES_IT* pr_it)) { for (PAGE_RES_IT page_res_it(page_res); page_res_it.word() != NULL; page_res_it.forward()) { WERD* word = page_res_it.word()->word; if (word->bounding_box().overlap(selection_box)) { if (!(this->*word_processor)(&page_res_it)) return; } } } } // namespace tesseract
1080228-arabicocr11
ccmain/pagewalk.cpp
C++
asf20
1,636
/////////////////////////////////////////////////////////////////////// // File: resultiterator.cpp // 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. // /////////////////////////////////////////////////////////////////////// #include "resultiterator.h" #include "allheaders.h" #include "pageres.h" #include "strngs.h" #include "tesseractclass.h" #include "unicharset.h" #include "unicodes.h" namespace tesseract { ResultIterator::ResultIterator(const LTRResultIterator &resit) : LTRResultIterator(resit) { in_minor_direction_ = false; at_beginning_of_minor_run_ = false; current_paragraph_is_ltr_ = CurrentParagraphIsLtr(); MoveToLogicalStartOfTextline(); } ResultIterator *ResultIterator::StartOfParagraph( const LTRResultIterator &resit) { return new ResultIterator(resit); } bool ResultIterator::ParagraphIsLtr() const { return current_paragraph_is_ltr_; } bool ResultIterator::CurrentParagraphIsLtr() const { if (!it_->word()) return true; // doesn't matter. LTRResultIterator it(*this); it.RestartParagraph(); // Try to figure out the ltr-ness of the paragraph. The rules below // make more sense in the context of a difficult paragraph example. // Here we denote {ltr characters, RTL CHARACTERS}: // // "don't go in there!" DAIS EH // EHT OTNI DEPMUJ FELSMIH NEHT DNA // .GNIDLIUB GNINRUB // // On the first line, the left-most word is LTR and the rightmost word // is RTL. Thus, we are better off taking the majority direction for // the whole paragraph contents. So instead of "the leftmost word is LTR" // indicating an LTR paragraph, we use a heuristic about what RTL paragraphs // would not do: Typically an RTL paragraph would *not* start with an LTR // word. So our heuristics are as follows: // // (1) If the first text line has an RTL word in the left-most position // it is RTL. // (2) If the first text line has an LTR word in the right-most position // it is LTR. // (3) If neither of the above is true, take the majority count for the // paragraph -- if there are more rtl words, it is RTL. If there // are more LTR words, it's LTR. bool leftmost_rtl = it.WordDirection() == DIR_RIGHT_TO_LEFT; bool rightmost_ltr = it.WordDirection() == DIR_LEFT_TO_RIGHT; int num_ltr, num_rtl; num_rtl = leftmost_rtl ? 1 : 0; num_ltr = (it.WordDirection() == DIR_LEFT_TO_RIGHT) ? 1 : 0; for (it.Next(RIL_WORD); !it.Empty(RIL_WORD) && !it.IsAtBeginningOf(RIL_TEXTLINE); it.Next(RIL_WORD)) { StrongScriptDirection dir = it.WordDirection(); rightmost_ltr = (dir == DIR_LEFT_TO_RIGHT); num_rtl += (dir == DIR_RIGHT_TO_LEFT) ? 1 : 0; num_ltr += rightmost_ltr ? 1 : 0; } if (leftmost_rtl) return false; if (rightmost_ltr) return true; // First line is ambiguous. Take statistics on the whole paragraph. if (!it.Empty(RIL_WORD) && !it.IsAtBeginningOf(RIL_PARA)) do { StrongScriptDirection dir = it.WordDirection(); num_rtl += (dir == DIR_RIGHT_TO_LEFT) ? 1 : 0; num_ltr += (dir == DIR_LEFT_TO_RIGHT) ? 1 : 0; } while (it.Next(RIL_WORD) && !it.IsAtBeginningOf(RIL_PARA)); return num_ltr >= num_rtl; } const int ResultIterator::kMinorRunStart = -1; const int ResultIterator::kMinorRunEnd = -2; const int ResultIterator::kComplexWord = -3; void ResultIterator::CalculateBlobOrder( GenericVector<int> *blob_indices) const { bool context_is_ltr = current_paragraph_is_ltr_ ^ in_minor_direction_; blob_indices->clear(); if (Empty(RIL_WORD)) return; if (context_is_ltr || it_->word()->UnicharsInReadingOrder()) { // Easy! just return the blobs in order; for (int i = 0; i < word_length_; i++) blob_indices->push_back(i); return; } // The blobs are in left-to-right order, but the current reading context // is right-to-left. const int U_LTR = UNICHARSET::U_LEFT_TO_RIGHT; const int U_RTL = UNICHARSET::U_RIGHT_TO_LEFT; const int U_EURO_NUM = UNICHARSET::U_EUROPEAN_NUMBER; const int U_EURO_NUM_SEP = UNICHARSET::U_EUROPEAN_NUMBER_SEPARATOR; const int U_EURO_NUM_TERM = UNICHARSET::U_EUROPEAN_NUMBER_TERMINATOR; const int U_COMMON_NUM_SEP = UNICHARSET::U_COMMON_NUMBER_SEPARATOR; const int U_OTHER_NEUTRAL = UNICHARSET::U_OTHER_NEUTRAL; // Step 1: Scan for and mark European Number sequences // [:ET:]*[:EN:]+(([:ES:]|[:CS:])?[:EN:]+)*[:ET:]* GenericVector<int> letter_types; for (int i = 0; i < word_length_; i++) { letter_types.push_back(it_->word()->SymbolDirection(i)); } // Convert a single separtor sandwiched between two EN's into an EN. for (int i = 0; i + 2 < word_length_; i++) { if (letter_types[i] == U_EURO_NUM && letter_types[i + 2] == U_EURO_NUM && (letter_types[i + 1] == U_EURO_NUM_SEP || letter_types[i + 1] == U_COMMON_NUM_SEP)) { letter_types[i + 1] = U_EURO_NUM; } } // Scan for sequences of European Number Terminators around ENs and convert // them to ENs. for (int i = 0; i < word_length_; i++) { if (letter_types[i] == U_EURO_NUM_TERM) { int j = i + 1; while (j < word_length_ && letter_types[j] == U_EURO_NUM_TERM) { j++; } if (j < word_length_ && letter_types[j] == U_EURO_NUM) { // The sequence [i..j] should be converted to all European Numbers. for (int k = i; k < j; k++) letter_types[k] = U_EURO_NUM; } j = i - 1; while (j > -1 && letter_types[j] == U_EURO_NUM_TERM) { j--; } if (j > -1 && letter_types[j] == U_EURO_NUM) { // The sequence [j..i] should be converted to all European Numbers. for (int k = j; k <= i; k++) letter_types[k] = U_EURO_NUM; } } } // Step 2: Convert all remaining types to either L or R. // Sequences ([:L:]|[:EN:])+ (([:CS:]|[:ON:])+ ([:L:]|[:EN:])+)* -> L. // All other are R. for (int i = 0; i < word_length_;) { int ti = letter_types[i]; if (ti == U_LTR || ti == U_EURO_NUM) { // Left to right sequence; scan to the end of it. int last_good = i; for (int j = i + 1; j < word_length_; j++) { int tj = letter_types[j]; if (tj == U_LTR || tj == U_EURO_NUM) { last_good = j; } else if (tj == U_COMMON_NUM_SEP || tj == U_OTHER_NEUTRAL) { // do nothing. } else { break; } } // [i..last_good] is the L sequence for (int k = i; k <= last_good; k++) letter_types[k] = U_LTR; i = last_good + 1; } else { letter_types[i] = U_RTL; i++; } } // At this point, letter_types is entirely U_LTR or U_RTL. for (int i = word_length_ - 1; i >= 0;) { if (letter_types[i] == U_RTL) { blob_indices->push_back(i); i--; } else { // left to right sequence. scan to the beginning. int j = i - 1; for (; j >= 0 && letter_types[j] != U_RTL; j--) { } // pass // Now (j, i] is LTR for (int k = j + 1; k <= i; k++) blob_indices->push_back(k); i = j; } } ASSERT_HOST(blob_indices->size() == word_length_); } static void PrintScriptDirs(const GenericVector<StrongScriptDirection> &dirs) { for (int i = 0; i < dirs.size(); i++) { switch (dirs[i]) { case DIR_NEUTRAL: tprintf ("N "); break; case DIR_LEFT_TO_RIGHT: tprintf("L "); break; case DIR_RIGHT_TO_LEFT: tprintf("R "); break; case DIR_MIX: tprintf("Z "); break; default: tprintf("? "); break; } } tprintf("\n"); } void ResultIterator::CalculateTextlineOrder( bool paragraph_is_ltr, const LTRResultIterator &resit, GenericVectorEqEq<int> *word_indices) const { GenericVector<StrongScriptDirection> directions; CalculateTextlineOrder(paragraph_is_ltr, resit, &directions, word_indices); } void ResultIterator::CalculateTextlineOrder( bool paragraph_is_ltr, const LTRResultIterator &resit, GenericVector<StrongScriptDirection> *dirs_arg, GenericVectorEqEq<int> *word_indices) const { GenericVector<StrongScriptDirection> dirs; GenericVector<StrongScriptDirection> *directions; directions = (dirs_arg != NULL) ? dirs_arg : &dirs; directions->truncate(0); // A LTRResultIterator goes strictly left-to-right word order. LTRResultIterator ltr_it(resit); ltr_it.RestartRow(); if (ltr_it.Empty(RIL_WORD)) return; do { directions->push_back(ltr_it.WordDirection()); } while (ltr_it.Next(RIL_WORD) && !ltr_it.IsAtBeginningOf(RIL_TEXTLINE)); word_indices->truncate(0); CalculateTextlineOrder(paragraph_is_ltr, *directions, word_indices); } void ResultIterator::CalculateTextlineOrder( bool paragraph_is_ltr, const GenericVector<StrongScriptDirection> &word_dirs, GenericVectorEqEq<int> *reading_order) { reading_order->truncate(0); if (word_dirs.size() == 0) return; // Take all of the runs of minor direction words and insert them // in reverse order. int minor_direction, major_direction, major_step, start, end; if (paragraph_is_ltr) { start = 0; end = word_dirs.size(); major_step = 1; major_direction = DIR_LEFT_TO_RIGHT; minor_direction = DIR_RIGHT_TO_LEFT; } else { start = word_dirs.size() - 1; end = -1; major_step = -1; major_direction = DIR_RIGHT_TO_LEFT; minor_direction = DIR_LEFT_TO_RIGHT; // Special rule: if there are neutral words at the right most side // of a line adjacent to a left-to-right word in the middle of the // line, we interpret the end of the line as a single LTR sequence. if (word_dirs[start] == DIR_NEUTRAL) { int neutral_end = start; while (neutral_end > 0 && word_dirs[neutral_end] == DIR_NEUTRAL) { neutral_end--; } if (neutral_end >= 0 && word_dirs[neutral_end] == DIR_LEFT_TO_RIGHT) { // LTR followed by neutrals. // Scan for the beginning of the minor left-to-right run. int left = neutral_end; for (int i = left; i >= 0 && word_dirs[i] != DIR_RIGHT_TO_LEFT; i--) { if (word_dirs[i] == DIR_LEFT_TO_RIGHT) left = i; } reading_order->push_back(kMinorRunStart); for (int i = left; i < word_dirs.size(); i++) { reading_order->push_back(i); if (word_dirs[i] == DIR_MIX) reading_order->push_back(kComplexWord); } reading_order->push_back(kMinorRunEnd); start = left - 1; } } } for (int i = start; i != end;) { if (word_dirs[i] == minor_direction) { int j = i; while (j != end && word_dirs[j] != major_direction) j += major_step; if (j == end) j -= major_step; while (j != i && word_dirs[j] != minor_direction) j -= major_step; // [j..i] is a minor direction run. reading_order->push_back(kMinorRunStart); for (int k = j; k != i; k -= major_step) { reading_order->push_back(k); } reading_order->push_back(i); reading_order->push_back(kMinorRunEnd); i = j + major_step; } else { reading_order->push_back(i); if (word_dirs[i] == DIR_MIX) reading_order->push_back(kComplexWord); i += major_step; } } } int ResultIterator::LTRWordIndex() const { int this_word_index = 0; LTRResultIterator textline(*this); textline.RestartRow(); while (!textline.PositionedAtSameWord(it_)) { this_word_index++; textline.Next(RIL_WORD); } return this_word_index; } void ResultIterator::MoveToLogicalStartOfWord() { if (word_length_ == 0) { BeginWord(0); return; } GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); if (blob_order.size() == 0 || blob_order[0] == 0) return; BeginWord(blob_order[0]); } bool ResultIterator::IsAtFinalSymbolOfWord() const { if (!it_->word()) return true; GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); return blob_order.size() == 0 || blob_order.back() == blob_index_; } bool ResultIterator::IsAtFirstSymbolOfWord() const { if (!it_->word()) return true; GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); return blob_order.size() == 0 || blob_order[0] == blob_index_; } void ResultIterator::AppendSuffixMarks(STRING *text) const { if (!it_->word()) return; bool reading_direction_is_ltr = current_paragraph_is_ltr_ ^ in_minor_direction_; // scan forward to see what meta-information the word ordering algorithm // left us. // If this word is at the *end* of a minor run, insert the other // direction's mark; else if this was a complex word, insert the // current reading order's mark. GenericVectorEqEq<int> textline_order; CalculateTextlineOrder(current_paragraph_is_ltr_, *this, &textline_order); int this_word_index = LTRWordIndex(); int i = textline_order.get_index(this_word_index); if (i < 0) return; int last_non_word_mark = 0; for (i++; i < textline_order.size() && textline_order[i] < 0; i++) { last_non_word_mark = textline_order[i]; } if (last_non_word_mark == kComplexWord) { *text += reading_direction_is_ltr ? kLRM : kRLM; } else if (last_non_word_mark == kMinorRunEnd) { if (current_paragraph_is_ltr_) { *text += kLRM; } else { *text += kRLM; } } } void ResultIterator::MoveToLogicalStartOfTextline() { GenericVectorEqEq<int> word_indices; RestartRow(); CalculateTextlineOrder(current_paragraph_is_ltr_, dynamic_cast<const LTRResultIterator&>(*this), &word_indices); int i = 0; for (; i < word_indices.size() && word_indices[i] < 0; i++) { if (word_indices[i] == kMinorRunStart) in_minor_direction_ = true; else if (word_indices[i] == kMinorRunEnd) in_minor_direction_ = false; } if (in_minor_direction_) at_beginning_of_minor_run_ = true; if (i >= word_indices.size()) return; int first_word_index = word_indices[i]; for (int j = 0; j < first_word_index; j++) { PageIterator::Next(RIL_WORD); } MoveToLogicalStartOfWord(); } void ResultIterator::Begin() { LTRResultIterator::Begin(); current_paragraph_is_ltr_ = CurrentParagraphIsLtr(); in_minor_direction_ = false; at_beginning_of_minor_run_ = false; MoveToLogicalStartOfTextline(); } bool ResultIterator::Next(PageIteratorLevel level) { if (it_->block() == NULL) return false; // already at end! switch (level) { case RIL_BLOCK: // explicit fall-through case RIL_PARA: // explicit fall-through case RIL_TEXTLINE: if (!PageIterator::Next(level)) return false; if (IsWithinFirstTextlineOfParagraph()) { // if we've advanced to a new paragraph, // recalculate current_paragraph_is_ltr_ current_paragraph_is_ltr_ = CurrentParagraphIsLtr(); } in_minor_direction_ = false; MoveToLogicalStartOfTextline(); return it_->block() != NULL; case RIL_SYMBOL: { GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); int next_blob = 0; while (next_blob < blob_order.size() && blob_index_ != blob_order[next_blob]) next_blob++; next_blob++; if (next_blob < blob_order.size()) { // we're in the same word; simply advance one blob. BeginWord(blob_order[next_blob]); at_beginning_of_minor_run_ = false; return true; } level = RIL_WORD; // we've fallen through to the next word. } case RIL_WORD: // explicit fall-through. { if (it_->word() == NULL) return Next(RIL_BLOCK); GenericVectorEqEq<int> word_indices; int this_word_index = LTRWordIndex(); CalculateTextlineOrder(current_paragraph_is_ltr_, *this, &word_indices); int final_real_index = word_indices.size() - 1; while (final_real_index > 0 && word_indices[final_real_index] < 0) final_real_index--; for (int i = 0; i < final_real_index; i++) { if (word_indices[i] == this_word_index) { int j = i + 1; for (; j < final_real_index && word_indices[j] < 0; j++) { if (word_indices[j] == kMinorRunStart) in_minor_direction_ = true; if (word_indices[j] == kMinorRunEnd) in_minor_direction_ = false; } at_beginning_of_minor_run_ = (word_indices[j - 1] == kMinorRunStart); // awesome, we move to word_indices[j] if (BidiDebug(3)) { tprintf("Next(RIL_WORD): %d -> %d\n", this_word_index, word_indices[j]); } PageIterator::RestartRow(); for (int k = 0; k < word_indices[j]; k++) { PageIterator::Next(RIL_WORD); } MoveToLogicalStartOfWord(); return true; } } if (BidiDebug(3)) { tprintf("Next(RIL_WORD): %d -> EOL\n", this_word_index); } // we're going off the end of the text line. return Next(RIL_TEXTLINE); } } ASSERT_HOST(false); // shouldn't happen. return false; } bool ResultIterator::IsAtBeginningOf(PageIteratorLevel level) const { if (it_->block() == NULL) return false; // Already at the end! if (it_->word() == NULL) return true; // In an image block. if (level == RIL_SYMBOL) return true; // Always at beginning of a symbol. bool at_word_start = IsAtFirstSymbolOfWord(); if (level == RIL_WORD) return at_word_start; ResultIterator line_start(*this); // move to the first word in the line... line_start.MoveToLogicalStartOfTextline(); bool at_textline_start = at_word_start && *line_start.it_ == *it_; if (level == RIL_TEXTLINE) return at_textline_start; // now we move to the left-most word... line_start.RestartRow(); bool at_block_start = at_textline_start && line_start.it_->block() != line_start.it_->prev_block(); if (level == RIL_BLOCK) return at_block_start; bool at_para_start = at_block_start || (at_textline_start && line_start.it_->row()->row->para() != line_start.it_->prev_row()->row->para()); if (level == RIL_PARA) return at_para_start; ASSERT_HOST(false); // shouldn't happen. return false; } /** * NOTE! This is an exact copy of PageIterator::IsAtFinalElement with the * change that the variable next is now a ResultIterator instead of a * PageIterator. */ bool ResultIterator::IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const { if (Empty(element)) return true; // Already at the end! // The result is true if we step forward by element and find we are // at the the end of the page or at beginning of *all* levels in: // [level, element). // When there is more than one level difference between element and level, // we could for instance move forward one symbol and still be at the first // word on a line, so we also have to be at the first symbol in a word. ResultIterator next(*this); next.Next(element); if (next.Empty(element)) return true; // Reached the end of the page. while (element > level) { element = static_cast<PageIteratorLevel>(element - 1); if (!next.IsAtBeginningOf(element)) return false; } return true; } /** * Returns the null terminated UTF-8 encoded text string for the current * object at the given level. Use delete [] to free after use. */ char* ResultIterator::GetUTF8Text(PageIteratorLevel level) const { if (it_->word() == NULL) return NULL; // Already at the end! STRING text; switch (level) { case RIL_BLOCK: { ResultIterator pp(*this); do { pp.AppendUTF8ParagraphText(&text); } while (pp.Next(RIL_PARA) && pp.it_->block() == it_->block()); } break; case RIL_PARA: AppendUTF8ParagraphText(&text); break; case RIL_TEXTLINE: { ResultIterator it(*this); it.MoveToLogicalStartOfTextline(); it.IterateAndAppendUTF8TextlineText(&text); } break; case RIL_WORD: AppendUTF8WordText(&text); break; case RIL_SYMBOL: { bool reading_direction_is_ltr = current_paragraph_is_ltr_ ^ in_minor_direction_; if (at_beginning_of_minor_run_) { text += reading_direction_is_ltr ? kLRM : kRLM; } text = it_->word()->BestUTF8(blob_index_, !reading_direction_is_ltr); if (IsAtFinalSymbolOfWord()) AppendSuffixMarks(&text); } break; } int length = text.length() + 1; char* result = new char[length]; strncpy(result, text.string(), length); return result; } void ResultIterator::AppendUTF8WordText(STRING *text) const { if (!it_->word()) return; ASSERT_HOST(it_->word()->best_choice != NULL); bool reading_direction_is_ltr = current_paragraph_is_ltr_ ^ in_minor_direction_; if (at_beginning_of_minor_run_) { *text += reading_direction_is_ltr ? kLRM : kRLM; } GenericVector<int> blob_order; CalculateBlobOrder(&blob_order); for (int i = 0; i < blob_order.size(); i++) { *text += it_->word()->BestUTF8(blob_order[i], !reading_direction_is_ltr); } AppendSuffixMarks(text); } void ResultIterator::IterateAndAppendUTF8TextlineText(STRING *text) { if (Empty(RIL_WORD)) { Next(RIL_WORD); return; } if (BidiDebug(1)) { GenericVectorEqEq<int> textline_order; GenericVector<StrongScriptDirection> dirs; CalculateTextlineOrder(current_paragraph_is_ltr_, *this, &dirs, &textline_order); tprintf("Strong Script dirs [%p/P=%s]: ", it_->row(), current_paragraph_is_ltr_ ? "ltr" : "rtl"); PrintScriptDirs(dirs); tprintf("Logical textline order [%p/P=%s]: ", it_->row(), current_paragraph_is_ltr_ ? "ltr" : "rtl"); for (int i = 0; i < textline_order.size(); i++) { tprintf("%d ", textline_order[i]); } tprintf("\n"); } int words_appended = 0; do { AppendUTF8WordText(text); words_appended++; *text += " "; } while (Next(RIL_WORD) && !IsAtBeginningOf(RIL_TEXTLINE)); if (BidiDebug(1)) { tprintf("%d words printed\n", words_appended); } text->truncate_at(text->length() - 1); *text += line_separator_; // If we just finished a paragraph, add an extra newline. if (it_->block() == NULL || IsAtBeginningOf(RIL_PARA)) *text += paragraph_separator_; } void ResultIterator::AppendUTF8ParagraphText(STRING *text) const { ResultIterator it(*this); it.RestartParagraph(); it.MoveToLogicalStartOfTextline(); if (it.Empty(RIL_WORD)) return; do { it.IterateAndAppendUTF8TextlineText(text); } while (it.it_->block() != NULL && !it.IsAtBeginningOf(RIL_PARA)); } bool ResultIterator::BidiDebug(int min_level) const { int debug_level = 1; IntParam *p = ParamUtils::FindParam<IntParam>( "bidi_debug", GlobalParams()->int_params, tesseract_->params()->int_params); if (p != NULL) debug_level = (inT32)(*p); return debug_level >= min_level; } } // namespace tesseract.
1080228-arabicocr11
ccmain/resultiterator.cpp
C++
asf20
23,701
/////////////////////////////////////////////////////////////////////// // File: par_control.cpp // Description: Control code for parallel implementation. // Author: Ray Smith // Created: Mon Nov 04 13:23:15 PST 2013 // // (C) Copyright 2013, 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. // /////////////////////////////////////////////////////////////////////// #include "tesseractclass.h" namespace tesseract { struct BlobData { BlobData() : blob(NULL), choices(NULL) {} BlobData(int index, Tesseract* tess, const WERD_RES& word) : blob(word.chopped_word->blobs[index]), tesseract(tess), choices(&(*word.ratings)(index, index)) {} TBLOB* blob; Tesseract* tesseract; BLOB_CHOICE_LIST** choices; }; void Tesseract::PrerecAllWordsPar(const GenericVector<WordData>& words) { // Prepare all the blobs. GenericVector<BlobData> blobs; for (int w = 0; w < words.size(); ++w) { if (words[w].word->ratings != NULL && words[w].word->ratings->get(0, 0) == NULL) { for (int s = 0; s < words[w].lang_words.size(); ++s) { Tesseract* sub = s < sub_langs_.size() ? sub_langs_[s] : this; const WERD_RES& word = *words[w].lang_words[s]; for (int b = 0; b < word.chopped_word->NumBlobs(); ++b) { blobs.push_back(BlobData(b, sub, word)); } } } } // Pre-classify all the blobs. if (tessedit_parallelize > 1) { #pragma omp parallel for num_threads(10) for (int b = 0; b < blobs.size(); ++b) { *blobs[b].choices = blobs[b].tesseract->classify_blob(blobs[b].blob, "par", White, NULL); } } else { // TODO(AMD) parallelize this. for (int b = 0; b < blobs.size(); ++b) { *blobs[b].choices = blobs[b].tesseract->classify_blob(blobs[b].blob, "par", White, NULL); } } } } // namespace tesseract.
1080228-arabicocr11
ccmain/par_control.cpp
C++
asf20
2,372
/********************************************************************** * File: wordit.c * Description: An iterator for passing over all the words in a document. * Author: Ray Smith * Created: Mon Apr 27 08:51:22 BST 1992 * * (C) Copyright 1992, 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 WERDIT_H #define WERDIT_H #include "pageres.h" PAGE_RES_IT* make_pseudo_word(PAGE_RES* page_res, const TBOX& selection_box); #endif
1080228-arabicocr11
ccmain/werdit.h
C
asf20
1,080
/////////////////////////////////////////////////////////////////////// // File: mutableiterator.h // Description: Iterator for tesseract results providing access to // both high-level API and Tesseract internal data structures. // Author: David Eger // Created: Thu Feb 24 19:01: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_MUTABLEITERATOR_H__ #define TESSERACT_CCMAIN_MUTABLEITERATOR_H__ #include "resultiterator.h" class BLOB_CHOICE_IT; 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. // ResultIterator adds text-specific methods for access to OCR output. // MutableIterator adds access to internal data structures. class MutableIterator : public ResultIterator { public: // See argument descriptions in ResultIterator() MutableIterator(PAGE_RES* page_res, Tesseract* tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height) : ResultIterator( LTRResultIterator(page_res, tesseract, scale, scaled_yres, rect_left, rect_top, rect_width, rect_height)) {} virtual ~MutableIterator() {} // See PageIterator and ResultIterator for most calls. // Return access to Tesseract internals. const PAGE_RES_IT *PageResIt() const { return it_; } }; } // namespace tesseract. #endif // TESSERACT_CCMAIN_MUTABLEITERATOR_H__
1080228-arabicocr11
ccmain/mutableiterator.h
C++
asf20
2,671
/////////////////////////////////////////////////////////////////////// // File: recogtraining.cpp // Description: Functions for ambiguity and parameter training. // Author: Daria Antonova // Created: Mon Aug 13 11:26:43 PDT 2009 // // (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. // /////////////////////////////////////////////////////////////////////// #include "tesseractclass.h" #include "boxread.h" #include "control.h" #include "cutil.h" #include "host.h" #include "ratngs.h" #include "reject.h" #include "stopper.h" namespace tesseract { const inT16 kMaxBoxEdgeDiff = 2; // Sets flags necessary for recognition in the training mode. // Opens and returns the pointer to the output file. FILE *Tesseract::init_recog_training(const STRING &fname) { if (tessedit_ambigs_training) { tessedit_tess_adaption_mode.set_value(0); // turn off adaption tessedit_enable_doc_dict.set_value(0); // turn off document dictionary // Explore all segmentations. getDict().stopper_no_acceptable_choices.set_value(1); } STRING output_fname = fname; const char *lastdot = strrchr(output_fname.string(), '.'); if (lastdot != NULL) output_fname[lastdot - output_fname.string()] = '\0'; output_fname += ".txt"; FILE *output_file = open_file(output_fname.string(), "a+"); return output_file; } // Copies the bounding box from page_res_it->word() to the given TBOX. bool read_t(PAGE_RES_IT *page_res_it, TBOX *tbox) { while (page_res_it->block() != NULL && page_res_it->word() == NULL) page_res_it->forward(); if (page_res_it->word() != NULL) { *tbox = page_res_it->word()->word->bounding_box(); // If tbox->left() is negative, the training image has vertical text and // all the coordinates of bounding boxes of page_res are rotated by 90 // degrees in a counterclockwise direction. We need to rotate the TBOX back // in order to compare with the TBOXes of box files. if (tbox->left() < 0) { tbox->rotate(FCOORD(0.0, -1.0)); } return true; } else { return false; } } // This function takes tif/box pair of files and runs recognition on the image, // while making sure that the word bounds that tesseract identified roughly // match to those specified by the input box file. For each word (ngram in a // single bounding box from the input box file) it outputs the ocred result, // the correct label, rating and certainty. void Tesseract::recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file) { STRING box_fname = fname; const char *lastdot = strrchr(box_fname.string(), '.'); if (lastdot != NULL) box_fname[lastdot - box_fname.string()] = '\0'; box_fname += ".box"; // read_next_box() will close box_file FILE *box_file = open_file(box_fname.string(), "r"); PAGE_RES_IT page_res_it; page_res_it.page_res = page_res; page_res_it.restart_page(); STRING label; // Process all the words on this page. TBOX tbox; // tesseract-identified box TBOX bbox; // box from the box file bool keep_going; int line_number = 0; int examined_words = 0; do { keep_going = read_t(&page_res_it, &tbox); keep_going &= ReadNextBox(applybox_page, &line_number, box_file, &label, &bbox); // Align bottom left points of the TBOXes. while (keep_going && !NearlyEqual<int>(tbox.bottom(), bbox.bottom(), kMaxBoxEdgeDiff)) { if (bbox.bottom() < tbox.bottom()) { page_res_it.forward(); keep_going = read_t(&page_res_it, &tbox); } else { keep_going = ReadNextBox(applybox_page, &line_number, box_file, &label, &bbox); } } while (keep_going && !NearlyEqual<int>(tbox.left(), bbox.left(), kMaxBoxEdgeDiff)) { if (bbox.left() > tbox.left()) { page_res_it.forward(); keep_going = read_t(&page_res_it, &tbox); } else { keep_going = ReadNextBox(applybox_page, &line_number, box_file, &label, &bbox); } } // OCR the word if top right points of the TBOXes are similar. if (keep_going && NearlyEqual<int>(tbox.right(), bbox.right(), kMaxBoxEdgeDiff) && NearlyEqual<int>(tbox.top(), bbox.top(), kMaxBoxEdgeDiff)) { ambigs_classify_and_output(label.string(), &page_res_it, output_file); examined_words++; } page_res_it.forward(); } while (keep_going); fclose(box_file); // Set up scripts on all of the words that did not get sent to // ambigs_classify_and_output. They all should have, but if all the // werd_res's don't get uch_sets, tesseract will crash when you try // to iterate over them. :-( int total_words = 0; for (page_res_it.restart_page(); page_res_it.block() != NULL; page_res_it.forward()) { if (page_res_it.word()) { if (page_res_it.word()->uch_set == NULL) page_res_it.word()->SetupFake(unicharset); total_words++; } } if (examined_words < 0.85 * total_words) { tprintf("TODO(antonova): clean up recog_training_segmented; " " It examined only a small fraction of the ambigs image.\n"); } tprintf("recog_training_segmented: examined %d / %d words.\n", examined_words, total_words); } // Helper prints the given set of blob choices. static void PrintPath(int length, const BLOB_CHOICE** blob_choices, const UNICHARSET& unicharset, const char *label, FILE *output_file) { float rating = 0.0f; float certainty = 0.0f; for (int i = 0; i < length; ++i) { const BLOB_CHOICE* blob_choice = blob_choices[i]; fprintf(output_file, "%s", unicharset.id_to_unichar(blob_choice->unichar_id())); rating += blob_choice->rating(); if (certainty > blob_choice->certainty()) certainty = blob_choice->certainty(); } fprintf(output_file, "\t%s\t%.4f\t%.4f\n", label, rating, certainty); } // Helper recursively prints all paths through the ratings matrix, starting // at column col. static void PrintMatrixPaths(int col, int dim, const MATRIX& ratings, int length, const BLOB_CHOICE** blob_choices, const UNICHARSET& unicharset, const char *label, FILE *output_file) { for (int row = col; row < dim && row - col < ratings.bandwidth(); ++row) { if (ratings.get(col, row) != NOT_CLASSIFIED) { BLOB_CHOICE_IT bc_it(ratings.get(col, row)); for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) { blob_choices[length] = bc_it.data(); if (row + 1 < dim) { PrintMatrixPaths(row + 1, dim, ratings, length + 1, blob_choices, unicharset, label, output_file); } else { PrintPath(length + 1, blob_choices, unicharset, label, output_file); } } } } } // Runs classify_word_pass1() on the current word. Outputs Tesseract's // raw choice as a result of the classification. For words labeled with a // single unichar also outputs all alternatives from blob_choices of the // best choice. void Tesseract::ambigs_classify_and_output(const char *label, PAGE_RES_IT* pr_it, FILE *output_file) { // Classify word. fflush(stdout); WordData word_data(*pr_it); SetupWordPassN(1, &word_data); classify_word_and_language(&Tesseract::classify_word_pass1, pr_it, &word_data); WERD_RES* werd_res = word_data.word; WERD_CHOICE *best_choice = werd_res->best_choice; ASSERT_HOST(best_choice != NULL); // Compute the number of unichars in the label. GenericVector<UNICHAR_ID> encoding; if (!unicharset.encode_string(label, true, &encoding, NULL, NULL)) { tprintf("Not outputting illegal unichar %s\n", label); return; } // Dump all paths through the ratings matrix (which is normally small). int dim = werd_res->ratings->dimension(); const BLOB_CHOICE** blob_choices = new const BLOB_CHOICE*[dim]; PrintMatrixPaths(0, dim, *werd_res->ratings, 0, blob_choices, unicharset, label, output_file); delete [] blob_choices; } } // namespace tesseract
1080228-arabicocr11
ccmain/recogtraining.cpp
C++
asf20
8,998
/********************************************************************** * File: tessbox.h (Formerly tessbox.h) * Description: Black boxed Tess for developing a resaljet. * Author: Ray Smith * Created: Thu Apr 23 11:03:36 BST 1992 * * (C) Copyright 1992, 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 TESSBOX_H #define TESSBOX_H #include "ratngs.h" #include "tesseractclass.h" // TODO(ocr-team): Delete this along with other empty header files. #endif
1080228-arabicocr11
ccmain/tessbox.h
C
asf20
1,119
/********************************************************************** * File: paragraphs.h * Description: Paragraph Detection internal data structures. * Author: David Eger * Created: 11 March 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_PARAGRAPHS_INTERNAL_H_ #define TESSERACT_CCMAIN_PARAGRAPHS_INTERNAL_H_ #include "paragraphs.h" #ifdef _MSC_VER #include <string> #else #include "strings.h" #endif // NO CODE OUTSIDE OF paragraphs.cpp AND TESTS SHOULD NEED TO ACCESS // DATA STRUCTURES OR FUNCTIONS IN THIS FILE. class WERD_CHOICE; namespace tesseract { // Return whether the given word is likely to be a list item start word. bool AsciiLikelyListItem(const STRING &word); // Return the first Unicode Codepoint from werd[pos]. int UnicodeFor(const UNICHARSET *u, const WERD_CHOICE *werd, int pos); // Set right word attributes given either a unicharset and werd or a utf8 // string. void RightWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd, const STRING &utf8, bool *is_list, bool *starts_idea, bool *ends_idea); // Set left word attributes given either a unicharset and werd or a utf8 string. void LeftWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd, const STRING &utf8, bool *is_list, bool *starts_idea, bool *ends_idea); enum LineType { LT_START = 'S', // First line of a paragraph. LT_BODY = 'C', // Continuation line of a paragraph. LT_UNKNOWN = 'U', // No clues. LT_MULTIPLE = 'M', // Matches for both LT_START and LT_BODY. }; // The first paragraph in a page of body text is often un-indented. // This is a typographic convention which is common to indicate either that: // (1) The paragraph is the continuation of a previous paragraph, or // (2) The paragraph is the first paragraph in a chapter. // // I refer to such paragraphs as "crown"s, and the output of the paragraph // detection algorithm attempts to give them the same paragraph model as // the rest of the body text. // // Nonetheless, while building hypotheses, it is useful to mark the lines // of crown paragraphs temporarily as crowns, either aligned left or right. extern const ParagraphModel *kCrownLeft; extern const ParagraphModel *kCrownRight; inline bool StrongModel(const ParagraphModel *model) { return model != NULL && model != kCrownLeft && model != kCrownRight; } struct LineHypothesis { LineHypothesis() : ty(LT_UNKNOWN), model(NULL) {} LineHypothesis(LineType line_type, const ParagraphModel *m) : ty(line_type), model(m) {} LineHypothesis(const LineHypothesis &other) : ty(other.ty), model(other.model) {} bool operator==(const LineHypothesis &other) const { return ty == other.ty && model == other.model; } LineType ty; const ParagraphModel *model; }; class ParagraphTheory; // Forward Declaration typedef GenericVectorEqEq<const ParagraphModel *> SetOfModels; // Row Scratch Registers are data generated by the paragraph detection // algorithm based on a RowInfo input. class RowScratchRegisters { public: // We presume row will outlive us. void Init(const RowInfo &row); LineType GetLineType() const; LineType GetLineType(const ParagraphModel *model) const; // Mark this as a start line type, sans model. This is useful for the // initial marking of probable body lines or paragraph start lines. void SetStartLine(); // Mark this as a body line type, sans model. This is useful for the // initial marking of probably body lines or paragraph start lines. void SetBodyLine(); // Record that this row fits as a paragraph start line in the given model, void AddStartLine(const ParagraphModel *model); // Record that this row fits as a paragraph body line in the given model, void AddBodyLine(const ParagraphModel *model); // Clear all hypotheses about this line. void SetUnknown() { hypotheses_.truncate(0); } // Append all hypotheses of strong models that match this row as a start. void StartHypotheses(SetOfModels *models) const; // Append all hypotheses of strong models matching this row. void StrongHypotheses(SetOfModels *models) const; // Append all hypotheses for this row. void NonNullHypotheses(SetOfModels *models) const; // Discard any hypotheses whose model is not in the given list. void DiscardNonMatchingHypotheses(const SetOfModels &models); // If we have only one hypothesis and that is that this line is a paragraph // start line of a certain model, return that model. Else return NULL. const ParagraphModel *UniqueStartHypothesis() const; // If we have only one hypothesis and that is that this line is a paragraph // body line of a certain model, return that model. Else return NULL. const ParagraphModel *UniqueBodyHypothesis() const; // Return the indentation for the side opposite of the aligned side. int OffsideIndent(tesseract::ParagraphJustification just) const { switch (just) { case tesseract::JUSTIFICATION_RIGHT: return lindent_; case tesseract::JUSTIFICATION_LEFT: return rindent_; default: return lindent_ > rindent_ ? lindent_ : rindent_; } } // Return the indentation for the side the text is aligned to. int AlignsideIndent(tesseract::ParagraphJustification just) const { switch (just) { case tesseract::JUSTIFICATION_RIGHT: return rindent_; case tesseract::JUSTIFICATION_LEFT: return lindent_; default: return lindent_ > rindent_ ? lindent_ : rindent_; } } // Append header fields to a vector of row headings. static void AppendDebugHeaderFields(GenericVector<STRING> *header); // Append data for this row to a vector of debug strings. void AppendDebugInfo(const ParagraphTheory &theory, GenericVector<STRING> *dbg) const; const RowInfo *ri_; // These four constants form a horizontal box model for the white space // on the edges of each line. At each point in the algorithm, the following // shall hold: // ri_->pix_ldistance = lmargin_ + lindent_ // ri_->pix_rdistance = rindent_ + rmargin_ int lmargin_; int lindent_; int rindent_; int rmargin_; private: // Hypotheses of either LT_START or LT_BODY GenericVectorEqEq<LineHypothesis> hypotheses_; }; // A collection of convenience functions for wrapping the set of // Paragraph Models we believe correctly model the paragraphs in the image. class ParagraphTheory { public: // We presume models will outlive us, and that models will take ownership // of any ParagraphModel *'s we add. explicit ParagraphTheory(GenericVector<ParagraphModel *> *models) : models_(models) {} GenericVector<ParagraphModel *> &models() { return *models_; } const GenericVector<ParagraphModel *> &models() const { return *models_; } // Return an existing model if one that is Comparable() can be found. // Else, allocate a new copy of model to save and return a pointer to it. const ParagraphModel *AddModel(const ParagraphModel &model); // Discard any models we've made that are not in the list of used models. void DiscardUnusedModels(const SetOfModels &used_models); // Return the set of all non-centered models. void NonCenteredModels(SetOfModels *models); // If any of the non-centered paragraph models we know about fit // rows[start, end), return it. Else NULL. const ParagraphModel *Fits(const GenericVector<RowScratchRegisters> *rows, int start, int end) const; int IndexOf(const ParagraphModel *model) const; private: GenericVector<ParagraphModel *> *models_; GenericVectorEqEq<ParagraphModel *> models_we_added_; }; bool ValidFirstLine(const GenericVector<RowScratchRegisters> *rows, int row, const ParagraphModel *model); bool ValidBodyLine(const GenericVector<RowScratchRegisters> *rows, int row, const ParagraphModel *model); bool CrownCompatible(const GenericVector<RowScratchRegisters> *rows, int a, int b, const ParagraphModel *model); // A class for smearing Paragraph Model hypotheses to surrounding rows. // The idea here is that StrongEvidenceClassify first marks only exceedingly // obvious start and body rows and constructs models of them. Thereafter, // we may have left over unmarked lines (mostly end-of-paragraph lines) which // were too short to have much confidence about, but which fit the models we've // constructed perfectly and which we ought to mark. This class is used to // "smear" our models over the text. class ParagraphModelSmearer { public: ParagraphModelSmearer(GenericVector<RowScratchRegisters> *rows, int row_start, int row_end, ParagraphTheory *theory); // Smear forward paragraph models from existing row markings to subsequent // text lines if they fit, and mark any thereafter still unmodeled rows // with any model in the theory that fits them. void Smear(); private: // Record in open_models_ for rows [start_row, end_row) the list of models // currently open at each row. // A model is still open in a row if some previous row has said model as a // start hypothesis, and all rows since (including this row) would fit as // either a body or start line in that model. void CalculateOpenModels(int row_start, int row_end); SetOfModels &OpenModels(int row) { return open_models_[row - row_start_ + 1]; } ParagraphTheory *theory_; GenericVector<RowScratchRegisters> *rows_; int row_start_; int row_end_; // open_models_ corresponds to rows[start_row_ - 1, end_row_] // // open_models_: Contains models which there was an active (open) paragraph // as of the previous line and for which the left and right // indents admit the possibility that this text line continues // to fit the same model. // TODO(eger): Think about whether we can get rid of "Open" models and just // use the current hypotheses on RowScratchRegisters. GenericVector<SetOfModels> open_models_; }; // Clear all hypotheses about lines [start, end) and reset the margins to the // percentile (0..100) value of the left and right row edges for this run of // rows. void RecomputeMarginsAndClearHypotheses( GenericVector<RowScratchRegisters> *rows, int start, int end, int percentile); // Return the median inter-word space in rows[row_start, row_end). int InterwordSpace(const GenericVector<RowScratchRegisters> &rows, int row_start, int row_end); // Return whether the first word on the after line can fit in the space at // the end of the before line (knowing which way the text is aligned and read). bool FirstWordWouldHaveFit(const RowScratchRegisters &before, const RowScratchRegisters &after, tesseract::ParagraphJustification justification); // Return whether the first word on the after line can fit in the space at // the end of the before line (not knowing the text alignment). bool FirstWordWouldHaveFit(const RowScratchRegisters &before, const RowScratchRegisters &after); // Do rows[start, end) form a single instance of the given paragraph model? bool RowsFitModel(const GenericVector<RowScratchRegisters> *rows, int start, int end, const ParagraphModel *model); // Do the text and geometry of two rows support a paragraph break between them? bool LikelyParagraphStart(const RowScratchRegisters &before, const RowScratchRegisters &after, tesseract::ParagraphJustification j); // Given a set of row_owners pointing to PARAs or NULL (no paragraph known), // normalize each row_owner to point to an actual PARA, and output the // paragraphs in order onto paragraphs. void CanonicalizeDetectionResults( GenericVector<PARA *> *row_owners, PARA_LIST *paragraphs); } // namespace #endif // TESSERACT_CCMAIN_PARAGRAPHS_INTERNAL_H_
1080228-arabicocr11
ccmain/paragraphs_internal.h
C++
asf20
12,707
/////////////////////////////////////////////////////////////////////// // File: pageiterator.cpp // Description: Iterator for tesseract page structure that avoids using // tesseract internal data structures. // Author: Ray Smith // Created: Fri Feb 26 14:32:09 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. // /////////////////////////////////////////////////////////////////////// #include "pageiterator.h" #include "allheaders.h" #include "helpers.h" #include "pageres.h" #include "tesseractclass.h" namespace tesseract { PageIterator::PageIterator(PAGE_RES* page_res, Tesseract* tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height) : page_res_(page_res), tesseract_(tesseract), word_(NULL), word_length_(0), blob_index_(0), cblob_it_(NULL), scale_(scale), scaled_yres_(scaled_yres), rect_left_(rect_left), rect_top_(rect_top), rect_width_(rect_width), rect_height_(rect_height) { it_ = new PAGE_RES_IT(page_res); PageIterator::Begin(); } PageIterator::~PageIterator() { delete it_; delete cblob_it_; } /** * PageIterators 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. */ PageIterator::PageIterator(const PageIterator& src) : page_res_(src.page_res_), tesseract_(src.tesseract_), word_(NULL), word_length_(src.word_length_), blob_index_(src.blob_index_), cblob_it_(NULL), scale_(src.scale_), scaled_yres_(src.scaled_yres_), rect_left_(src.rect_left_), rect_top_(src.rect_top_), rect_width_(src.rect_width_), rect_height_(src.rect_height_) { it_ = new PAGE_RES_IT(*src.it_); BeginWord(src.blob_index_); } const PageIterator& PageIterator::operator=(const PageIterator& src) { page_res_ = src.page_res_; tesseract_ = src.tesseract_; scale_ = src.scale_; scaled_yres_ = src.scaled_yres_; rect_left_ = src.rect_left_; rect_top_ = src.rect_top_; rect_width_ = src.rect_width_; rect_height_ = src.rect_height_; if (it_ != NULL) delete it_; it_ = new PAGE_RES_IT(*src.it_); BeginWord(src.blob_index_); return *this; } bool PageIterator::PositionedAtSameWord(const PAGE_RES_IT* other) const { return (it_ == NULL && it_ == other) || ((other != NULL) && (it_ != NULL) && (*it_ == *other)); } // ============= Moving around within the page ============. /** Resets the iterator to point to the start of the page. */ void PageIterator::Begin() { it_->restart_page_with_empties(); BeginWord(0); } void PageIterator::RestartParagraph() { if (it_->block() == NULL) return; // At end of the document. PAGE_RES_IT para(page_res_); PAGE_RES_IT next_para(para); next_para.forward_paragraph(); while (next_para.cmp(*it_) <= 0) { para = next_para; next_para.forward_paragraph(); } *it_ = para; BeginWord(0); } bool PageIterator::IsWithinFirstTextlineOfParagraph() const { PageIterator p_start(*this); p_start.RestartParagraph(); return p_start.it_->row() == it_->row(); } void PageIterator::RestartRow() { it_->restart_row(); BeginWord(0); } /** * 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 (CHANGED!) that ALL PageIteratorLevel level values will visit each * non-text block at least once. * Think of non text blocks as containing a single para, with at least one * line, with a single imaginary word, containing a single symbol. * The bounding boxes mark out any polygonal nature of the block, and * PTIsTextType(BLockType()) is false for non-text blocks. * 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. */ bool PageIterator::Next(PageIteratorLevel level) { if (it_->block() == NULL) return false; // Already at the end! if (it_->word() == NULL) level = RIL_BLOCK; switch (level) { case RIL_BLOCK: it_->forward_block(); break; case RIL_PARA: it_->forward_paragraph(); break; case RIL_TEXTLINE: for (it_->forward_with_empties(); it_->row() == it_->prev_row(); it_->forward_with_empties()); break; case RIL_WORD: it_->forward_with_empties(); break; case RIL_SYMBOL: if (cblob_it_ != NULL) cblob_it_->forward(); ++blob_index_; if (blob_index_ >= word_length_) it_->forward_with_empties(); else return true; break; } BeginWord(0); return it_->block() != NULL; } /** * Returns true if the iterator is at the start of an object at the given * level. Possible uses include determining if a call to Next(RIL_WORD) * moved to the start of a RIL_PARA. */ bool PageIterator::IsAtBeginningOf(PageIteratorLevel level) const { if (it_->block() == NULL) return false; // Already at the end! if (it_->word() == NULL) return true; // In an image block. switch (level) { case RIL_BLOCK: return blob_index_ == 0 && it_->block() != it_->prev_block(); case RIL_PARA: return blob_index_ == 0 && (it_->block() != it_->prev_block() || it_->row()->row->para() != it_->prev_row()->row->para()); case RIL_TEXTLINE: return blob_index_ == 0 && it_->row() != it_->prev_row(); case RIL_WORD: return blob_index_ == 0; case RIL_SYMBOL: return true; } return false; } /** * 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) */ bool PageIterator::IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const { if (Empty(element)) return true; // Already at the end! // The result is true if we step forward by element and find we are // at the the end of the page or at beginning of *all* levels in: // [level, element). // When there is more than one level difference between element and level, // we could for instance move forward one symbol and still be at the first // word on a line, so we also have to be at the first symbol in a word. PageIterator next(*this); next.Next(element); if (next.Empty(element)) return true; // Reached the end of the page. while (element > level) { element = static_cast<PageIteratorLevel>(element - 1); if (!next.IsAtBeginningOf(element)) return false; } return true; } /** * Returns whether this iterator is positioned * before other: -1 * equal to other: 0 * after other: 1 */ int PageIterator::Cmp(const PageIterator &other) const { int word_cmp = it_->cmp(*other.it_); if (word_cmp != 0) return word_cmp; if (blob_index_ < other.blob_index_) return -1; if (blob_index_ == other.blob_index_) return 0; return 1; } // ============= 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 in * the coordinates of the working image that is pix_binary(). * See comment on coordinate system above. * Returns false if there is no such object at the current position. */ bool PageIterator::BoundingBoxInternal(PageIteratorLevel level, int* left, int* top, int* right, int* bottom) const { if (Empty(level)) return false; TBOX box; PARA *para = NULL; switch (level) { case RIL_BLOCK: box = it_->block()->block->bounding_box(); break; case RIL_PARA: para = it_->row()->row->para(); // explicit fall-through. case RIL_TEXTLINE: box = it_->row()->row->bounding_box(); break; case RIL_WORD: box = it_->word()->word->bounding_box(); break; case RIL_SYMBOL: if (cblob_it_ == NULL) box = it_->word()->box_word->BlobBox(blob_index_); else box = cblob_it_->data()->bounding_box(); } if (level == RIL_PARA) { PageIterator other = *this; other.Begin(); do { if (other.it_->block() && other.it_->block()->block == it_->block()->block && other.it_->row() && other.it_->row()->row && other.it_->row()->row->para() == para) { box = box.bounding_union(other.it_->row()->row->bounding_box()); } } while (other.Next(RIL_TEXTLINE)); } if (level != RIL_SYMBOL || cblob_it_ != NULL) box.rotate(it_->block()->block->re_rotation()); // Now we have a box in tesseract coordinates relative to the image rectangle, // we have to convert the coords to a top-down system. const int pix_height = pixGetHeight(tesseract_->pix_binary()); const int pix_width = pixGetWidth(tesseract_->pix_binary()); *left = ClipToRange(static_cast<int>(box.left()), 0, pix_width); *top = ClipToRange(pix_height - box.top(), 0, pix_height); *right = ClipToRange(static_cast<int>(box.right()), *left, pix_width); *bottom = ClipToRange(pix_height - box.bottom(), *top, pix_height); return true; } /** * Returns the bounding rectangle of the current object at the given level in * coordinates of the original image. * See comment on coordinate system above. * Returns false if there is no such object at the current position. */ bool PageIterator::BoundingBox(PageIteratorLevel level, int* left, int* top, int* right, int* bottom) const { return BoundingBox(level, 0, left, top, right, bottom); } bool PageIterator::BoundingBox(PageIteratorLevel level, const int padding, int* left, int* top, int* right, int* bottom) const { if (!BoundingBoxInternal(level, left, top, right, bottom)) return false; // Convert to the coordinate system of the original image. *left = ClipToRange(*left / scale_ + rect_left_ - padding, rect_left_, rect_left_ + rect_width_); *top = ClipToRange(*top / scale_ + rect_top_ - padding, rect_top_, rect_top_ + rect_height_); *right = ClipToRange((*right + scale_ - 1) / scale_ + rect_left_ + padding, *left, rect_left_ + rect_width_); *bottom = ClipToRange((*bottom + scale_ - 1) / scale_ + rect_top_ + padding, *top, rect_top_ + rect_height_); return true; } /** Return that there is no such object at a given level. */ bool PageIterator::Empty(PageIteratorLevel level) const { if (it_->block() == NULL) return true; // Already at the end! if (it_->word() == NULL && level != RIL_BLOCK) return true; // image block if (level == RIL_SYMBOL && blob_index_ >= word_length_) return true; // Zero length word, or already at the end of it. return false; } /** Returns the type of the current block. See apitypes.h for PolyBlockType. */ PolyBlockType PageIterator::BlockType() const { if (it_->block() == NULL || it_->block()->block == NULL) return PT_UNKNOWN; // Already at the end! if (it_->block()->block->poly_block() == NULL) return PT_FLOWING_TEXT; // No layout analysis used - assume text. return it_->block()->block->poly_block()->isA(); } /** Returns the polygon outline of the current block. The returned Pta must * be ptaDestroy-ed after use. */ Pta* PageIterator::BlockPolygon() const { if (it_->block() == NULL || it_->block()->block == NULL) return NULL; // Already at the end! if (it_->block()->block->poly_block() == NULL) return NULL; // No layout analysis used - no polygon. ICOORDELT_IT it(it_->block()->block->poly_block()->points()); Pta* pta = ptaCreate(it.length()); int num_pts = 0; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward(), ++num_pts) { ICOORD* pt = it.data(); // Convert to top-down coords within the input image. float x = static_cast<float>(pt->x()) / scale_ + rect_left_; float y = rect_top_ + rect_height_ - static_cast<float>(pt->y()) / scale_; ptaAddPt(pta, x, y); } return pta; } /** * 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. * The following methods are used to generate the images: * RIL_BLOCK: mask the page image with the block polygon. * RIL_TEXTLINE: Clip the rectangle of the line box from the page image. * TODO(rays) fix this to generate and use a line polygon. * RIL_WORD: Clip the rectangle of the word box from the page image. * RIL_SYMBOL: Render the symbol outline to an image for cblobs (prior * to recognition) or the bounding box otherwise. * A reconstruction of the original image (using xor to check for double * representation) should be reasonably accurate, * apart from removed noise, at the block level. Below the block level, the * reconstruction will be missing images and line separators. * At the symbol level, kerned characters will be invade the bounding box * if rendered after recognition, making an xor reconstruction inaccurate, but * an or construction better. Before recognition, symbol-level reconstruction * should be good, even with xor, since the images come from the connected * components. */ Pix* PageIterator::GetBinaryImage(PageIteratorLevel level) const { int left, top, right, bottom; if (!BoundingBoxInternal(level, &left, &top, &right, &bottom)) return NULL; Pix* pix = NULL; switch (level) { case RIL_BLOCK: case RIL_PARA: int bleft, btop, bright, bbottom; BoundingBoxInternal(RIL_BLOCK, &bleft, &btop, &bright, &bbottom); pix = it_->block()->block->render_mask(); // AND the mask and the image. pixRasterop(pix, 0, 0, pixGetWidth(pix), pixGetHeight(pix), PIX_SRC & PIX_DST, tesseract_->pix_binary(), bleft, btop); if (level == RIL_PARA) { // RIL_PARA needs further attention: // clip the paragraph from the block mask. Box* box = boxCreate(left - bleft, top - btop, right - left, bottom - top); Pix* pix2 = pixClipRectangle(pix, box, NULL); boxDestroy(&box); pixDestroy(&pix); pix = pix2; } break; case RIL_TEXTLINE: case RIL_WORD: case RIL_SYMBOL: if (level == RIL_SYMBOL && cblob_it_ != NULL && cblob_it_->data()->area() != 0) return cblob_it_->data()->render(); // Just clip from the bounding box. Box* box = boxCreate(left, top, right - left, bottom - top); pix = pixClipRectangle(tesseract_->pix_binary(), box, NULL); boxDestroy(&box); break; } return pix; } /** * 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. * If you do not supply an original image, you will get a binary one. * Use pixDestroy to delete the image after use. */ Pix* PageIterator::GetImage(PageIteratorLevel level, int padding, Pix* original_img, int* left, int* top) const { int right, bottom; if (!BoundingBox(level, left, top, &right, &bottom)) return NULL; if (original_img == NULL) return GetBinaryImage(level); // Expand the box. *left = MAX(*left - padding, 0); *top = MAX(*top - padding, 0); right = MIN(right + padding, rect_width_); bottom = MIN(bottom + padding, rect_height_); Box* box = boxCreate(*left, *top, right - *left, bottom - *top); Pix* grey_pix = pixClipRectangle(original_img, box, NULL); boxDestroy(&box); if (level == RIL_BLOCK) { Pix* mask = it_->block()->block->render_mask(); Pix* expanded_mask = pixCreate(right - *left, bottom - *top, 1); pixRasterop(expanded_mask, padding, padding, pixGetWidth(mask), pixGetHeight(mask), PIX_SRC, mask, 0, 0); pixDestroy(&mask); pixDilateBrick(expanded_mask, expanded_mask, 2*padding + 1, 2*padding + 1); pixInvert(expanded_mask, expanded_mask); pixSetMasked(grey_pix, expanded_mask, MAX_UINT32); pixDestroy(&expanded_mask); } return grey_pix; } /** * 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! */ bool PageIterator::Baseline(PageIteratorLevel level, int* x1, int* y1, int* x2, int* y2) const { if (it_->word() == NULL) return false; // Already at the end! ROW* row = it_->row()->row; WERD* word = it_->word()->word; TBOX box = (level == RIL_WORD || level == RIL_SYMBOL) ? word->bounding_box() : row->bounding_box(); int left = box.left(); ICOORD startpt(left, static_cast<inT16>(row->base_line(left) + 0.5)); int right = box.right(); ICOORD endpt(right, static_cast<inT16>(row->base_line(right) + 0.5)); // Rotate to image coordinates and convert to global image coords. startpt.rotate(it_->block()->block->re_rotation()); endpt.rotate(it_->block()->block->re_rotation()); *x1 = startpt.x() / scale_ + rect_left_; *y1 = (rect_height_ - startpt.y()) / scale_ + rect_top_; *x2 = endpt.x() / scale_ + rect_left_; *y2 = (rect_height_ - endpt.y()) / scale_ + rect_top_; return true; } void PageIterator::Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const { BLOCK* block = it_->block()->block; // Orientation FCOORD up_in_image(0.0, 1.0); up_in_image.unrotate(block->classify_rotation()); up_in_image.rotate(block->re_rotation()); if (up_in_image.x() == 0.0F) { if (up_in_image.y() > 0.0F) { *orientation = ORIENTATION_PAGE_UP; } else { *orientation = ORIENTATION_PAGE_DOWN; } } else if (up_in_image.x() > 0.0F) { *orientation = ORIENTATION_PAGE_RIGHT; } else { *orientation = ORIENTATION_PAGE_LEFT; } // Writing direction bool is_vertical_text = (block->classify_rotation().x() == 0.0); bool right_to_left = block->right_to_left(); *writing_direction = is_vertical_text ? WRITING_DIRECTION_TOP_TO_BOTTOM : (right_to_left ? WRITING_DIRECTION_RIGHT_TO_LEFT : WRITING_DIRECTION_LEFT_TO_RIGHT); // Textline Order bool is_mongolian = false; // TODO(eger): fix me *textline_order = is_vertical_text ? (is_mongolian ? TEXTLINE_ORDER_LEFT_TO_RIGHT : TEXTLINE_ORDER_RIGHT_TO_LEFT) : TEXTLINE_ORDER_TOP_TO_BOTTOM; // Deskew angle FCOORD skew = block->skew(); // true horizontal for textlines *deskew_angle = -skew.angle(); } void PageIterator::ParagraphInfo(tesseract::ParagraphJustification *just, bool *is_list_item, bool *is_crown, int *first_line_indent) const { *just = tesseract::JUSTIFICATION_UNKNOWN; if (!it_->row() || !it_->row()->row || !it_->row()->row->para() || !it_->row()->row->para()->model) return; PARA *para = it_->row()->row->para(); *is_list_item = para->is_list_item; *is_crown = para->is_very_first_or_continuation; *first_line_indent = para->model->first_indent() - para->model->body_indent(); } /** * Sets up the internal data for iterating the blobs of a new word, then * moves the iterator to the given offset. */ void PageIterator::BeginWord(int offset) { WERD_RES* word_res = it_->word(); if (word_res == NULL) { // This is a non-text block, so there is no word. word_length_ = 0; blob_index_ = 0; word_ = NULL; return; } if (word_res->best_choice != NULL) { // Recognition has been done, so we are using the box_word, which // is already baseline denormalized. word_length_ = word_res->best_choice->length(); if (word_res->box_word != NULL) { if (word_res->box_word->length() != word_length_) { tprintf("Corrupted word! best_choice[len=%d] = %s, box_word[len=%d]: ", word_length_, word_res->best_choice->unichar_string().string(), word_res->box_word->length()); word_res->box_word->bounding_box().print(); } ASSERT_HOST(word_res->box_word->length() == word_length_); } word_ = NULL; // We will be iterating the box_word. if (cblob_it_ != NULL) { delete cblob_it_; cblob_it_ = NULL; } } else { // No recognition yet, so a "symbol" is a cblob. word_ = word_res->word; ASSERT_HOST(word_->cblob_list() != NULL); word_length_ = word_->cblob_list()->length(); if (cblob_it_ == NULL) cblob_it_ = new C_BLOB_IT; cblob_it_->set_to_list(word_->cblob_list()); } for (blob_index_ = 0; blob_index_ < offset; ++blob_index_) { if (cblob_it_ != NULL) cblob_it_->forward(); } } bool PageIterator::SetWordBlamerBundle(BlamerBundle *blamer_bundle) { if (it_->word() != NULL) { it_->word()->blamer_bundle = blamer_bundle; return true; } else { return false; } } } // namespace tesseract.
1080228-arabicocr11
ccmain/pageiterator.cpp
C++
asf20
22,936
/********************************************************************** * File: werdit.cpp (Formerly wordit.c) * Description: An iterator for passing over all the words in a document. * Author: Ray Smith * Created: Mon Apr 27 08:51:22 BST 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ #include "werdit.h" /********************************************************************** * make_pseudo_word * * Make all the blobs inside a selection into a single word. * The returned PAGE_RES_IT* it points to the new word. After use, call * it->DeleteCurrentWord() to delete the fake word, and then * delete it to get rid of the iterator itself. **********************************************************************/ PAGE_RES_IT* make_pseudo_word(PAGE_RES* page_res, const TBOX& selection_box) { PAGE_RES_IT pr_it(page_res); C_BLOB_LIST new_blobs; // list of gathered blobs C_BLOB_IT new_blob_it = &new_blobs; // iterator for (WERD_RES* word_res = pr_it.word(); word_res != NULL; word_res = pr_it.forward()) { WERD* word = word_res->word; if (word->bounding_box().overlap(selection_box)) { C_BLOB_IT blob_it(word->cblob_list()); for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { C_BLOB* blob = blob_it.data(); if (blob->bounding_box().overlap(selection_box)) { new_blob_it.add_after_then_move(C_BLOB::deep_copy(blob)); } } if (!new_blobs.empty()) { WERD* pseudo_word = new WERD(&new_blobs, 1, NULL); word_res = pr_it.InsertSimpleCloneWord(*word_res, pseudo_word); PAGE_RES_IT* it = new PAGE_RES_IT(page_res); while (it->word() != word_res && it->word() != NULL) it->forward(); ASSERT_HOST(it->word() == word_res); return it; } } } return NULL; }
1080228-arabicocr11
ccmain/werdit.cpp
C++
asf20
2,492
/********************************************************************** * File: adaptions.cpp (Formerly adaptions.c) * Description: Functions used to adapt to blobs already confidently * identified * Author: Chris Newton * Created: Thu Oct 7 10:17:28 BST 1993 * * (C) Copyright 1992, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4305) // int/float warnings #endif #ifdef __UNIX__ #include <assert.h> #endif #include <ctype.h> #include <string.h> #include "tessbox.h" #include "tessvars.h" #include "memry.h" #include "reject.h" #include "control.h" #include "stopper.h" #include "tesseractclass.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif namespace tesseract { BOOL8 Tesseract::word_adaptable( //should we adapt? WERD_RES *word, uinT16 mode) { if (tessedit_adaption_debug) { tprintf("Running word_adaptable() for %s rating %.4f certainty %.4f\n", word->best_choice == NULL ? "" : word->best_choice->unichar_string().string(), word->best_choice->rating(), word->best_choice->certainty()); } BOOL8 status = FALSE; BITS16 flags(mode); enum MODES { ADAPTABLE_WERD, ACCEPTABLE_WERD, CHECK_DAWGS, CHECK_SPACES, CHECK_ONE_ELL_CONFLICT, CHECK_AMBIG_WERD }; /* 0: NO adaption */ if (mode == 0) { if (tessedit_adaption_debug) tprintf("adaption disabled\n"); return FALSE; } if (flags.bit (ADAPTABLE_WERD)) { status |= word->tess_would_adapt; // result of Classify::AdaptableWord() if (tessedit_adaption_debug && !status) { tprintf("tess_would_adapt bit is false\n"); } } if (flags.bit (ACCEPTABLE_WERD)) { status |= word->tess_accepted; if (tessedit_adaption_debug && !status) { tprintf("tess_accepted bit is false\n"); } } if (!status) { // If not set then return FALSE; // ignore other checks } if (flags.bit (CHECK_DAWGS) && (word->best_choice->permuter () != SYSTEM_DAWG_PERM) && (word->best_choice->permuter () != FREQ_DAWG_PERM) && (word->best_choice->permuter () != USER_DAWG_PERM) && (word->best_choice->permuter () != NUMBER_PERM)) { if (tessedit_adaption_debug) tprintf("word not in dawgs\n"); return FALSE; } if (flags.bit (CHECK_ONE_ELL_CONFLICT) && one_ell_conflict (word, FALSE)) { if (tessedit_adaption_debug) tprintf("word has ell conflict\n"); return FALSE; } if (flags.bit (CHECK_SPACES) && (strchr(word->best_choice->unichar_string().string(), ' ') != NULL)) { if (tessedit_adaption_debug) tprintf("word contains spaces\n"); return FALSE; } if (flags.bit (CHECK_AMBIG_WERD) && word->best_choice->dangerous_ambig_found()) { if (tessedit_adaption_debug) tprintf("word is ambiguous\n"); return FALSE; } if (tessedit_adaption_debug) { tprintf("returning status %d\n", status); } return status; } } // namespace tesseract
1080228-arabicocr11
ccmain/adaptions.cpp
C++
asf20
3,867
/********************************************************************** * File: tessbox.cpp (Formerly tessbox.c) * Description: Black boxed Tess for developing a resaljet. * Author: Ray Smith * Created: Thu Apr 23 11:03:36 BST 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif #include "mfoutline.h" #include "tessbox.h" #include "tesseractclass.h" #define EXTERN /** * @name tess_segment_pass_n * * Segment a word using the pass_n conditions of the tess segmenter. * @param pass_n pass number * @param word word to do */ namespace tesseract { void Tesseract::tess_segment_pass_n(int pass_n, WERD_RES *word) { int saved_enable_assoc = 0; int saved_chop_enable = 0; if (word->word->flag(W_DONT_CHOP)) { saved_enable_assoc = wordrec_enable_assoc; saved_chop_enable = chop_enable; wordrec_enable_assoc.set_value(0); chop_enable.set_value(0); } if (pass_n == 1) set_pass1(); else set_pass2(); recog_word(word); if (word->best_choice == NULL) word->SetupFake(*word->uch_set); if (word->word->flag(W_DONT_CHOP)) { wordrec_enable_assoc.set_value(saved_enable_assoc); chop_enable.set_value(saved_chop_enable); } } /** * @name tess_acceptable_word * * @return true if the word is regarded as "good enough". * @param word_choice after context * @param raw_choice before context */ bool Tesseract::tess_acceptable_word(WERD_RES* word) { return getDict().AcceptableResult(word); } /** * @name tess_add_doc_word * * Add the given word to the document dictionary */ void Tesseract::tess_add_doc_word(WERD_CHOICE *word_choice) { getDict().add_document_word(*word_choice); } } // namespace tesseract
1080228-arabicocr11
ccmain/tessbox.cpp
C++
asf20
2,399
/********************************************************************** * File: tesseract_cube_combiner.h * Description: Declaration of the Tesseract & Cube results combiner Class * Author: Ahmad Abdulkader * Created: 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. * **********************************************************************/ // The TesseractCubeCombiner class provides the functionality of combining // the recognition results of Tesseract and Cube at the word level #include <algorithm> #include <string> #include <vector> #include <wctype.h> #include "tesseract_cube_combiner.h" #include "cube_object.h" #include "cube_reco_context.h" #include "cube_utils.h" #include "neural_net.h" #include "tesseractclass.h" #include "word_altlist.h" namespace tesseract { TesseractCubeCombiner::TesseractCubeCombiner(CubeRecoContext *cube_cntxt) { cube_cntxt_ = cube_cntxt; combiner_net_ = NULL; } TesseractCubeCombiner::~TesseractCubeCombiner() { if (combiner_net_ != NULL) { delete combiner_net_; combiner_net_ = NULL; } } bool TesseractCubeCombiner::LoadCombinerNet() { ASSERT_HOST(cube_cntxt_); // Compute the path of the combiner net string data_path; cube_cntxt_->GetDataFilePath(&data_path); string net_file_name = data_path + cube_cntxt_->Lang() + ".tesseract_cube.nn"; // Return false if file does not exist FILE *fp = fopen(net_file_name.c_str(), "rb"); if (fp == NULL) return false; else fclose(fp); // Load and validate net combiner_net_ = NeuralNet::FromFile(net_file_name); if (combiner_net_ == NULL) { tprintf("Could not read combiner net file %s", net_file_name.c_str()); return false; } else if (combiner_net_->out_cnt() != 2) { tprintf("Invalid combiner net file %s! Output count != 2\n", net_file_name.c_str()); delete combiner_net_; combiner_net_ = NULL; return false; } return true; } // Normalize a UTF-8 string. Converts the UTF-8 string to UTF32 and optionally // strips punc and/or normalizes case and then converts back string TesseractCubeCombiner::NormalizeString(const string &str, bool remove_punc, bool norm_case) { // convert to UTF32 string_32 str32; CubeUtils::UTF8ToUTF32(str.c_str(), &str32); // strip punc and normalize string_32 new_str32; for (int idx = 0; idx < str32.length(); idx++) { // if no punc removal is required or not a punctuation character if (!remove_punc || iswpunct(str32[idx]) == 0) { char_32 norm_char = str32[idx]; // normalize case if required if (norm_case && iswalpha(norm_char)) { norm_char = towlower(norm_char); } new_str32.push_back(norm_char); } } // convert back to UTF8 string new_str; CubeUtils::UTF32ToUTF8(new_str32.c_str(), &new_str); return new_str; } // Compares 2 strings optionally ignoring punctuation int TesseractCubeCombiner::CompareStrings(const string &str1, const string &str2, bool ignore_punc, bool ignore_case) { if (!ignore_punc && !ignore_case) { return str1.compare(str2); } string norm_str1 = NormalizeString(str1, ignore_punc, ignore_case); string norm_str2 = NormalizeString(str2, ignore_punc, ignore_case); return norm_str1.compare(norm_str2); } // Check if a string is a valid Tess dict word or not bool TesseractCubeCombiner::ValidWord(const string &str) { return (cube_cntxt_->TesseractObject()->getDict().valid_word(str.c_str()) > 0); } // Public method for computing the combiner features. The agreement // output parameter will be true if both answers are identical, // and false otherwise. bool TesseractCubeCombiner::ComputeCombinerFeatures(const string &tess_str, int tess_confidence, CubeObject *cube_obj, WordAltList *cube_alt_list, vector<double> *features, bool *agreement) { features->clear(); *agreement = false; if (cube_alt_list == NULL || cube_alt_list->AltCount() <= 0) return false; // Get Cube's best string; return false if empty char_32 *cube_best_str32 = cube_alt_list->Alt(0); if (cube_best_str32 == NULL || CubeUtils::StrLen(cube_best_str32) < 1) return false; string cube_best_str; int cube_best_cost = cube_alt_list->AltCost(0); int cube_best_bigram_cost = 0; bool cube_best_bigram_cost_valid = true; if (cube_cntxt_->Bigrams()) cube_best_bigram_cost = cube_cntxt_->Bigrams()-> Cost(cube_best_str32, cube_cntxt_->CharacterSet()); else cube_best_bigram_cost_valid = false; CubeUtils::UTF32ToUTF8(cube_best_str32, &cube_best_str); // Get Tesseract's UTF32 string string_32 tess_str32; CubeUtils::UTF8ToUTF32(tess_str.c_str(), &tess_str32); // Compute agreement flag *agreement = (tess_str.compare(cube_best_str) == 0); // Get Cube's second best string; if empty, return false char_32 *cube_next_best_str32; string cube_next_best_str; int cube_next_best_cost = WORST_COST; if (cube_alt_list->AltCount() > 1) { cube_next_best_str32 = cube_alt_list->Alt(1); if (cube_next_best_str32 == NULL || CubeUtils::StrLen(cube_next_best_str32) == 0) { return false; } cube_next_best_cost = cube_alt_list->AltCost(1); CubeUtils::UTF32ToUTF8(cube_next_best_str32, &cube_next_best_str); } // Rank of Tesseract's top result in Cube's alternate list int tess_rank = 0; for (tess_rank = 0; tess_rank < cube_alt_list->AltCount(); tess_rank++) { string alt_str; CubeUtils::UTF32ToUTF8(cube_alt_list->Alt(tess_rank), &alt_str); if (alt_str == tess_str) break; } // Cube's cost for tesseract's result. Note that this modifies the // state of cube_obj, including its alternate list by calling RecognizeWord() int tess_cost = cube_obj->WordCost(tess_str.c_str()); // Cube's bigram cost of Tesseract's string int tess_bigram_cost = 0; int tess_bigram_cost_valid = true; if (cube_cntxt_->Bigrams()) tess_bigram_cost = cube_cntxt_->Bigrams()-> Cost(tess_str32.c_str(), cube_cntxt_->CharacterSet()); else tess_bigram_cost_valid = false; // Tesseract confidence features->push_back(tess_confidence); // Cube cost of Tesseract string features->push_back(tess_cost); // Cube Rank of Tesseract string features->push_back(tess_rank); // length of Tesseract OCR string features->push_back(tess_str.length()); // Tesseract OCR string in dictionary features->push_back(ValidWord(tess_str)); if (tess_bigram_cost_valid) { // bigram cost of Tesseract string features->push_back(tess_bigram_cost); } // Cube tess_cost of Cube best string features->push_back(cube_best_cost); // Cube tess_cost of Cube next best string features->push_back(cube_next_best_cost); // length of Cube string features->push_back(cube_best_str.length()); // Cube string in dictionary features->push_back(ValidWord(cube_best_str)); if (cube_best_bigram_cost_valid) { // bigram cost of Cube string features->push_back(cube_best_bigram_cost); } // case-insensitive string comparison, including punctuation int compare_nocase_punc = CompareStrings(cube_best_str, tess_str, false, true); features->push_back(compare_nocase_punc == 0); // case-sensitive string comparison, ignoring punctuation int compare_case_nopunc = CompareStrings(cube_best_str, tess_str, true, false); features->push_back(compare_case_nopunc == 0); // case-insensitive string comparison, ignoring punctuation int compare_nocase_nopunc = CompareStrings(cube_best_str, tess_str, true, true); features->push_back(compare_nocase_nopunc == 0); return true; } // The CubeObject parameter is used for 2 purposes: 1) to retrieve // cube's alt list, and 2) to compute cube's word cost for the // tesseract result. The call to CubeObject::WordCost() modifies // the object's alternate list, so previous state will be lost. float TesseractCubeCombiner::CombineResults(WERD_RES *tess_res, CubeObject *cube_obj) { // If no combiner is loaded or the cube object is undefined, // tesseract wins with probability 1.0 if (combiner_net_ == NULL || cube_obj == NULL) { tprintf("Cube WARNING (TesseractCubeCombiner::CombineResults): " "Cube objects not initialized; defaulting to Tesseract\n"); return 1.0; } // Retrieve the alternate list from the CubeObject's current state. // If the alt list empty, tesseract wins with probability 1.0 WordAltList *cube_alt_list = cube_obj->AlternateList(); if (cube_alt_list == NULL) cube_alt_list = cube_obj->RecognizeWord(); if (cube_alt_list == NULL || cube_alt_list->AltCount() <= 0) { tprintf("Cube WARNING (TesseractCubeCombiner::CombineResults): " "Cube returned no results; defaulting to Tesseract\n"); return 1.0; } return CombineResults(tess_res, cube_obj, cube_alt_list); } // The alt_list parameter is expected to have been extracted from the // CubeObject that recognized the word to be combined. The cube_obj // parameter passed may be either same instance or a separate instance to // be used only by the combiner. In both cases, its alternate // list will be modified by an internal call to RecognizeWord(). float TesseractCubeCombiner::CombineResults(WERD_RES *tess_res, CubeObject *cube_obj, WordAltList *cube_alt_list) { // If no combiner is loaded or the cube object is undefined, or the // alt list is empty, tesseract wins with probability 1.0 if (combiner_net_ == NULL || cube_obj == NULL || cube_alt_list == NULL || cube_alt_list->AltCount() <= 0) { tprintf("Cube WARNING (TesseractCubeCombiner::CombineResults): " "Cube result cannot be retrieved; defaulting to Tesseract\n"); return 1.0; } // Tesseract result string, tesseract confidence, and cost of // tesseract result according to cube string tess_str = tess_res->best_choice->unichar_string().string(); // Map certainty [-20.0, 0.0] to confidence [0, 100] int tess_confidence = MIN(100, MAX(1, static_cast<int>( 100 + (5 * tess_res->best_choice->certainty())))); // Compute the combiner features. If feature computation fails or // answers are identical, tesseract wins with probability 1.0 vector<double> features; bool agreement; bool combiner_success = ComputeCombinerFeatures(tess_str, tess_confidence, cube_obj, cube_alt_list, &features, &agreement); if (!combiner_success || agreement) return 1.0; // Classify combiner feature vector and return output (probability // of tesseract class). double net_out[2]; if (!combiner_net_->FeedForward(&features[0], net_out)) return 1.0; return net_out[1]; } }
1080228-arabicocr11
ccmain/tesseract_cube_combiner.cpp
C++
asf20
11,967
/****************************************************************** * File: fixspace.h (Formerly fixspace.h) * Description: Implements a pass over the page res, exploring the alternative * spacing possibilities, trying to use context to improve the word spacing * Author: Phil Cheatle * Created: Thu Oct 21 11:38:43 BST 1993 * * (C) Copyright 1993, 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 FIXSPACE_H #define FIXSPACE_H #include "pageres.h" #include "params.h" void initialise_search(WERD_RES_LIST &src_list, WERD_RES_LIST &new_list); void transform_to_next_perm(WERD_RES_LIST &words); void fixspace_dbg(WERD_RES *word); #endif
1080228-arabicocr11
ccmain/fixspace.h
C
asf20
1,303
/****************************************************************** * File: control.cpp (Formerly control.c) * Description: Module-independent matcher controller. * Author: Ray Smith * Created: Thu Apr 23 11:09:58 BST 1992 * ReHacked: Tue Sep 22 08:42:49 BST 1992 Phil Cheatle * * (C) Copyright 1992, 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. * **********************************************************************/ #include <string.h> #include <math.h> #ifdef __UNIX__ #include <assert.h> #include <unistd.h> #include <errno.h> #endif #include <ctype.h> #include "ocrclass.h" #include "werdit.h" #include "drawfx.h" #include "tessbox.h" #include "tessvars.h" #include "pgedit.h" #include "reject.h" #include "fixspace.h" #include "docqual.h" #include "control.h" #include "output.h" #include "callcpp.h" #include "globals.h" #include "sorthelper.h" #include "tesseractclass.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #define MIN_FONT_ROW_COUNT 8 #define MAX_XHEIGHT_DIFF 3 const char* const kBackUpConfigFile = "tempconfigdata.config"; // Multiple of x-height to make a repeated word have spaces in it. const double kRepcharGapThreshold = 0.5; // Min believable x-height for any text when refitting as a fraction of // original x-height const double kMinRefitXHeightFraction = 0.5; /** * recog_pseudo_word * * Make a word from the selected blobs and run Tess on them. * * @param page_res recognise blobs * @param selection_box within this box */ namespace tesseract { void Tesseract::recog_pseudo_word(PAGE_RES* page_res, TBOX &selection_box) { PAGE_RES_IT* it = make_pseudo_word(page_res, selection_box); if (it != NULL) { recog_interactive(it); it->DeleteCurrentWord(); delete it; } } /** * recog_interactive * * Recognize a single word in interactive mode. * * @param block block * @param row row of word * @param word_res word to recognise */ BOOL8 Tesseract::recog_interactive(PAGE_RES_IT* pr_it) { inT16 char_qual; inT16 good_char_qual; WordData word_data(*pr_it); SetupWordPassN(2, &word_data); classify_word_and_language(&Tesseract::classify_word_pass2, pr_it, &word_data); if (tessedit_debug_quality_metrics) { WERD_RES* word_res = pr_it->word(); word_char_quality(word_res, pr_it->row()->row, &char_qual, &good_char_qual); tprintf("\n%d chars; word_blob_quality: %d; outline_errs: %d; " "char_quality: %d; good_char_quality: %d\n", word_res->reject_map.length(), word_blob_quality(word_res, pr_it->row()->row), word_outline_errs(word_res), char_qual, good_char_qual); } return TRUE; } // Helper function to check for a target word and handle it appropriately. // Inspired by Jetsoft's requirement to process only single words on pass2 // and beyond. // If word_config is not null: // If the word_box and target_word_box overlap, read the word_config file // else reset to previous config data. // return true. // else // If the word_box and target_word_box overlap or pass <= 1, return true. // Note that this function uses a fixed temporary file for storing the previous // configs, so it is neither thread-safe, nor process-safe, but the assumption // is that it will only be used for one debug window at a time. // // Since this function is used for debugging (and not to change OCR results) // set only debug params from the word config file. bool Tesseract::ProcessTargetWord(const TBOX& word_box, const TBOX& target_word_box, const char* word_config, int pass) { if (word_config != NULL) { if (word_box.major_overlap(target_word_box)) { if (backup_config_file_ == NULL) { backup_config_file_ = kBackUpConfigFile; FILE* config_fp = fopen(backup_config_file_, "wb"); ParamUtils::PrintParams(config_fp, params()); fclose(config_fp); ParamUtils::ReadParamsFile(word_config, SET_PARAM_CONSTRAINT_DEBUG_ONLY, params()); } } else { if (backup_config_file_ != NULL) { ParamUtils::ReadParamsFile(backup_config_file_, SET_PARAM_CONSTRAINT_DEBUG_ONLY, params()); backup_config_file_ = NULL; } } } else if (pass > 1 && !word_box.major_overlap(target_word_box)) { return false; } return true; } // If tesseract is to be run, sets the words up ready for it. void Tesseract::SetupAllWordsPassN(int pass_n, const TBOX* target_word_box, const char* word_config, PAGE_RES* page_res, GenericVector<WordData>* words) { // Prepare all the words. PAGE_RES_IT page_res_it(page_res); for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { if (target_word_box == NULL || ProcessTargetWord(page_res_it.word()->word->bounding_box(), *target_word_box, word_config, 1)) { words->push_back(WordData(page_res_it)); } } // Setup all the words for recognition with polygonal approximation. for (int w = 0; w < words->size(); ++w) { SetupWordPassN(pass_n, &(*words)[w]); if (w > 0) (*words)[w].prev_word = &(*words)[w - 1]; } } // Sets up the single word ready for whichever engine is to be run. void Tesseract::SetupWordPassN(int pass_n, WordData* word) { if (pass_n == 1 || !word->word->done) { if (pass_n == 1) { word->word->SetupForRecognition(unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL, classify_bln_numeric_mode, textord_use_cjk_fp_model, poly_allow_detailed_fx, word->row, word->block); } else if (pass_n == 2) { // TODO(rays) Should we do this on pass1 too? word->word->caps_height = 0.0; if (word->word->x_height == 0.0f) word->word->x_height = word->row->x_height(); } for (int s = 0; s <= sub_langs_.size(); ++s) { // The sub_langs_.size() entry is for the master language. Tesseract* lang_t = s < sub_langs_.size() ? sub_langs_[s] : this; WERD_RES* word_res = new WERD_RES; word_res->InitForRetryRecognition(*word->word); word->lang_words.push_back(word_res); // Cube doesn't get setup for pass2. if (pass_n == 1 || lang_t->tessedit_ocr_engine_mode != OEM_CUBE_ONLY) { word_res->SetupForRecognition( lang_t->unicharset, lang_t, BestPix(), lang_t->tessedit_ocr_engine_mode, NULL, lang_t->classify_bln_numeric_mode, lang_t->textord_use_cjk_fp_model, lang_t->poly_allow_detailed_fx, word->row, word->block); } } } } // Runs word recognition on all the words. bool Tesseract::RecogAllWordsPassN(int pass_n, ETEXT_DESC* monitor, PAGE_RES_IT* pr_it, GenericVector<WordData>* words) { // TODO(rays) Before this loop can be parallelized (it would yield a massive // speed-up) all remaining member globals need to be converted to local/heap // (eg set_pass1 and set_pass2) and an intermediate adaption pass needs to be // added. The results will be significantly different with adaption on, and // deterioration will need investigation. pr_it->restart_page(); for (int w = 0; w < words->size(); ++w) { WordData* word = &(*words)[w]; if (w > 0) word->prev_word = &(*words)[w - 1]; if (monitor != NULL) { monitor->ocr_alive = TRUE; if (pass_n == 1) monitor->progress = 30 + 50 * w / words->size(); else monitor->progress = 80 + 10 * w / words->size(); if (monitor->deadline_exceeded() || (monitor->cancel != NULL && (*monitor->cancel)(monitor->cancel_this, words->size()))) { // Timeout. Fake out the rest of the words. for (; w < words->size(); ++w) { (*words)[w].word->SetupFake(unicharset); } return false; } } if (word->word->tess_failed) { int s; for (s = 0; s < word->lang_words.size() && word->lang_words[s]->tess_failed; ++s) {} // If all are failed, skip it. Image words are skipped by this test. if (s > word->lang_words.size()) continue; } // Sync pr_it with the wth WordData. while (pr_it->word() != NULL && pr_it->word() != word->word) pr_it->forward(); ASSERT_HOST(pr_it->word() != NULL); WordRecognizer recognizer = pass_n == 1 ? &Tesseract::classify_word_pass1 : &Tesseract::classify_word_pass2; classify_word_and_language(recognizer, pr_it, word); if (tessedit_dump_choices) { tprintf("Pass%d: %s [%s]\n", pass_n, word->word->best_choice->unichar_string().string(), word->word->best_choice->debug_string().string()); } pr_it->forward(); } return true; } /** * recog_all_words() * * Walk the page_res, recognizing all the words. * If monitor is not null, it is used as a progress monitor/timeout/cancel. * If dopasses is 0, all recognition passes are run, * 1 just pass 1, 2 passes2 and higher. * If target_word_box is not null, special things are done to words that * overlap the target_word_box: * if word_config is not null, the word config file is read for just the * target word(s), otherwise, on pass 2 and beyond ONLY the target words * are processed (Jetsoft modification.) * Returns false if we cancelled prematurely. * * @param page_res page structure * @param monitor progress monitor * @param word_config word_config file * @param target_word_box specifies just to extract a rectangle * @param dopasses 0 - all, 1 just pass 1, 2 passes 2 and higher */ bool Tesseract::recog_all_words(PAGE_RES* page_res, ETEXT_DESC* monitor, const TBOX* target_word_box, const char* word_config, int dopasses) { PAGE_RES_IT page_res_it(page_res); if (tessedit_minimal_rej_pass1) { tessedit_test_adaption.set_value (TRUE); tessedit_minimal_rejection.set_value (TRUE); } if (dopasses==0 || dopasses==1) { page_res_it.restart_page(); // ****************** Pass 1 ******************* // Clear adaptive classifier at the beginning of the page if it is full. // This is done only at the beginning of the page to ensure that the // classifier is not reset at an arbitrary point while processing the page, // which would cripple Passes 2+ if the reset happens towards the end of // Pass 1 on a page with very difficult text. // TODO(daria): preemptively clear the classifier if it is almost full. if (AdaptiveClassifierIsFull()) ResetAdaptiveClassifierInternal(); // Now check the sub-langs as well. for (int i = 0; i < sub_langs_.size(); ++i) { if (sub_langs_[i]->AdaptiveClassifierIsFull()) sub_langs_[i]->ResetAdaptiveClassifierInternal(); } // Set up all words ready for recognition, so that if parallelism is on // all the input and output classes are ready to run the classifier. GenericVector<WordData> words; SetupAllWordsPassN(1, target_word_box, word_config, page_res, &words); if (tessedit_parallelize) { PrerecAllWordsPar(words); } stats_.word_count = words.size(); stats_.dict_words = 0; stats_.doc_blob_quality = 0; stats_.doc_outline_errs = 0; stats_.doc_char_quality = 0; stats_.good_char_count = 0; stats_.doc_good_char_quality = 0; most_recently_used_ = this; // Run pass 1 word recognition. if (!RecogAllWordsPassN(1, monitor, &page_res_it, &words)) return false; // Pass 1 post-processing. for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { if (page_res_it.word()->word->flag(W_REP_CHAR)) { fix_rep_char(&page_res_it); continue; } // Count dict words. if (page_res_it.word()->best_choice->permuter() == USER_DAWG_PERM) ++(stats_.dict_words); // Update misadaption log (we only need to do it on pass 1, since // adaption only happens on this pass). if (page_res_it.word()->blamer_bundle != NULL && page_res_it.word()->blamer_bundle->misadaption_debug().length() > 0) { page_res->misadaption_log.push_back( page_res_it.word()->blamer_bundle->misadaption_debug()); } } } if (dopasses == 1) return true; // ****************** Pass 2 ******************* if (tessedit_tess_adaption_mode != 0x0 && !tessedit_test_adaption && AnyTessLang()) { page_res_it.restart_page(); GenericVector<WordData> words; SetupAllWordsPassN(2, target_word_box, word_config, page_res, &words); if (tessedit_parallelize) { PrerecAllWordsPar(words); } most_recently_used_ = this; // Run pass 2 word recognition. if (!RecogAllWordsPassN(2, monitor, &page_res_it, &words)) return false; } // The next passes can only be run if tesseract has been used, as cube // doesn't set all the necessary outputs in WERD_RES. if (AnyTessLang()) { // ****************** Pass 3 ******************* // Fix fuzzy spaces. set_global_loc_code(LOC_FUZZY_SPACE); if (!tessedit_test_adaption && tessedit_fix_fuzzy_spaces && !tessedit_word_for_word && !right_to_left()) fix_fuzzy_spaces(monitor, stats_.word_count, page_res); // ****************** Pass 4 ******************* if (tessedit_enable_dict_correction) dictionary_correction_pass(page_res); if (tessedit_enable_bigram_correction) bigram_correction_pass(page_res); // ****************** Pass 5,6 ******************* rejection_passes(page_res, monitor, target_word_box, word_config); // ****************** Pass 7 ******************* // Cube combiner. // If cube is loaded and its combiner is present, run it. if (tessedit_ocr_engine_mode == OEM_TESSERACT_CUBE_COMBINED) { run_cube_combiner(page_res); } // ****************** Pass 8 ******************* font_recognition_pass(page_res); // ****************** Pass 9 ******************* // Check the correctness of the final results. blamer_pass(page_res); script_pos_pass(page_res); } // Write results pass. set_global_loc_code(LOC_WRITE_RESULTS); // This is now redundant, but retained commented so show how to obtain // bounding boxes and style information. // changed by jetsoft // needed for dll to output memory structure if ((dopasses == 0 || dopasses == 2) && (monitor || tessedit_write_unlv)) output_pass(page_res_it, target_word_box); // end jetsoft PageSegMode pageseg_mode = static_cast<PageSegMode>( static_cast<int>(tessedit_pageseg_mode)); textord_.CleanupSingleRowResult(pageseg_mode, page_res); // Remove empty words, as these mess up the result iterators. for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { WERD_RES* word = page_res_it.word(); if (word->best_choice == NULL || word->best_choice->length() == 0) page_res_it.DeleteCurrentWord(); } if (monitor != NULL) { monitor->progress = 100; } return true; } void Tesseract::bigram_correction_pass(PAGE_RES *page_res) { PAGE_RES_IT word_it(page_res); WERD_RES *w_prev = NULL; WERD_RES *w = word_it.word(); while (1) { w_prev = w; while (word_it.forward() != NULL && (!word_it.word() || word_it.word()->part_of_combo)) { // advance word_it, skipping over parts of combos } if (!word_it.word()) break; w = word_it.word(); if (!w || !w_prev || w->uch_set != w_prev->uch_set) { continue; } if (w_prev->word->flag(W_REP_CHAR) || w->word->flag(W_REP_CHAR)) { if (tessedit_bigram_debug) { tprintf("Skipping because one of the words is W_REP_CHAR\n"); } continue; } // Two words sharing the same language model, excellent! GenericVector<WERD_CHOICE *> overrides_word1; GenericVector<WERD_CHOICE *> overrides_word2; STRING orig_w1_str = w_prev->best_choice->unichar_string(); STRING orig_w2_str = w->best_choice->unichar_string(); WERD_CHOICE prev_best(w->uch_set); { int w1start, w1end; w_prev->best_choice->GetNonSuperscriptSpan(&w1start, &w1end); prev_best = w_prev->best_choice->shallow_copy(w1start, w1end); } WERD_CHOICE this_best(w->uch_set); { int w2start, w2end; w->best_choice->GetNonSuperscriptSpan(&w2start, &w2end); this_best = w->best_choice->shallow_copy(w2start, w2end); } if (w->tesseract->getDict().valid_bigram(prev_best, this_best)) { if (tessedit_bigram_debug) { tprintf("Top choice \"%s %s\" verified by bigram model.\n", orig_w1_str.string(), orig_w2_str.string()); } continue; } if (tessedit_bigram_debug > 2) { tprintf("Examining alt choices for \"%s %s\".\n", orig_w1_str.string(), orig_w2_str.string()); } if (tessedit_bigram_debug > 1) { if (!w_prev->best_choices.singleton()) { w_prev->PrintBestChoices(); } if (!w->best_choices.singleton()) { w->PrintBestChoices(); } } float best_rating = 0.0; int best_idx = 0; WERD_CHOICE_IT prev_it(&w_prev->best_choices); for (prev_it.mark_cycle_pt(); !prev_it.cycled_list(); prev_it.forward()) { WERD_CHOICE *p1 = prev_it.data(); WERD_CHOICE strip1(w->uch_set); { int p1start, p1end; p1->GetNonSuperscriptSpan(&p1start, &p1end); strip1 = p1->shallow_copy(p1start, p1end); } WERD_CHOICE_IT w_it(&w->best_choices); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD_CHOICE *p2 = w_it.data(); WERD_CHOICE strip2(w->uch_set); { int p2start, p2end; p2->GetNonSuperscriptSpan(&p2start, &p2end); strip2 = p2->shallow_copy(p2start, p2end); } if (w->tesseract->getDict().valid_bigram(strip1, strip2)) { overrides_word1.push_back(p1); overrides_word2.push_back(p2); if (overrides_word1.size() == 1 || p1->rating() + p2->rating() < best_rating) { best_rating = p1->rating() + p2->rating(); best_idx = overrides_word1.size() - 1; } } } } if (overrides_word1.size() >= 1) { // Excellent, we have some bigram matches. if (EqualIgnoringCaseAndTerminalPunct(*w_prev->best_choice, *overrides_word1[best_idx]) && EqualIgnoringCaseAndTerminalPunct(*w->best_choice, *overrides_word2[best_idx])) { if (tessedit_bigram_debug > 1) { tprintf("Top choice \"%s %s\" verified (sans case) by bigram " "model.\n", orig_w1_str.string(), orig_w2_str.string()); } continue; } STRING new_w1_str = overrides_word1[best_idx]->unichar_string(); STRING new_w2_str = overrides_word2[best_idx]->unichar_string(); if (new_w1_str != orig_w1_str) { w_prev->ReplaceBestChoice(overrides_word1[best_idx]); } if (new_w2_str != orig_w2_str) { w->ReplaceBestChoice(overrides_word2[best_idx]); } if (tessedit_bigram_debug > 0) { STRING choices_description; int num_bigram_choices = overrides_word1.size() * overrides_word2.size(); if (num_bigram_choices == 1) { choices_description = "This was the unique bigram choice."; } else { if (tessedit_bigram_debug > 1) { STRING bigrams_list; const int kMaxChoicesToPrint = 20; for (int i = 0; i < overrides_word1.size() && i < kMaxChoicesToPrint; i++) { if (i > 0) { bigrams_list += ", "; } WERD_CHOICE *p1 = overrides_word1[i]; WERD_CHOICE *p2 = overrides_word2[i]; bigrams_list += p1->unichar_string() + " " + p2->unichar_string(); if (i == kMaxChoicesToPrint) { bigrams_list += " ..."; } } choices_description = "There were many choices: {"; choices_description += bigrams_list; choices_description += "}"; } else { choices_description.add_str_int("There were ", num_bigram_choices); choices_description += " compatible bigrams."; } } tprintf("Replaced \"%s %s\" with \"%s %s\" with bigram model. %s\n", orig_w1_str.string(), orig_w2_str.string(), new_w1_str.string(), new_w2_str.string(), choices_description.string()); } } } } void Tesseract::rejection_passes(PAGE_RES* page_res, ETEXT_DESC* monitor, const TBOX* target_word_box, const char* word_config) { PAGE_RES_IT page_res_it(page_res); // ****************** Pass 5 ******************* // Gather statistics on rejects. int word_index = 0; while (!tessedit_test_adaption && page_res_it.word() != NULL) { set_global_loc_code(LOC_MM_ADAPT); WERD_RES* word = page_res_it.word(); word_index++; if (monitor != NULL) { monitor->ocr_alive = TRUE; monitor->progress = 95 + 5 * word_index / stats_.word_count; } if (word->rebuild_word == NULL) { // Word was not processed by tesseract. page_res_it.forward(); continue; } check_debug_pt(word, 70); // changed by jetsoft // specific to its needs to extract one word when need if (target_word_box && !ProcessTargetWord(word->word->bounding_box(), *target_word_box, word_config, 4)) { page_res_it.forward(); continue; } // end jetsoft page_res_it.rej_stat_word(); int chars_in_word = word->reject_map.length(); int rejects_in_word = word->reject_map.reject_count(); int blob_quality = word_blob_quality(word, page_res_it.row()->row); stats_.doc_blob_quality += blob_quality; int outline_errs = word_outline_errs(word); stats_.doc_outline_errs += outline_errs; inT16 all_char_quality; inT16 accepted_all_char_quality; word_char_quality(word, page_res_it.row()->row, &all_char_quality, &accepted_all_char_quality); stats_.doc_char_quality += all_char_quality; uinT8 permuter_type = word->best_choice->permuter(); if ((permuter_type == SYSTEM_DAWG_PERM) || (permuter_type == FREQ_DAWG_PERM) || (permuter_type == USER_DAWG_PERM)) { stats_.good_char_count += chars_in_word - rejects_in_word; stats_.doc_good_char_quality += accepted_all_char_quality; } check_debug_pt(word, 80); if (tessedit_reject_bad_qual_wds && (blob_quality == 0) && (outline_errs >= chars_in_word)) word->reject_map.rej_word_bad_quality(); check_debug_pt(word, 90); page_res_it.forward(); } if (tessedit_debug_quality_metrics) { tprintf ("QUALITY: num_chs= %d num_rejs= %d %5.3f blob_qual= %d %5.3f" " outline_errs= %d %5.3f char_qual= %d %5.3f good_ch_qual= %d %5.3f\n", page_res->char_count, page_res->rej_count, page_res->rej_count / static_cast<float>(page_res->char_count), stats_.doc_blob_quality, stats_.doc_blob_quality / static_cast<float>(page_res->char_count), stats_.doc_outline_errs, stats_.doc_outline_errs / static_cast<float>(page_res->char_count), stats_.doc_char_quality, stats_.doc_char_quality / static_cast<float>(page_res->char_count), stats_.doc_good_char_quality, (stats_.good_char_count > 0) ? (stats_.doc_good_char_quality / static_cast<float>(stats_.good_char_count)) : 0.0); } BOOL8 good_quality_doc = ((page_res->rej_count / static_cast<float>(page_res->char_count)) <= quality_rej_pc) && (stats_.doc_blob_quality / static_cast<float>(page_res->char_count) >= quality_blob_pc) && (stats_.doc_outline_errs / static_cast<float>(page_res->char_count) <= quality_outline_pc) && (stats_.doc_char_quality / static_cast<float>(page_res->char_count) >= quality_char_pc); // ****************** Pass 6 ******************* // Do whole document or whole block rejection pass if (!tessedit_test_adaption) { set_global_loc_code(LOC_DOC_BLK_REJ); quality_based_rejection(page_res_it, good_quality_doc); } } void Tesseract::blamer_pass(PAGE_RES* page_res) { if (!wordrec_run_blamer) return; PAGE_RES_IT page_res_it(page_res); for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { WERD_RES *word = page_res_it.word(); BlamerBundle::LastChanceBlame(wordrec_debug_blamer, word); page_res->blame_reasons[word->blamer_bundle->incorrect_result_reason()]++; } tprintf("Blame reasons:\n"); for (int bl = 0; bl < IRR_NUM_REASONS; ++bl) { tprintf("%s %d\n", BlamerBundle::IncorrectReasonName( static_cast<IncorrectResultReason>(bl)), page_res->blame_reasons[bl]); } if (page_res->misadaption_log.length() > 0) { tprintf("Misadaption log:\n"); for (int i = 0; i < page_res->misadaption_log.length(); ++i) { tprintf("%s\n", page_res->misadaption_log[i].string()); } } } // Sets script positions and detects smallcaps on all output words. void Tesseract::script_pos_pass(PAGE_RES* page_res) { PAGE_RES_IT page_res_it(page_res); for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { WERD_RES* word = page_res_it.word(); if (word->word->flag(W_REP_CHAR)) { page_res_it.forward(); continue; } float x_height = page_res_it.block()->block->x_height(); float word_x_height = word->x_height; if (word_x_height < word->best_choice->min_x_height() || word_x_height > word->best_choice->max_x_height()) { word_x_height = (word->best_choice->min_x_height() + word->best_choice->max_x_height()) / 2.0f; } // Test for small caps. Word capheight must be close to block xheight, // and word must contain no lower case letters, and at least one upper case. double small_cap_xheight = x_height * kXHeightCapRatio; double small_cap_delta = (x_height - small_cap_xheight) / 2.0; if (word->uch_set->script_has_xheight() && small_cap_xheight - small_cap_delta <= word_x_height && word_x_height <= small_cap_xheight + small_cap_delta) { // Scan for upper/lower. int num_upper = 0; int num_lower = 0; for (int i = 0; i < word->best_choice->length(); ++i) { if (word->uch_set->get_isupper(word->best_choice->unichar_id(i))) ++num_upper; else if (word->uch_set->get_islower(word->best_choice->unichar_id(i))) ++num_lower; } if (num_upper > 0 && num_lower == 0) word->small_caps = true; } word->SetScriptPositions(); } } // Factored helper considers the indexed word and updates all the pointed // values. static void EvaluateWord(const PointerVector<WERD_RES>& words, int index, float* rating, float* certainty, bool* bad, bool* valid_permuter, int* right, int* next_left) { *right = -MAX_INT32; *next_left = MAX_INT32; if (index < words.size()) { WERD_CHOICE* choice = words[index]->best_choice; if (choice == NULL) { *bad = true; } else { *rating += choice->rating(); *certainty = MIN(*certainty, choice->certainty()); if (!Dict::valid_word_permuter(choice->permuter(), false)) *valid_permuter = false; } *right = words[index]->word->bounding_box().right(); if (index + 1 < words.size()) *next_left = words[index + 1]->word->bounding_box().left(); } else { *valid_permuter = false; *bad = true; } } // Helper chooses the best combination of words, transferring good ones from // new_words to best_words. To win, a new word must have (better rating and // certainty) or (better permuter status and rating within rating ratio and // certainty within certainty margin) than current best. // All the new_words are consumed (moved to best_words or deleted.) // The return value is the number of new_words used minus the number of // best_words that remain in the output. static int SelectBestWords(double rating_ratio, double certainty_margin, bool debug, PointerVector<WERD_RES>* new_words, PointerVector<WERD_RES>* best_words) { // Process the smallest groups of words that have an overlapping word // boundary at the end. GenericVector<WERD_RES*> out_words; // Index into each word vector (best, new). int b = 0, n = 0; int num_best = 0, num_new = 0; while (b < best_words->size() || n < new_words->size()) { // Start of the current run in each. int start_b = b, start_n = n; // Rating of the current run in each. float b_rating = 0.0f, n_rating = 0.0f; // Certainty of the current run in each. float b_certainty = 0.0f, n_certainty = 0.0f; // True if any word is missing its best choice. bool b_bad = false, n_bad = false; // True if all words have a valid permuter. bool b_valid_permuter = true, n_valid_permuter = true; while (b < best_words->size() || n < new_words->size()) { int b_right = -MAX_INT32; int next_b_left = MAX_INT32; EvaluateWord(*best_words, b, &b_rating, &b_certainty, &b_bad, &b_valid_permuter, &b_right, &next_b_left); int n_right = -MAX_INT32; int next_n_left = MAX_INT32; EvaluateWord(*new_words, n, &n_rating, &n_certainty, &n_bad, &n_valid_permuter, &n_right, &next_n_left); if (MAX(b_right, n_right) < MIN(next_b_left, next_n_left)) { // The word breaks overlap. [start_b,b] and [start_n, n] match. break; } // Keep searching for the matching word break. if ((b_right < n_right && b < best_words->size()) || n == new_words->size()) ++b; else ++n; } bool new_better = false; if (!n_bad && (b_bad || (n_certainty > b_certainty && n_rating < b_rating) || (!b_valid_permuter && n_valid_permuter && n_rating < b_rating * rating_ratio && n_certainty > b_certainty - certainty_margin))) { // New is better. for (int i = start_n; i <= n; ++i) { out_words.push_back((*new_words)[i]); (*new_words)[i] = NULL; ++num_new; } new_better = true; } else if (!b_bad) { // Current best is better. for (int i = start_b; i <= b; ++i) { out_words.push_back((*best_words)[i]); (*best_words)[i] = NULL; ++num_best; } } int end_b = b < best_words->size() ? b + 1 : b; int end_n = n < new_words->size() ? n + 1 : n; if (debug) { tprintf("%d new words %s than %d old words: r: %g v %g c: %g v %g" " valid dict: %d v %d\n", end_n - start_n, new_better ? "better" : "worse", end_b - start_b, n_rating, b_rating, n_certainty, b_certainty, n_valid_permuter, b_valid_permuter); } // Move on to the next group. b = end_b; n = end_n; } // Transfer from out_words to best_words. best_words->clear(); for (int i = 0; i < out_words.size(); ++i) best_words->push_back(out_words[i]); return num_new - num_best; } // Helper to recognize the word using the given (language-specific) tesseract. // Returns positive if this recognizer found more new best words than the // number kept from best_words. int Tesseract::RetryWithLanguage(const WordData& word_data, WordRecognizer recognizer, WERD_RES** in_word, PointerVector<WERD_RES>* best_words) { bool debug = classify_debug_level || cube_debug_level; if (debug) { tprintf("Trying word using lang %s, oem %d\n", lang.string(), static_cast<int>(tessedit_ocr_engine_mode)); } // Run the recognizer on the word. PointerVector<WERD_RES> new_words; (this->*recognizer)(word_data, in_word, &new_words); if (new_words.empty()) { // Transfer input word to new_words, as the classifier must have put // the result back in the input. new_words.push_back(*in_word); *in_word = NULL; } if (debug) { for (int i = 0; i < new_words.size(); ++i) new_words[i]->DebugTopChoice("Lang result"); } // Initial version is a bit of a hack based on better certainty and rating // (to reduce false positives from cube) or a dictionary vs non-dictionary // word. return SelectBestWords(classify_max_rating_ratio, classify_max_certainty_margin, debug, &new_words, best_words); } // Helper returns true if all the words are acceptable. static bool WordsAcceptable(const PointerVector<WERD_RES>& words) { for (int w = 0; w < words.size(); ++w) { if (words[w]->tess_failed || !words[w]->tess_accepted) return false; } return true; } // Generic function for classifying a word. Can be used either for pass1 or // pass2 according to the function passed to recognizer. // word_data holds the word to be recognized, and its block and row, and // pr_it points to the word as well, in case we are running LSTM and it wants // to output multiple words. // Recognizes in the current language, and if successful that is all. // If recognition was not successful, tries all available languages until // it gets a successful result or runs out of languages. Keeps the best result. void Tesseract::classify_word_and_language(WordRecognizer recognizer, PAGE_RES_IT* pr_it, WordData* word_data) { // Best result so far. PointerVector<WERD_RES> best_words; // Points to the best result. May be word or in lang_words. WERD_RES* word = word_data->word; clock_t start_t = clock(); if (classify_debug_level || cube_debug_level) { tprintf("%s word with lang %s at:", word->done ? "Already done" : "Processing", most_recently_used_->lang.string()); word->word->bounding_box().print(); } if (word->done) { // If done on pass1, leave it as-is. if (!word->tess_failed) most_recently_used_ = word->tesseract; return; } int sub = sub_langs_.size(); if (most_recently_used_ != this) { // Get the index of the most_recently_used_. for (sub = 0; sub < sub_langs_.size() && most_recently_used_ != sub_langs_[sub]; ++sub) {} } most_recently_used_->RetryWithLanguage( *word_data, recognizer, &word_data->lang_words[sub], &best_words); Tesseract* best_lang_tess = most_recently_used_; if (!WordsAcceptable(best_words)) { // Try all the other languages to see if they are any better. if (most_recently_used_ != this && this->RetryWithLanguage(*word_data, recognizer, &word_data->lang_words[sub_langs_.size()], &best_words) > 0) { best_lang_tess = this; } for (int i = 0; !WordsAcceptable(best_words) && i < sub_langs_.size(); ++i) { if (most_recently_used_ != sub_langs_[i] && sub_langs_[i]->RetryWithLanguage(*word_data, recognizer, &word_data->lang_words[i], &best_words) > 0) { best_lang_tess = sub_langs_[i]; } } } most_recently_used_ = best_lang_tess; if (!best_words.empty()) { if (best_words.size() == 1 && !best_words[0]->combination) { // Move the best single result to the main word. word_data->word->ConsumeWordResults(best_words[0]); } else { // Words came from LSTM, and must be moved to the PAGE_RES properly. word_data->word = best_words.back(); pr_it->ReplaceCurrentWord(&best_words); } ASSERT_HOST(word_data->word->box_word != NULL); } else { tprintf("no best words!!\n"); } clock_t ocr_t = clock(); if (tessedit_timing_debug) { tprintf("%s (ocr took %.2f sec)\n", word->best_choice->unichar_string().string(), static_cast<double>(ocr_t-start_t)/CLOCKS_PER_SEC); } } /** * classify_word_pass1 * * Baseline normalize the word and pass it to Tess. */ void Tesseract::classify_word_pass1(const WordData& word_data, WERD_RES** in_word, PointerVector<WERD_RES>* out_words) { ROW* row = word_data.row; BLOCK* block = word_data.block; prev_word_best_choice_ = word_data.prev_word != NULL ? word_data.prev_word->word->best_choice : NULL; // If we only intend to run cube - run it and return. if (tessedit_ocr_engine_mode == OEM_CUBE_ONLY) { cube_word_pass1(block, row, *in_word); return; } WERD_RES* word = *in_word; match_word_pass_n(1, word, row, block); if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) { word->tess_would_adapt = AdaptableWord(word); bool adapt_ok = word_adaptable(word, tessedit_tess_adaption_mode); if (adapt_ok) { // Send word to adaptive classifier for training. word->BestChoiceToCorrectText(); LearnWord(NULL, word); // Mark misadaptions if running blamer. if (word->blamer_bundle != NULL) { word->blamer_bundle->SetMisAdaptionDebug(word->best_choice, wordrec_debug_blamer); } } if (tessedit_enable_doc_dict && !word->IsAmbiguous()) tess_add_doc_word(word->best_choice); } } // Helper to report the result of the xheight fix. void Tesseract::ReportXhtFixResult(bool accept_new_word, float new_x_ht, WERD_RES* word, WERD_RES* new_word) { tprintf("New XHT Match:%s = %s ", word->best_choice->unichar_string().string(), word->best_choice->debug_string().string()); word->reject_map.print(debug_fp); tprintf(" -> %s = %s ", new_word->best_choice->unichar_string().string(), new_word->best_choice->debug_string().string()); new_word->reject_map.print(debug_fp); tprintf(" %s->%s %s %s\n", word->guessed_x_ht ? "GUESS" : "CERT", new_word->guessed_x_ht ? "GUESS" : "CERT", new_x_ht > 0.1 ? "STILL DOUBT" : "OK", accept_new_word ? "ACCEPTED" : ""); } // Run the x-height fix-up, based on min/max top/bottom information in // unicharset. // Returns true if the word was changed. // See the comment in fixxht.cpp for a description of the overall process. bool Tesseract::TrainedXheightFix(WERD_RES *word, BLOCK* block, ROW *row) { bool accept_new_x_ht = false; int original_misfits = CountMisfitTops(word); if (original_misfits == 0) return false; float new_x_ht = ComputeCompatibleXheight(word); if (new_x_ht >= kMinRefitXHeightFraction * word->x_height) { WERD_RES new_x_ht_word(word->word); if (word->blamer_bundle != NULL) { new_x_ht_word.blamer_bundle = new BlamerBundle(); new_x_ht_word.blamer_bundle->CopyTruth(*(word->blamer_bundle)); } new_x_ht_word.x_height = new_x_ht; new_x_ht_word.caps_height = 0.0; new_x_ht_word.SetupForRecognition( unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL, classify_bln_numeric_mode, textord_use_cjk_fp_model, poly_allow_detailed_fx, row, block); match_word_pass_n(2, &new_x_ht_word, row, block); if (!new_x_ht_word.tess_failed) { int new_misfits = CountMisfitTops(&new_x_ht_word); if (debug_x_ht_level >= 1) { tprintf("Old misfits=%d with x-height %f, new=%d with x-height %f\n", original_misfits, word->x_height, new_misfits, new_x_ht); tprintf("Old rating= %f, certainty=%f, new=%f, %f\n", word->best_choice->rating(), word->best_choice->certainty(), new_x_ht_word.best_choice->rating(), new_x_ht_word.best_choice->certainty()); } // The misfits must improve and either the rating or certainty. accept_new_x_ht = new_misfits < original_misfits && (new_x_ht_word.best_choice->certainty() > word->best_choice->certainty() || new_x_ht_word.best_choice->rating() < word->best_choice->rating()); if (debug_x_ht_level >= 1) { ReportXhtFixResult(accept_new_x_ht, new_x_ht, word, &new_x_ht_word); } } if (accept_new_x_ht) { word->ConsumeWordResults(&new_x_ht_word); return true; } } return false; } /** * classify_word_pass2 * * Control what to do with the word in pass 2 */ void Tesseract::classify_word_pass2(const WordData& word_data, WERD_RES** in_word, PointerVector<WERD_RES>* out_words) { // Return if we do not want to run Tesseract. if (tessedit_ocr_engine_mode != OEM_TESSERACT_ONLY && tessedit_ocr_engine_mode != OEM_TESSERACT_CUBE_COMBINED && word_data.word->best_choice != NULL) return; if (tessedit_ocr_engine_mode == OEM_CUBE_ONLY) { return; } ROW* row = word_data.row; BLOCK* block = word_data.block; WERD_RES* word = *in_word; prev_word_best_choice_ = word_data.prev_word != NULL ? word_data.prev_word->word->best_choice : NULL; set_global_subloc_code(SUBLOC_NORM); check_debug_pt(word, 30); if (!word->done) { word->caps_height = 0.0; if (word->x_height == 0.0f) word->x_height = row->x_height(); match_word_pass_n(2, word, row, block); check_debug_pt(word, 40); } SubAndSuperscriptFix(word); if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) { if (unicharset.top_bottom_useful() && unicharset.script_has_xheight() && block->classify_rotation().y() == 0.0f) { // Use the tops and bottoms since they are available. TrainedXheightFix(word, block, row); } set_global_subloc_code(SUBLOC_NORM); } #ifndef GRAPHICS_DISABLED if (tessedit_display_outwords) { if (fx_win == NULL) create_fx_win(); clear_fx_win(); word->rebuild_word->plot(fx_win); TBOX wbox = word->rebuild_word->bounding_box(); fx_win->ZoomToRectangle(wbox.left(), wbox.top(), wbox.right(), wbox.bottom()); ScrollView::Update(); } #endif set_global_subloc_code(SUBLOC_NORM); check_debug_pt(word, 50); } /** * match_word_pass2 * * Baseline normalize the word and pass it to Tess. */ void Tesseract::match_word_pass_n(int pass_n, WERD_RES *word, ROW *row, BLOCK* block) { if (word->tess_failed) return; tess_segment_pass_n(pass_n, word); if (!word->tess_failed) { if (!word->word->flag (W_REP_CHAR)) { word->fix_quotes(); if (tessedit_fix_hyphens) word->fix_hyphens(); /* Dont trust fix_quotes! - though I think I've fixed the bug */ if (word->best_choice->length() != word->box_word->length()) { tprintf("POST FIX_QUOTES FAIL String:\"%s\"; Strlen=%d;" " #Blobs=%d\n", word->best_choice->debug_string().string(), word->best_choice->length(), word->box_word->length()); } word->tess_accepted = tess_acceptable_word(word); // Also sets word->done flag make_reject_map(word, row, pass_n); } } set_word_fonts(word); ASSERT_HOST(word->raw_choice != NULL); } // Helper to return the best rated BLOB_CHOICE in the whole word that matches // the given char_id, or NULL if none can be found. static BLOB_CHOICE* FindBestMatchingChoice(UNICHAR_ID char_id, WERD_RES* word_res) { // Find the corresponding best BLOB_CHOICE from any position in the word_res. BLOB_CHOICE* best_choice = NULL; for (int i = 0; i < word_res->best_choice->length(); ++i) { BLOB_CHOICE* choice = FindMatchingChoice(char_id, word_res->GetBlobChoices(i)); if (choice != NULL) { if (best_choice == NULL || choice->rating() < best_choice->rating()) best_choice = choice; } } return best_choice; } // Helper to insert blob_choice in each location in the leader word if there is // no matching BLOB_CHOICE there already, and correct any incorrect results // in the best_choice. static void CorrectRepcharChoices(BLOB_CHOICE* blob_choice, WERD_RES* word_res) { WERD_CHOICE* word = word_res->best_choice; for (int i = 0; i < word_res->best_choice->length(); ++i) { BLOB_CHOICE* choice = FindMatchingChoice(blob_choice->unichar_id(), word_res->GetBlobChoices(i)); if (choice == NULL) { BLOB_CHOICE_IT choice_it(word_res->GetBlobChoices(i)); choice_it.add_before_stay_put(new BLOB_CHOICE(*blob_choice)); } } // Correct any incorrect results in word. for (int i = 0; i < word->length(); ++i) { if (word->unichar_id(i) != blob_choice->unichar_id()) word->set_unichar_id(blob_choice->unichar_id(), i); } } /** * fix_rep_char() * The word is a repeated char. (Leader.) Find the repeated char character. * Create the appropriate single-word or multi-word sequence according to * the size of spaces in between blobs, and correct the classifications * where some of the characters disagree with the majority. */ void Tesseract::fix_rep_char(PAGE_RES_IT* page_res_it) { WERD_RES *word_res = page_res_it->word(); const WERD_CHOICE &word = *(word_res->best_choice); // Find the frequency of each unique character in the word. SortHelper<UNICHAR_ID> rep_ch(word.length()); for (int i = 0; i < word.length(); ++i) { rep_ch.Add(word.unichar_id(i), 1); } // Find the most frequent result. UNICHAR_ID maxch_id = INVALID_UNICHAR_ID; // most common char int max_count = rep_ch.MaxCount(&maxch_id); // Find the best exemplar of a classifier result for maxch_id. BLOB_CHOICE* best_choice = FindBestMatchingChoice(maxch_id, word_res); if (best_choice == NULL) { tprintf("Failed to find a choice for %s, occurring %d times\n", word_res->uch_set->debug_str(maxch_id).string(), max_count); return; } word_res->done = TRUE; // Measure the mean space. int gap_count = 0; WERD* werd = word_res->word; C_BLOB_IT blob_it(werd->cblob_list()); C_BLOB* prev_blob = blob_it.data(); for (blob_it.forward(); !blob_it.at_first(); blob_it.forward()) { C_BLOB* blob = blob_it.data(); int gap = blob->bounding_box().left(); gap -= prev_blob->bounding_box().right(); ++gap_count; prev_blob = blob; } // Just correct existing classification. CorrectRepcharChoices(best_choice, word_res); word_res->reject_map.initialise(word.length()); } ACCEPTABLE_WERD_TYPE Tesseract::acceptable_word_string( const UNICHARSET& char_set, const char *s, const char *lengths) { int i = 0; int offset = 0; int leading_punct_count; int upper_count = 0; int hyphen_pos = -1; ACCEPTABLE_WERD_TYPE word_type = AC_UNACCEPTABLE; if (strlen (lengths) > 20) return word_type; /* Single Leading punctuation char*/ if (s[offset] != '\0' && STRING(chs_leading_punct).contains(s[offset])) offset += lengths[i++]; leading_punct_count = i; /* Initial cap */ while (s[offset] != '\0' && char_set.get_isupper(s + offset, lengths[i])) { offset += lengths[i++]; upper_count++; } if (upper_count > 1) { word_type = AC_UPPER_CASE; } else { /* Lower case word, possibly with an initial cap */ while (s[offset] != '\0' && char_set.get_islower(s + offset, lengths[i])) { offset += lengths[i++]; } if (i - leading_punct_count < quality_min_initial_alphas_reqd) goto not_a_word; /* Allow a single hyphen in a lower case word - dont trust upper case - I've seen several cases of "H" -> "I-I" */ if (lengths[i] == 1 && s[offset] == '-') { hyphen_pos = i; offset += lengths[i++]; if (s[offset] != '\0') { while ((s[offset] != '\0') && char_set.get_islower(s + offset, lengths[i])) { offset += lengths[i++]; } if (i < hyphen_pos + 3) goto not_a_word; } } else { /* Allow "'s" in NON hyphenated lower case words */ if (lengths[i] == 1 && (s[offset] == '\'') && lengths[i + 1] == 1 && (s[offset + lengths[i]] == 's')) { offset += lengths[i++]; offset += lengths[i++]; } } if (upper_count > 0) word_type = AC_INITIAL_CAP; else word_type = AC_LOWER_CASE; } /* Up to two different, constrained trailing punctuation chars */ if (lengths[i] == 1 && s[offset] != '\0' && STRING(chs_trailing_punct1).contains(s[offset])) offset += lengths[i++]; if (lengths[i] == 1 && s[offset] != '\0' && i > 0 && s[offset - lengths[i - 1]] != s[offset] && STRING(chs_trailing_punct2).contains (s[offset])) offset += lengths[i++]; if (s[offset] != '\0') word_type = AC_UNACCEPTABLE; not_a_word: if (word_type == AC_UNACCEPTABLE) { /* Look for abbreviation string */ i = 0; offset = 0; if (s[0] != '\0' && char_set.get_isupper(s, lengths[0])) { word_type = AC_UC_ABBREV; while (s[offset] != '\0' && char_set.get_isupper(s + offset, lengths[i]) && lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') { offset += lengths[i++]; offset += lengths[i++]; } } else if (s[0] != '\0' && char_set.get_islower(s, lengths[0])) { word_type = AC_LC_ABBREV; while (s[offset] != '\0' && char_set.get_islower(s + offset, lengths[i]) && lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') { offset += lengths[i++]; offset += lengths[i++]; } } if (s[offset] != '\0') word_type = AC_UNACCEPTABLE; } return word_type; } BOOL8 Tesseract::check_debug_pt(WERD_RES *word, int location) { BOOL8 show_map_detail = FALSE; inT16 i; if (!test_pt) return FALSE; tessedit_rejection_debug.set_value (FALSE); debug_x_ht_level.set_value (0); if (word->word->bounding_box ().contains (FCOORD (test_pt_x, test_pt_y))) { if (location < 0) return TRUE; // For breakpoint use tessedit_rejection_debug.set_value (TRUE); debug_x_ht_level.set_value (20); tprintf ("\n\nTESTWD::"); switch (location) { case 0: tprintf ("classify_word_pass1 start\n"); word->word->print(); break; case 10: tprintf ("make_reject_map: initial map"); break; case 20: tprintf ("make_reject_map: after NN"); break; case 30: tprintf ("classify_word_pass2 - START"); break; case 40: tprintf ("classify_word_pass2 - Pre Xht"); break; case 50: tprintf ("classify_word_pass2 - END"); show_map_detail = TRUE; break; case 60: tprintf ("fixspace"); break; case 70: tprintf ("MM pass START"); break; case 80: tprintf ("MM pass END"); break; case 90: tprintf ("After Poor quality rejection"); break; case 100: tprintf ("unrej_good_quality_words - START"); break; case 110: tprintf ("unrej_good_quality_words - END"); break; case 120: tprintf ("Write results pass"); show_map_detail = TRUE; break; } if (word->best_choice != NULL) { tprintf(" \"%s\" ", word->best_choice->unichar_string().string()); word->reject_map.print(debug_fp); tprintf("\n"); if (show_map_detail) { tprintf("\"%s\"\n", word->best_choice->unichar_string().string()); for (i = 0; word->best_choice->unichar_string()[i] != '\0'; i++) { tprintf("**** \"%c\" ****\n", word->best_choice->unichar_string()[i]); word->reject_map[i].full_print(debug_fp); } } } else { tprintf("null best choice\n"); } tprintf ("Tess Accepted: %s\n", word->tess_accepted ? "TRUE" : "FALSE"); tprintf ("Done flag: %s\n\n", word->done ? "TRUE" : "FALSE"); return TRUE; } else { return FALSE; } } /** * find_modal_font * * Find the modal font and remove from the stats. */ static void find_modal_font( //good chars in word STATS *fonts, //font stats inT16 *font_out, //output font inT8 *font_count //output count ) { inT16 font; //font index inT32 count; //pile couat if (fonts->get_total () > 0) { font = (inT16) fonts->mode (); *font_out = font; count = fonts->pile_count (font); *font_count = count < MAX_INT8 ? count : MAX_INT8; fonts->add (font, -*font_count); } else { *font_out = -1; *font_count = 0; } } /** * set_word_fonts * * Get the fonts for the word. */ void Tesseract::set_word_fonts(WERD_RES *word) { // Don't try to set the word fonts for a cube word, as the configs // will be meaningless. if (word->chopped_word == NULL) return; ASSERT_HOST(word->best_choice != NULL); inT32 index; // char id index // character iterator BLOB_CHOICE_IT choice_it; // choice iterator int fontinfo_size = get_fontinfo_table().size(); int fontset_size = get_fontset_table().size(); if (fontinfo_size == 0 || fontset_size == 0) return; STATS fonts(0, fontinfo_size); // font counters word->italic = 0; word->bold = 0; if (!word->best_choice_fontinfo_ids.empty()) { word->best_choice_fontinfo_ids.clear(); } // Compute the modal font for the word for (index = 0; index < word->best_choice->length(); ++index) { UNICHAR_ID word_ch_id = word->best_choice->unichar_id(index); choice_it.set_to_list(word->GetBlobChoices(index)); if (tessedit_debug_fonts) { tprintf("Examining fonts in %s\n", word->best_choice->debug_string().string()); } for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) { UNICHAR_ID blob_ch_id = choice_it.data()->unichar_id(); if (blob_ch_id == word_ch_id) { if (tessedit_debug_fonts) { tprintf("%s font %s (%d) font2 %s (%d)\n", word->uch_set->id_to_unichar(blob_ch_id), choice_it.data()->fontinfo_id() < 0 ? "unknown" : fontinfo_table_.get(choice_it.data()->fontinfo_id()).name, choice_it.data()->fontinfo_id(), choice_it.data()->fontinfo_id2() < 0 ? "unknown" : fontinfo_table_.get(choice_it.data()->fontinfo_id2()).name, choice_it.data()->fontinfo_id2()); } // 1st choice font gets 2 pts, 2nd choice 1 pt. if (choice_it.data()->fontinfo_id() >= 0) { fonts.add(choice_it.data()->fontinfo_id(), 2); } if (choice_it.data()->fontinfo_id2() >= 0) { fonts.add(choice_it.data()->fontinfo_id2(), 1); } break; } } } inT16 font_id1, font_id2; find_modal_font(&fonts, &font_id1, &word->fontinfo_id_count); find_modal_font(&fonts, &font_id2, &word->fontinfo_id2_count); word->fontinfo = font_id1 >= 0 ? &fontinfo_table_.get(font_id1) : NULL; word->fontinfo2 = font_id2 >= 0 ? &fontinfo_table_.get(font_id2) : NULL; // All the blobs get the word's best choice font. for (int i = 0; i < word->best_choice->length(); ++i) { word->best_choice_fontinfo_ids.push_back(font_id1); } if (word->fontinfo_id_count > 0) { FontInfo fi = fontinfo_table_.get(font_id1); if (tessedit_debug_fonts) { if (word->fontinfo_id2_count > 0) { tprintf("Word modal font=%s, score=%d, 2nd choice %s/%d\n", fi.name, word->fontinfo_id_count, fontinfo_table_.get(font_id2).name, word->fontinfo_id2_count); } else { tprintf("Word modal font=%s, score=%d. No 2nd choice\n", fi.name, word->fontinfo_id_count); } } // 1st choices got 2 pts, so we need to halve the score for the mode. word->italic = (fi.is_italic() ? 1 : -1) * (word->fontinfo_id_count + 1) / 2; word->bold = (fi.is_bold() ? 1 : -1) * (word->fontinfo_id_count + 1) / 2; } } /** * font_recognition_pass * * Smooth the fonts for the document. */ void Tesseract::font_recognition_pass(PAGE_RES* page_res) { PAGE_RES_IT page_res_it(page_res); WERD_RES *word; // current word STATS doc_fonts(0, font_table_size_); // font counters // Gather font id statistics. for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { word = page_res_it.word(); if (word->fontinfo != NULL) { doc_fonts.add(word->fontinfo->universal_id, word->fontinfo_id_count); } if (word->fontinfo2 != NULL) { doc_fonts.add(word->fontinfo2->universal_id, word->fontinfo_id2_count); } } inT16 doc_font; // modal font inT8 doc_font_count; // modal font find_modal_font(&doc_fonts, &doc_font, &doc_font_count); if (doc_font_count == 0) return; // Get the modal font pointer. const FontInfo* modal_font = NULL; for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { word = page_res_it.word(); if (word->fontinfo != NULL && word->fontinfo->universal_id == doc_font) { modal_font = word->fontinfo; break; } if (word->fontinfo2 != NULL && word->fontinfo2->universal_id == doc_font) { modal_font = word->fontinfo2; break; } } ASSERT_HOST(modal_font != NULL); // Assign modal font to weak words. for (page_res_it.restart_page(); page_res_it.word() != NULL; page_res_it.forward()) { word = page_res_it.word(); int length = word->best_choice->length(); // 1st choices got 2 pts, so we need to halve the score for the mode. int count = (word->fontinfo_id_count + 1) / 2; if (!(count == length || (length > 3 && count >= length * 3 / 4))) { word->fontinfo = modal_font; // Counts only get 1 as it came from the doc. word->fontinfo_id_count = 1; word->italic = modal_font->is_italic() ? 1 : -1; word->bold = modal_font->is_bold() ? 1 : -1; } } } // If a word has multiple alternates check if the best choice is in the // dictionary. If not, replace it with an alternate that exists in the // dictionary. void Tesseract::dictionary_correction_pass(PAGE_RES *page_res) { PAGE_RES_IT word_it(page_res); for (WERD_RES* word = word_it.word(); word != NULL; word = word_it.forward()) { if (word->best_choices.singleton()) continue; // There are no alternates. WERD_CHOICE* best = word->best_choice; if (word->tesseract->getDict().valid_word(*best) != 0) continue; // The best choice is in the dictionary. WERD_CHOICE_IT choice_it(&word->best_choices); for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) { WERD_CHOICE* alternate = choice_it.data(); if (word->tesseract->getDict().valid_word(*alternate)) { // The alternate choice is in the dictionary. if (tessedit_bigram_debug) { tprintf("Dictionary correction replaces best choice '%s' with '%s'\n", best->unichar_string().string(), alternate->unichar_string().string()); } // Replace the 'best' choice with a better choice. word->ReplaceBestChoice(alternate); break; } } } } } // namespace tesseract
1080228-arabicocr11
ccmain/control.cpp
C++
asf20
61,507
/****************************************************************** * File: fixspace.cpp (Formerly fixspace.c) * Description: Implements a pass over the page res, exploring the alternative * spacing possibilities, trying to use context to improve the * word spacing * Author: Phil Cheatle * Created: Thu Oct 21 11:38:43 BST 1993 * * (C) Copyright 1993, 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. * **********************************************************************/ #include <ctype.h> #include "reject.h" #include "statistc.h" #include "control.h" #include "fixspace.h" #include "genblob.h" #include "tessvars.h" #include "tessbox.h" #include "globals.h" #include "tesseractclass.h" #define PERFECT_WERDS 999 #define MAXSPACING 128 /*max expected spacing in pix */ namespace tesseract { /** * @name fix_fuzzy_spaces() * Walk over the page finding sequences of words joined by fuzzy spaces. Extract * them as a sublist, process the sublist to find the optimal arrangement of * spaces then replace the sublist in the ROW_RES. * * @param monitor progress monitor * @param word_count count of words in doc * @param[out] page_res */ void Tesseract::fix_fuzzy_spaces(ETEXT_DESC *monitor, inT32 word_count, PAGE_RES *page_res) { BLOCK_RES_IT block_res_it; ROW_RES_IT row_res_it; WERD_RES_IT word_res_it_from; WERD_RES_IT word_res_it_to; WERD_RES *word_res; WERD_RES_LIST fuzzy_space_words; inT16 new_length; BOOL8 prevent_null_wd_fixsp; // DONT process blobless wds inT32 word_index; // current word block_res_it.set_to_list(&page_res->block_res_list); word_index = 0; for (block_res_it.mark_cycle_pt(); !block_res_it.cycled_list(); block_res_it.forward()) { row_res_it.set_to_list(&block_res_it.data()->row_res_list); for (row_res_it.mark_cycle_pt(); !row_res_it.cycled_list(); row_res_it.forward()) { word_res_it_from.set_to_list(&row_res_it.data()->word_res_list); while (!word_res_it_from.at_last()) { word_res = word_res_it_from.data(); while (!word_res_it_from.at_last() && !(word_res->combination || word_res_it_from.data_relative(1)->word->flag(W_FUZZY_NON) || word_res_it_from.data_relative(1)->word->flag(W_FUZZY_SP))) { fix_sp_fp_word(word_res_it_from, row_res_it.data()->row, block_res_it.data()->block); word_res = word_res_it_from.forward(); word_index++; if (monitor != NULL) { monitor->ocr_alive = TRUE; monitor->progress = 90 + 5 * word_index / word_count; if (monitor->deadline_exceeded() || (monitor->cancel != NULL && (*monitor->cancel)(monitor->cancel_this, stats_.dict_words))) return; } } if (!word_res_it_from.at_last()) { word_res_it_to = word_res_it_from; prevent_null_wd_fixsp = word_res->word->cblob_list()->empty(); if (check_debug_pt(word_res, 60)) debug_fix_space_level.set_value(10); word_res_it_to.forward(); word_index++; if (monitor != NULL) { monitor->ocr_alive = TRUE; monitor->progress = 90 + 5 * word_index / word_count; if (monitor->deadline_exceeded() || (monitor->cancel != NULL && (*monitor->cancel)(monitor->cancel_this, stats_.dict_words))) return; } while (!word_res_it_to.at_last () && (word_res_it_to.data_relative(1)->word->flag(W_FUZZY_NON) || word_res_it_to.data_relative(1)->word->flag(W_FUZZY_SP))) { if (check_debug_pt(word_res, 60)) debug_fix_space_level.set_value(10); if (word_res->word->cblob_list()->empty()) prevent_null_wd_fixsp = TRUE; word_res = word_res_it_to.forward(); } if (check_debug_pt(word_res, 60)) debug_fix_space_level.set_value(10); if (word_res->word->cblob_list()->empty()) prevent_null_wd_fixsp = TRUE; if (prevent_null_wd_fixsp) { word_res_it_from = word_res_it_to; } else { fuzzy_space_words.assign_to_sublist(&word_res_it_from, &word_res_it_to); fix_fuzzy_space_list(fuzzy_space_words, row_res_it.data()->row, block_res_it.data()->block); new_length = fuzzy_space_words.length(); word_res_it_from.add_list_before(&fuzzy_space_words); for (; !word_res_it_from.at_last() && new_length > 0; new_length--) { word_res_it_from.forward(); } } if (test_pt) debug_fix_space_level.set_value(0); } fix_sp_fp_word(word_res_it_from, row_res_it.data()->row, block_res_it.data()->block); // Last word in row } } } } void Tesseract::fix_fuzzy_space_list(WERD_RES_LIST &best_perm, ROW *row, BLOCK* block) { inT16 best_score; WERD_RES_LIST current_perm; inT16 current_score; BOOL8 improved = FALSE; best_score = eval_word_spacing(best_perm); // default score dump_words(best_perm, best_score, 1, improved); if (best_score != PERFECT_WERDS) initialise_search(best_perm, current_perm); while ((best_score != PERFECT_WERDS) && !current_perm.empty()) { match_current_words(current_perm, row, block); current_score = eval_word_spacing(current_perm); dump_words(current_perm, current_score, 2, improved); if (current_score > best_score) { best_perm.clear(); best_perm.deep_copy(&current_perm, &WERD_RES::deep_copy); best_score = current_score; improved = TRUE; } if (current_score < PERFECT_WERDS) transform_to_next_perm(current_perm); } dump_words(best_perm, best_score, 3, improved); } } // namespace tesseract void initialise_search(WERD_RES_LIST &src_list, WERD_RES_LIST &new_list) { WERD_RES_IT src_it(&src_list); WERD_RES_IT new_it(&new_list); WERD_RES *src_wd; WERD_RES *new_wd; for (src_it.mark_cycle_pt(); !src_it.cycled_list(); src_it.forward()) { src_wd = src_it.data(); if (!src_wd->combination) { new_wd = WERD_RES::deep_copy(src_wd); new_wd->combination = FALSE; new_wd->part_of_combo = FALSE; new_it.add_after_then_move(new_wd); } } } namespace tesseract { void Tesseract::match_current_words(WERD_RES_LIST &words, ROW *row, BLOCK* block) { WERD_RES_IT word_it(&words); WERD_RES *word; // Since we are not using PAGE_RES to iterate over words, we need to update // prev_word_best_choice_ before calling classify_word_pass2(). prev_word_best_choice_ = NULL; for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { word = word_it.data(); if ((!word->part_of_combo) && (word->box_word == NULL)) { WordData word_data(block, row, word); SetupWordPassN(2, &word_data); classify_word_and_language(&Tesseract::classify_word_pass2, NULL, &word_data); } prev_word_best_choice_ = word->best_choice; } } /** * @name eval_word_spacing() * The basic measure is the number of characters in contextually confirmed * words. (I.e the word is done) * If all words are contextually confirmed the evaluation is deemed perfect. * * Some fiddles are done to handle "1"s as these are VERY frequent causes of * fuzzy spaces. The problem with the basic measure is that "561 63" would score * the same as "56163", though given our knowledge that the space is fuzzy, and * that there is a "1" next to the fuzzy space, we need to ensure that "56163" * is prefered. * * The solution is to NOT COUNT the score of any word which has a digit at one * end and a "1Il" as the character the other side of the space. * * Conversly, any character next to a "1" within a word is counted as a positive * score. Thus "561 63" would score 4 (3 chars in a numeric word plus 1 side of * the "1" joined). "56163" would score 7 - all chars in a numeric word + 2 * sides of a "1" joined. * * The joined 1 rule is applied to any word REGARDLESS of contextual * confirmation. Thus "PS7a71 3/7a" scores 1 (neither word is contexutally * confirmed. The only score is from the joined 1. "PS7a713/7a" scores 2. * */ inT16 Tesseract::eval_word_spacing(WERD_RES_LIST &word_res_list) { WERD_RES_IT word_res_it(&word_res_list); inT16 total_score = 0; inT16 word_count = 0; inT16 done_word_count = 0; inT16 word_len; inT16 i; inT16 offset; WERD_RES *word; // current word inT16 prev_word_score = 0; BOOL8 prev_word_done = FALSE; BOOL8 prev_char_1 = FALSE; // prev ch a "1/I/l"? BOOL8 prev_char_digit = FALSE; // prev ch 2..9 or 0 BOOL8 current_char_1 = FALSE; BOOL8 current_word_ok_so_far; STRING punct_chars = "!\"`',.:;"; BOOL8 prev_char_punct = FALSE; BOOL8 current_char_punct = FALSE; BOOL8 word_done = FALSE; do { word = word_res_it.data(); word_done = fixspace_thinks_word_done(word); word_count++; if (word->tess_failed) { total_score += prev_word_score; if (prev_word_done) done_word_count++; prev_word_score = 0; prev_char_1 = FALSE; prev_char_digit = FALSE; prev_word_done = FALSE; } else { /* Can we add the prev word score and potentially count this word? Yes IF it didnt end in a 1 when the first char of this word is a digit AND it didnt end in a digit when the first char of this word is a 1 */ word_len = word->reject_map.length(); current_word_ok_so_far = FALSE; if (!((prev_char_1 && digit_or_numeric_punct(word, 0)) || (prev_char_digit && ( (word_done && word->best_choice->unichar_lengths().string()[0] == 1 && word->best_choice->unichar_string()[0] == '1') || (!word_done && STRING(conflict_set_I_l_1).contains( word->best_choice->unichar_string()[0])))))) { total_score += prev_word_score; if (prev_word_done) done_word_count++; current_word_ok_so_far = word_done; } if (current_word_ok_so_far) { prev_word_done = TRUE; prev_word_score = word_len; } else { prev_word_done = FALSE; prev_word_score = 0; } /* Add 1 to total score for every joined 1 regardless of context and rejtn */ for (i = 0, prev_char_1 = FALSE; i < word_len; i++) { current_char_1 = word->best_choice->unichar_string()[i] == '1'; if (prev_char_1 || (current_char_1 && (i > 0))) total_score++; prev_char_1 = current_char_1; } /* Add 1 to total score for every joined punctuation regardless of context and rejtn */ if (tessedit_prefer_joined_punct) { for (i = 0, offset = 0, prev_char_punct = FALSE; i < word_len; offset += word->best_choice->unichar_lengths()[i++]) { current_char_punct = punct_chars.contains(word->best_choice->unichar_string()[offset]); if (prev_char_punct || (current_char_punct && i > 0)) total_score++; prev_char_punct = current_char_punct; } } prev_char_digit = digit_or_numeric_punct(word, word_len - 1); for (i = 0, offset = 0; i < word_len - 1; offset += word->best_choice->unichar_lengths()[i++]); prev_char_1 = ((word_done && (word->best_choice->unichar_string()[offset] == '1')) || (!word_done && STRING(conflict_set_I_l_1).contains( word->best_choice->unichar_string()[offset]))); } /* Find next word */ do { word_res_it.forward(); } while (word_res_it.data()->part_of_combo); } while (!word_res_it.at_first()); total_score += prev_word_score; if (prev_word_done) done_word_count++; if (done_word_count == word_count) return PERFECT_WERDS; else return total_score; } BOOL8 Tesseract::digit_or_numeric_punct(WERD_RES *word, int char_position) { int i; int offset; for (i = 0, offset = 0; i < char_position; offset += word->best_choice->unichar_lengths()[i++]); return ( word->uch_set->get_isdigit( word->best_choice->unichar_string().string() + offset, word->best_choice->unichar_lengths()[i]) || (word->best_choice->permuter() == NUMBER_PERM && STRING(numeric_punctuation).contains( word->best_choice->unichar_string().string()[offset]))); } } // namespace tesseract /** * @name transform_to_next_perm() * Examines the current word list to find the smallest word gap size. Then walks * the word list closing any gaps of this size by either inserted new * combination words, or extending existing ones. * * The routine COULD be limited to stop it building words longer than N blobs. * * If there are no more gaps then it DELETES the entire list and returns the * empty list to cause termination. */ void transform_to_next_perm(WERD_RES_LIST &words) { WERD_RES_IT word_it(&words); WERD_RES_IT prev_word_it(&words); WERD_RES *word; WERD_RES *prev_word; WERD_RES *combo; WERD *copy_word; inT16 prev_right = -MAX_INT16; TBOX box; inT16 gap; inT16 min_gap = MAX_INT16; for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { word = word_it.data(); if (!word->part_of_combo) { box = word->word->bounding_box(); if (prev_right > -MAX_INT16) { gap = box.left() - prev_right; if (gap < min_gap) min_gap = gap; } prev_right = box.right(); } } if (min_gap < MAX_INT16) { prev_right = -MAX_INT16; // back to start word_it.set_to_list(&words); // Note: we can't use cycle_pt due to inserted combos at start of list. for (; (prev_right == -MAX_INT16) || !word_it.at_first(); word_it.forward()) { word = word_it.data(); if (!word->part_of_combo) { box = word->word->bounding_box(); if (prev_right > -MAX_INT16) { gap = box.left() - prev_right; if (gap <= min_gap) { prev_word = prev_word_it.data(); if (prev_word->combination) { combo = prev_word; } else { /* Make a new combination and insert before * the first word being joined. */ copy_word = new WERD; *copy_word = *(prev_word->word); // deep copy combo = new WERD_RES(copy_word); combo->combination = TRUE; combo->x_height = prev_word->x_height; prev_word->part_of_combo = TRUE; prev_word_it.add_before_then_move(combo); } combo->word->set_flag(W_EOL, word->word->flag(W_EOL)); if (word->combination) { combo->word->join_on(word->word); // Move blobs to combo // old combo no longer needed delete word_it.extract(); } else { // Copy current wd to combo combo->copy_on(word); word->part_of_combo = TRUE; } combo->done = FALSE; combo->ClearResults(); } else { prev_word_it = word_it; // catch up } } prev_right = box.right(); } } } else { words.clear(); // signal termination } } namespace tesseract { void Tesseract::dump_words(WERD_RES_LIST &perm, inT16 score, inT16 mode, BOOL8 improved) { WERD_RES_IT word_res_it(&perm); if (debug_fix_space_level > 0) { if (mode == 1) { stats_.dump_words_str = ""; for (word_res_it.mark_cycle_pt(); !word_res_it.cycled_list(); word_res_it.forward()) { if (!word_res_it.data()->part_of_combo) { stats_.dump_words_str += word_res_it.data()->best_choice->unichar_string(); stats_.dump_words_str += ' '; } } } if (debug_fix_space_level > 1) { switch (mode) { case 1: tprintf("EXTRACTED (%d): \"", score); break; case 2: tprintf("TESTED (%d): \"", score); break; case 3: tprintf("RETURNED (%d): \"", score); break; } for (word_res_it.mark_cycle_pt(); !word_res_it.cycled_list(); word_res_it.forward()) { if (!word_res_it.data()->part_of_combo) { tprintf("%s/%1d ", word_res_it.data()->best_choice->unichar_string().string(), (int)word_res_it.data()->best_choice->permuter()); } } tprintf("\"\n"); } else if (improved) { tprintf("FIX SPACING \"%s\" => \"", stats_.dump_words_str.string()); for (word_res_it.mark_cycle_pt(); !word_res_it.cycled_list(); word_res_it.forward()) { if (!word_res_it.data()->part_of_combo) { tprintf("%s/%1d ", word_res_it.data()->best_choice->unichar_string().string(), (int)word_res_it.data()->best_choice->permuter()); } } tprintf("\"\n"); } } } BOOL8 Tesseract::fixspace_thinks_word_done(WERD_RES *word) { if (word->done) return TRUE; /* Use all the standard pass 2 conditions for mode 5 in set_done() in reject.c BUT DONT REJECT IF THE WERD IS AMBIGUOUS - FOR SPACING WE DONT CARE WHETHER WE HAVE of/at on/an etc. */ if (fixsp_done_mode > 0 && (word->tess_accepted || (fixsp_done_mode == 2 && word->reject_map.reject_count() == 0) || fixsp_done_mode == 3) && (strchr(word->best_choice->unichar_string().string(), ' ') == NULL) && ((word->best_choice->permuter() == SYSTEM_DAWG_PERM) || (word->best_choice->permuter() == FREQ_DAWG_PERM) || (word->best_choice->permuter() == USER_DAWG_PERM) || (word->best_choice->permuter() == NUMBER_PERM))) { return TRUE; } else { return FALSE; } } /** * @name fix_sp_fp_word() * Test the current word to see if it can be split by deleting noise blobs. If * so, do the business. * Return with the iterator pointing to the same place if the word is unchanged, * or the last of the replacement words. */ void Tesseract::fix_sp_fp_word(WERD_RES_IT &word_res_it, ROW *row, BLOCK* block) { WERD_RES *word_res; WERD_RES_LIST sub_word_list; WERD_RES_IT sub_word_list_it(&sub_word_list); inT16 blob_index; inT16 new_length; float junk; word_res = word_res_it.data(); if (word_res->word->flag(W_REP_CHAR) || word_res->combination || word_res->part_of_combo || !word_res->word->flag(W_DONT_CHOP)) return; blob_index = worst_noise_blob(word_res, &junk); if (blob_index < 0) return; if (debug_fix_space_level > 1) { tprintf("FP fixspace working on \"%s\"\n", word_res->best_choice->unichar_string().string()); } word_res->word->rej_cblob_list()->sort(c_blob_comparator); sub_word_list_it.add_after_stay_put(word_res_it.extract()); fix_noisy_space_list(sub_word_list, row, block); new_length = sub_word_list.length(); word_res_it.add_list_before(&sub_word_list); for (; !word_res_it.at_last() && new_length > 1; new_length--) { word_res_it.forward(); } } void Tesseract::fix_noisy_space_list(WERD_RES_LIST &best_perm, ROW *row, BLOCK* block) { inT16 best_score; WERD_RES_IT best_perm_it(&best_perm); WERD_RES_LIST current_perm; WERD_RES_IT current_perm_it(&current_perm); WERD_RES *old_word_res; inT16 current_score; BOOL8 improved = FALSE; best_score = fp_eval_word_spacing(best_perm); // default score dump_words(best_perm, best_score, 1, improved); old_word_res = best_perm_it.data(); // Even deep_copy doesn't copy the underlying WERD unless its combination // flag is true!. old_word_res->combination = TRUE; // Kludge to force deep copy current_perm_it.add_to_end(WERD_RES::deep_copy(old_word_res)); old_word_res->combination = FALSE; // Undo kludge break_noisiest_blob_word(current_perm); while (best_score != PERFECT_WERDS && !current_perm.empty()) { match_current_words(current_perm, row, block); current_score = fp_eval_word_spacing(current_perm); dump_words(current_perm, current_score, 2, improved); if (current_score > best_score) { best_perm.clear(); best_perm.deep_copy(&current_perm, &WERD_RES::deep_copy); best_score = current_score; improved = TRUE; } if (current_score < PERFECT_WERDS) { break_noisiest_blob_word(current_perm); } } dump_words(best_perm, best_score, 3, improved); } /** * break_noisiest_blob_word() * Find the word with the blob which looks like the worst noise. * Break the word into two, deleting the noise blob. */ void Tesseract::break_noisiest_blob_word(WERD_RES_LIST &words) { WERD_RES_IT word_it(&words); WERD_RES_IT worst_word_it; float worst_noise_score = 9999; int worst_blob_index = -1; // Noisiest blob of noisiest wd int blob_index; // of wds noisiest blob float noise_score; // of wds noisiest blob WERD_RES *word_res; C_BLOB_IT blob_it; C_BLOB_IT rej_cblob_it; C_BLOB_LIST new_blob_list; C_BLOB_IT new_blob_it; C_BLOB_IT new_rej_cblob_it; WERD *new_word; inT16 start_of_noise_blob; inT16 i; for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { blob_index = worst_noise_blob(word_it.data(), &noise_score); if (blob_index > -1 && worst_noise_score > noise_score) { worst_noise_score = noise_score; worst_blob_index = blob_index; worst_word_it = word_it; } } if (worst_blob_index < 0) { words.clear(); // signal termination return; } /* Now split the worst_word_it */ word_res = worst_word_it.data(); /* Move blobs before noise blob to a new bloblist */ new_blob_it.set_to_list(&new_blob_list); blob_it.set_to_list(word_res->word->cblob_list()); for (i = 0; i < worst_blob_index; i++, blob_it.forward()) { new_blob_it.add_after_then_move(blob_it.extract()); } start_of_noise_blob = blob_it.data()->bounding_box().left(); delete blob_it.extract(); // throw out noise blob new_word = new WERD(&new_blob_list, word_res->word); new_word->set_flag(W_EOL, FALSE); word_res->word->set_flag(W_BOL, FALSE); word_res->word->set_blanks(1); // After break new_rej_cblob_it.set_to_list(new_word->rej_cblob_list()); rej_cblob_it.set_to_list(word_res->word->rej_cblob_list()); for (; (!rej_cblob_it.empty() && (rej_cblob_it.data()->bounding_box().left() < start_of_noise_blob)); rej_cblob_it.forward()) { new_rej_cblob_it.add_after_then_move(rej_cblob_it.extract()); } WERD_RES* new_word_res = new WERD_RES(new_word); new_word_res->combination = TRUE; worst_word_it.add_before_then_move(new_word_res); word_res->ClearResults(); } inT16 Tesseract::worst_noise_blob(WERD_RES *word_res, float *worst_noise_score) { float noise_score[512]; int i; int min_noise_blob; // 1st contender int max_noise_blob; // last contender int non_noise_count; int worst_noise_blob; // Worst blob float small_limit = kBlnXHeight * fixsp_small_outlines_size; float non_noise_limit = kBlnXHeight * 0.8; if (word_res->rebuild_word == NULL) return -1; // Can't handle cube words. // Normalised. int blob_count = word_res->box_word->length(); ASSERT_HOST(blob_count <= 512); if (blob_count < 5) return -1; // too short to split /* Get the noise scores for all blobs */ #ifndef SECURE_NAMES if (debug_fix_space_level > 5) tprintf("FP fixspace Noise metrics for \"%s\": ", word_res->best_choice->unichar_string().string()); #endif for (i = 0; i < blob_count && i < word_res->rebuild_word->NumBlobs(); i++) { TBLOB* blob = word_res->rebuild_word->blobs[i]; if (word_res->reject_map[i].accepted()) noise_score[i] = non_noise_limit; else noise_score[i] = blob_noise_score(blob); if (debug_fix_space_level > 5) tprintf("%1.1f ", noise_score[i]); } if (debug_fix_space_level > 5) tprintf("\n"); /* Now find the worst one which is far enough away from the end of the word */ non_noise_count = 0; for (i = 0; i < blob_count && non_noise_count < fixsp_non_noise_limit; i++) { if (noise_score[i] >= non_noise_limit) { non_noise_count++; } } if (non_noise_count < fixsp_non_noise_limit) return -1; min_noise_blob = i; non_noise_count = 0; for (i = blob_count - 1; i >= 0 && non_noise_count < fixsp_non_noise_limit; i--) { if (noise_score[i] >= non_noise_limit) { non_noise_count++; } } if (non_noise_count < fixsp_non_noise_limit) return -1; max_noise_blob = i; if (min_noise_blob > max_noise_blob) return -1; *worst_noise_score = small_limit; worst_noise_blob = -1; for (i = min_noise_blob; i <= max_noise_blob; i++) { if (noise_score[i] < *worst_noise_score) { worst_noise_blob = i; *worst_noise_score = noise_score[i]; } } return worst_noise_blob; } float Tesseract::blob_noise_score(TBLOB *blob) { TBOX box; // BB of outline inT16 outline_count = 0; inT16 max_dimension; inT16 largest_outline_dimension = 0; for (TESSLINE* ol = blob->outlines; ol != NULL; ol= ol->next) { outline_count++; box = ol->bounding_box(); if (box.height() > box.width()) { max_dimension = box.height(); } else { max_dimension = box.width(); } if (largest_outline_dimension < max_dimension) largest_outline_dimension = max_dimension; } if (outline_count > 5) { // penalise LOTS of blobs largest_outline_dimension *= 2; } box = blob->bounding_box(); if (box.bottom() > kBlnBaselineOffset * 4 || box.top() < kBlnBaselineOffset / 2) { // Lax blob is if high or low largest_outline_dimension /= 2; } return largest_outline_dimension; } } // namespace tesseract void fixspace_dbg(WERD_RES *word) { TBOX box = word->word->bounding_box(); BOOL8 show_map_detail = FALSE; inT16 i; box.print(); tprintf(" \"%s\" ", word->best_choice->unichar_string().string()); tprintf("Blob count: %d (word); %d/%d (rebuild word)\n", word->word->cblob_list()->length(), word->rebuild_word->NumBlobs(), word->box_word->length()); word->reject_map.print(debug_fp); tprintf("\n"); if (show_map_detail) { tprintf("\"%s\"\n", word->best_choice->unichar_string().string()); for (i = 0; word->best_choice->unichar_string()[i] != '\0'; i++) { tprintf("**** \"%c\" ****\n", word->best_choice->unichar_string()[i]); word->reject_map[i].full_print(debug_fp); } } tprintf("Tess Accepted: %s\n", word->tess_accepted ? "TRUE" : "FALSE"); tprintf("Done flag: %s\n\n", word->done ? "TRUE" : "FALSE"); } /** * fp_eval_word_spacing() * Evaluation function for fixed pitch word lists. * * Basically, count the number of "nice" characters - those which are in tess * acceptable words or in dict words and are not rejected. * Penalise any potential noise chars */ namespace tesseract { inT16 Tesseract::fp_eval_word_spacing(WERD_RES_LIST &word_res_list) { WERD_RES_IT word_it(&word_res_list); WERD_RES *word; inT16 word_length; inT16 score = 0; inT16 i; float small_limit = kBlnXHeight * fixsp_small_outlines_size; for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { word = word_it.data(); if (word->rebuild_word == NULL) continue; // Can't handle cube words. word_length = word->reject_map.length(); if (word->done || word->tess_accepted || word->best_choice->permuter() == SYSTEM_DAWG_PERM || word->best_choice->permuter() == FREQ_DAWG_PERM || word->best_choice->permuter() == USER_DAWG_PERM || safe_dict_word(word) > 0) { int num_blobs = word->rebuild_word->NumBlobs(); UNICHAR_ID space = word->uch_set->unichar_to_id(" "); for (i = 0; i < word->best_choice->length() && i < num_blobs; ++i) { TBLOB* blob = word->rebuild_word->blobs[i]; if (word->best_choice->unichar_id(i) == space || blob_noise_score(blob) < small_limit) { score -= 1; // penalise possibly erroneous non-space } else if (word->reject_map[i].accepted()) { score++; } } } } if (score < 0) score = 0; return score; } } // namespace tesseract
1080228-arabicocr11
ccmain/fixspace.cpp
C++
asf20
29,721
/////////////////////////////////////////////////////////////////////// // File: equationdetect.cpp // Description: Helper classes to detect equations. // Author: Zongyi (Joe) Liu (joeliu@google.com) // Created: Fri Aug 31 11:13:01 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. // /////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #include <mathfix.h> #endif #ifdef __MINGW32__ #include <limits.h> #endif #include <float.h> // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "equationdetect.h" #include "bbgrid.h" #include "classify.h" #include "colpartition.h" #include "colpartitiongrid.h" #include "colpartitionset.h" #include "helpers.h" #include "ratngs.h" #include "tesseractclass.h" // Config variables. BOOL_VAR(equationdetect_save_bi_image, false, "Save input bi image"); BOOL_VAR(equationdetect_save_spt_image, false, "Save special character image"); BOOL_VAR(equationdetect_save_seed_image, false, "Save the seed image"); BOOL_VAR(equationdetect_save_merged_image, false, "Save the merged image"); namespace tesseract { /////////////////////////////////////////////////////////////////////////// // Utility ColParition sort functions. /////////////////////////////////////////////////////////////////////////// static int SortCPByTopReverse(const void* p1, const void* p2) { const ColPartition* cp1 = *reinterpret_cast<ColPartition* const*>(p1); const ColPartition* cp2 = *reinterpret_cast<ColPartition* const*>(p2); ASSERT_HOST(cp1 != NULL && cp2 != NULL); const TBOX &box1(cp1->bounding_box()), &box2(cp2->bounding_box()); return box2.top() - box1.top(); } static int SortCPByBottom(const void* p1, const void* p2) { const ColPartition* cp1 = *reinterpret_cast<ColPartition* const*>(p1); const ColPartition* cp2 = *reinterpret_cast<ColPartition* const*>(p2); ASSERT_HOST(cp1 != NULL && cp2 != NULL); const TBOX &box1(cp1->bounding_box()), &box2(cp2->bounding_box()); return box1.bottom() - box2.bottom(); } static int SortCPByHeight(const void* p1, const void* p2) { const ColPartition* cp1 = *reinterpret_cast<ColPartition* const*>(p1); const ColPartition* cp2 = *reinterpret_cast<ColPartition* const*>(p2); ASSERT_HOST(cp1 != NULL && cp2 != NULL); const TBOX &box1(cp1->bounding_box()), &box2(cp2->bounding_box()); return box1.height() - box2.height(); } // TODO(joeliu): we may want to parameterize these constants. const float kMathDigitDensityTh1 = 0.25; const float kMathDigitDensityTh2 = 0.1; const float kMathItalicDensityTh = 0.5; const float kUnclearDensityTh = 0.25; const int kSeedBlobsCountTh = 10; const int kLeftIndentAlignmentCountTh = 1; // Returns true if PolyBlockType is of text type or equation type. inline bool IsTextOrEquationType(PolyBlockType type) { return PTIsTextType(type) || type == PT_EQUATION; } inline bool IsLeftIndented(const EquationDetect::IndentType type) { return type == EquationDetect::LEFT_INDENT || type == EquationDetect::BOTH_INDENT; } inline bool IsRightIndented(const EquationDetect::IndentType type) { return type == EquationDetect::RIGHT_INDENT || type == EquationDetect::BOTH_INDENT; } EquationDetect::EquationDetect(const char* equ_datapath, const char* equ_name) { const char* default_name = "equ"; if (equ_name == NULL) { equ_name = default_name; } equ_tesseract_ = lang_tesseract_ = NULL; resolution_ = 0; page_count_ = 0; // Construct equ_tesseract_. equ_tesseract_ = new Tesseract(); if (equ_tesseract_->init_tesseract(equ_datapath, equ_name, OEM_TESSERACT_ONLY)) { tprintf("Warning: equation region detection requested," " but %s failed to load from %s\n", equ_name, equ_datapath); delete equ_tesseract_; equ_tesseract_ = NULL; } cps_super_bbox_ = NULL; } EquationDetect::~EquationDetect() { if (equ_tesseract_) { delete (equ_tesseract_); } if (cps_super_bbox_) { delete(cps_super_bbox_); } } void EquationDetect::SetLangTesseract(Tesseract* lang_tesseract) { lang_tesseract_ = lang_tesseract; } void EquationDetect::SetResolution(const int resolution) { resolution_ = resolution; } int EquationDetect::LabelSpecialText(TO_BLOCK* to_block) { if (to_block == NULL) { tprintf("Warning: input to_block is NULL!\n"); return -1; } GenericVector<BLOBNBOX_LIST*> blob_lists; blob_lists.push_back(&(to_block->blobs)); blob_lists.push_back(&(to_block->large_blobs)); for (int i = 0; i < blob_lists.size(); ++i) { BLOBNBOX_IT bbox_it(blob_lists[i]); for (bbox_it.mark_cycle_pt (); !bbox_it.cycled_list(); bbox_it.forward()) { bbox_it.data()->set_special_text_type(BSTT_NONE); } } return 0; } void EquationDetect::IdentifySpecialText( BLOBNBOX *blobnbox, const int height_th) { ASSERT_HOST(blobnbox != NULL); if (blobnbox->bounding_box().height() < height_th && height_th > 0) { // For small blob, we simply set to BSTT_NONE. blobnbox->set_special_text_type(BSTT_NONE); return; } BLOB_CHOICE_LIST ratings_equ, ratings_lang; C_BLOB* blob = blobnbox->cblob(); // TODO(joeliu/rays) Fix this. We may have to normalize separately for // each classifier here, as they may require different PolygonalCopy. TBLOB* tblob = TBLOB::PolygonalCopy(false, blob); const TBOX& box = tblob->bounding_box(); // Normalize the blob. Set the origin to the place we want to be the // bottom-middle, and scaling is to make the height the x-height. float scaling = static_cast<float>(kBlnXHeight) / box.height(); float x_orig = (box.left() + box.right()) / 2.0f, y_orig = box.bottom(); TBLOB* normed_blob = new TBLOB(*tblob); normed_blob->Normalize(NULL, NULL, NULL, x_orig, y_orig, scaling, scaling, 0.0f, static_cast<float>(kBlnBaselineOffset), false, NULL); equ_tesseract_->AdaptiveClassifier(normed_blob, &ratings_equ); lang_tesseract_->AdaptiveClassifier(normed_blob, &ratings_lang); delete normed_blob; delete tblob; // Get the best choice from ratings_lang and rating_equ. As the choice in the // list has already been sorted by the certainty, we simply use the first // choice. BLOB_CHOICE *lang_choice = NULL, *equ_choice = NULL; if (ratings_lang.length() > 0) { BLOB_CHOICE_IT choice_it(&ratings_lang); lang_choice = choice_it.data(); } if (ratings_equ.length() > 0) { BLOB_CHOICE_IT choice_it(&ratings_equ); equ_choice = choice_it.data(); } float lang_score = lang_choice ? lang_choice->certainty() : -FLT_MAX; float equ_score = equ_choice ? equ_choice->certainty() : -FLT_MAX; const float kConfScoreTh = -5.0f, kConfDiffTh = 1.8; // The scores here are negative, so the max/min == fabs(min/max). // float ratio = fmax(lang_score, equ_score) / fmin(lang_score, equ_score); float diff = fabs(lang_score - equ_score); BlobSpecialTextType type = BSTT_NONE; // Classification. if (fmax(lang_score, equ_score) < kConfScoreTh) { // If both score are very small, then mark it as unclear. type = BSTT_UNCLEAR; } else if (diff > kConfDiffTh && equ_score > lang_score) { // If equ_score is significantly higher, then we classify this character as // math symbol. type = BSTT_MATH; } else if (lang_choice) { // For other cases: lang_score is similar or significantly higher. type = EstimateTypeForUnichar( lang_tesseract_->unicharset, lang_choice->unichar_id()); } if (type == BSTT_NONE && lang_tesseract_->get_fontinfo_table().get( lang_choice->fontinfo_id()).is_italic()) { // For text symbol, we still check if it is italic. blobnbox->set_special_text_type(BSTT_ITALIC); } else { blobnbox->set_special_text_type(type); } } BlobSpecialTextType EquationDetect::EstimateTypeForUnichar( const UNICHARSET& unicharset, const UNICHAR_ID id) const { STRING s = unicharset.id_to_unichar(id); if (unicharset.get_isalpha(id)) { return BSTT_NONE; } if (unicharset.get_ispunctuation(id)) { // Exclude some special texts that are likely to be confused as math symbol. static GenericVector<UNICHAR_ID> ids_to_exclude; if (ids_to_exclude.empty()) { static const STRING kCharsToEx[] = {"'", "`", "\"", "\\", ",", ".", "〈", "〉", "《", "》", "」", "「", ""}; int i = 0; while (kCharsToEx[i] != "") { ids_to_exclude.push_back( unicharset.unichar_to_id(kCharsToEx[i++].string())); } ids_to_exclude.sort(); } return ids_to_exclude.bool_binary_search(id) ? BSTT_NONE : BSTT_MATH; } // Check if it is digit. In addition to the isdigit attribute, we also check // if this character belongs to those likely to be confused with a digit. static const STRING kDigitsChars = "|"; if (unicharset.get_isdigit(id) || (s.length() == 1 && kDigitsChars.contains(s[0]))) { return BSTT_DIGIT; } else { return BSTT_MATH; } } void EquationDetect::IdentifySpecialText() { // Set configuration for Tesseract::AdaptiveClassifier. equ_tesseract_->tess_cn_matching.set_value(true); // turn it on equ_tesseract_->tess_bn_matching.set_value(false); // Set the multiplier to zero for lang_tesseract_ to improve the accuracy. int classify_class_pruner = lang_tesseract_->classify_class_pruner_multiplier; int classify_integer_matcher = lang_tesseract_->classify_integer_matcher_multiplier; lang_tesseract_->classify_class_pruner_multiplier.set_value(0); lang_tesseract_->classify_integer_matcher_multiplier.set_value(0); ColPartitionGridSearch gsearch(part_grid_); ColPartition *part = NULL; gsearch.StartFullSearch(); while ((part = gsearch.NextFullSearch()) != NULL) { if (!IsTextOrEquationType(part->type())) { continue; } IdentifyBlobsToSkip(part); BLOBNBOX_C_IT bbox_it(part->boxes()); // Compute the height threshold. GenericVector<int> blob_heights; for (bbox_it.mark_cycle_pt (); !bbox_it.cycled_list(); bbox_it.forward()) { if (bbox_it.data()->special_text_type() != BSTT_SKIP) { blob_heights.push_back(bbox_it.data()->bounding_box().height()); } } blob_heights.sort(); int height_th = blob_heights[blob_heights.size() / 2] / 3 * 2; for (bbox_it.mark_cycle_pt (); !bbox_it.cycled_list(); bbox_it.forward()) { if (bbox_it.data()->special_text_type() != BSTT_SKIP) { IdentifySpecialText(bbox_it.data(), height_th); } } } // Set the multiplier values back. lang_tesseract_->classify_class_pruner_multiplier.set_value( classify_class_pruner); lang_tesseract_->classify_integer_matcher_multiplier.set_value( classify_integer_matcher); if (equationdetect_save_spt_image) { // For debug. STRING outfile; GetOutputTiffName("_spt", &outfile); PaintSpecialTexts(outfile); } } void EquationDetect::IdentifyBlobsToSkip(ColPartition* part) { ASSERT_HOST(part); BLOBNBOX_C_IT blob_it(part->boxes()); for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { // At this moment, no blob should have been joined. ASSERT_HOST(!blob_it.data()->joined_to_prev()); } for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { BLOBNBOX* blob = blob_it.data(); if (blob->joined_to_prev() || blob->special_text_type() == BSTT_SKIP) { continue; } TBOX blob_box = blob->bounding_box(); // Search if any blob can be merged into blob. If found, then we mark all // these blobs as BSTT_SKIP. BLOBNBOX_C_IT blob_it2 = blob_it; bool found = false; while (!blob_it2.at_last()) { BLOBNBOX* nextblob = blob_it2.forward(); const TBOX& nextblob_box = nextblob->bounding_box(); if (nextblob_box.left() >= blob_box.right()) { break; } const float kWidthR = 0.4, kHeightR = 0.3; bool xoverlap = blob_box.major_x_overlap(nextblob_box), yoverlap = blob_box.y_overlap(nextblob_box); float widthR = static_cast<float>( MIN(nextblob_box.width(), blob_box.width())) / MAX(nextblob_box.width(), blob_box.width()); float heightR = static_cast<float>( MIN(nextblob_box.height(), blob_box.height())) / MAX(nextblob_box.height(), blob_box.height()); if (xoverlap && yoverlap && widthR > kWidthR && heightR > kHeightR) { // Found one, set nextblob type and recompute blob_box. found = true; nextblob->set_special_text_type(BSTT_SKIP); blob_box += nextblob_box; } } if (found) { blob->set_special_text_type(BSTT_SKIP); } } } int EquationDetect::FindEquationParts( ColPartitionGrid* part_grid, ColPartitionSet** best_columns) { if (!equ_tesseract_ || !lang_tesseract_) { tprintf("Warning: equ_tesseract_/lang_tesseract_ is NULL!\n"); return -1; } if (!part_grid || !best_columns) { tprintf("part_grid/best_columns is NULL!!\n"); return -1; } cp_seeds_.clear(); part_grid_ = part_grid; best_columns_ = best_columns; resolution_ = lang_tesseract_->source_resolution(); STRING outfile; page_count_++; if (equationdetect_save_bi_image) { GetOutputTiffName("_bi", &outfile); pixWrite(outfile.string(), lang_tesseract_->pix_binary(), IFF_TIFF_G4); } // Pass 0: Compute special text type for blobs. IdentifySpecialText(); // Pass 1: Merge parts by overlap. MergePartsByLocation(); // Pass 2: compute the math blob density and find the seed partition. IdentifySeedParts(); // We still need separate seed into block seed and inline seed partition. IdentifyInlineParts(); if (equationdetect_save_seed_image) { GetOutputTiffName("_seed", &outfile); PaintColParts(outfile); } // Pass 3: expand block equation seeds. while (!cp_seeds_.empty()) { GenericVector<ColPartition*> seeds_expanded; for (int i = 0; i < cp_seeds_.size(); ++i) { if (ExpandSeed(cp_seeds_[i])) { // If this seed is expanded, then we add it into seeds_expanded. Note // this seed has been removed from part_grid_ if it is expanded. seeds_expanded.push_back(cp_seeds_[i]); } } // Add seeds_expanded back into part_grid_ and reset cp_seeds_. for (int i = 0; i < seeds_expanded.size(); ++i) { InsertPartAfterAbsorb(seeds_expanded[i]); } cp_seeds_ = seeds_expanded; } // Pass 4: find math block satellite text partitions and merge them. ProcessMathBlockSatelliteParts(); if (equationdetect_save_merged_image) { // For debug. GetOutputTiffName("_merged", &outfile); PaintColParts(outfile); } return 0; } void EquationDetect::MergePartsByLocation() { while (true) { ColPartition* part = NULL; // partitions that have been updated. GenericVector<ColPartition*> parts_updated; ColPartitionGridSearch gsearch(part_grid_); gsearch.StartFullSearch(); while ((part = gsearch.NextFullSearch()) != NULL) { if (!IsTextOrEquationType(part->type())) { continue; } GenericVector<ColPartition*> parts_to_merge; SearchByOverlap(part, &parts_to_merge); if (parts_to_merge.empty()) { continue; } // Merge parts_to_merge with part, and remove them from part_grid_. part_grid_->RemoveBBox(part); for (int i = 0; i < parts_to_merge.size(); ++i) { ASSERT_HOST(parts_to_merge[i] != NULL && parts_to_merge[i] != part); part->Absorb(parts_to_merge[i], NULL); } gsearch.RepositionIterator(); parts_updated.push_back(part); } if (parts_updated.empty()) { // Exit the loop break; } // Re-insert parts_updated into part_grid_. for (int i = 0; i < parts_updated.size(); ++i) { InsertPartAfterAbsorb(parts_updated[i]); } } } void EquationDetect::SearchByOverlap( ColPartition* seed, GenericVector<ColPartition*>* parts_overlap) { ASSERT_HOST(seed != NULL && parts_overlap != NULL); if (!IsTextOrEquationType(seed->type())) { return; } ColPartitionGridSearch search(part_grid_); const TBOX& seed_box(seed->bounding_box()); const int kRadNeighborCells = 30; search.StartRadSearch((seed_box.left() + seed_box.right()) / 2, (seed_box.top() + seed_box.bottom()) / 2, kRadNeighborCells); search.SetUniqueMode(true); // Search iteratively. ColPartition *part; GenericVector<ColPartition*> parts; const float kLargeOverlapTh = 0.95; const float kEquXOverlap = 0.4, kEquYOverlap = 0.5; while ((part = search.NextRadSearch()) != NULL) { if (part == seed || !IsTextOrEquationType(part->type())) { continue; } const TBOX& part_box(part->bounding_box()); bool merge = false; float x_overlap_fraction = part_box.x_overlap_fraction(seed_box), y_overlap_fraction = part_box.y_overlap_fraction(seed_box); // If part is large overlapped with seed, then set merge to true. if (x_overlap_fraction >= kLargeOverlapTh && y_overlap_fraction >= kLargeOverlapTh) { merge = true; } else if (seed->type() == PT_EQUATION && IsTextOrEquationType(part->type())) { if ((x_overlap_fraction > kEquXOverlap && y_overlap_fraction > 0.0) || (x_overlap_fraction > 0.0 && y_overlap_fraction > kEquYOverlap)) { merge = true; } } if (merge) { // Remove the part from search and put it into parts. search.RemoveBBox(); parts_overlap->push_back(part); } } } void EquationDetect::InsertPartAfterAbsorb(ColPartition* part) { ASSERT_HOST(part); // Before insert part back into part_grid_, we will need re-compute some // of its attributes such as first_column_, last_column_. However, we still // want to preserve its type. BlobTextFlowType flow_type = part->flow(); PolyBlockType part_type = part->type(); BlobRegionType blob_type = part->blob_type(); // Call SetPartitionType to re-compute the attributes of part. const TBOX& part_box(part->bounding_box()); int grid_x, grid_y; part_grid_->GridCoords( part_box.left(), part_box.bottom(), &grid_x, &grid_y); part->SetPartitionType(resolution_, best_columns_[grid_y]); // Reset the types back. part->set_type(part_type); part->set_blob_type(blob_type); part->set_flow(flow_type); part->SetBlobTypes(); // Insert into part_grid_. part_grid_->InsertBBox(true, true, part); } void EquationDetect::IdentifySeedParts() { ColPartitionGridSearch gsearch(part_grid_); ColPartition *part = NULL; gsearch.StartFullSearch(); GenericVector<ColPartition*> seeds1, seeds2; // The left coordinates of indented text partitions. GenericVector<int> indented_texts_left; // The foreground density of text partitions. GenericVector<float> texts_foreground_density; while ((part = gsearch.NextFullSearch()) != NULL) { if (!IsTextOrEquationType(part->type())) { continue; } part->ComputeSpecialBlobsDensity(); bool blobs_check = CheckSeedBlobsCount(part); const int kTextBlobsTh = 20; if (CheckSeedDensity(kMathDigitDensityTh1, kMathDigitDensityTh2, part) && blobs_check) { // Passed high density threshold test, save into seeds1. seeds1.push_back(part); } else { IndentType indent = IsIndented(part); if (IsLeftIndented(indent) && blobs_check && CheckSeedDensity(kMathDigitDensityTh2, kMathDigitDensityTh2, part)) { // Passed low density threshold test and is indented, save into seeds2. seeds2.push_back(part); } else if (!IsRightIndented(indent) && part->boxes_count() > kTextBlobsTh) { // This is likely to be a text part, save the features. const TBOX&box = part->bounding_box(); if (IsLeftIndented(indent)) { indented_texts_left.push_back(box.left()); } texts_foreground_density.push_back(ComputeForegroundDensity(box)); } } } // Sort the features collected from text regions. indented_texts_left.sort(); texts_foreground_density.sort(); float foreground_density_th = 0.15; // Default value. if (!texts_foreground_density.empty()) { // Use the median of the texts_foreground_density. foreground_density_th = 0.8 * texts_foreground_density[ texts_foreground_density.size() / 2]; } for (int i = 0; i < seeds1.size(); ++i) { const TBOX& box = seeds1[i]->bounding_box(); if (CheckSeedFgDensity(foreground_density_th, seeds1[i]) && !(IsLeftIndented(IsIndented(seeds1[i])) && CountAlignment(indented_texts_left, box.left()) >= kLeftIndentAlignmentCountTh)) { // Mark as PT_EQUATION type. seeds1[i]->set_type(PT_EQUATION); cp_seeds_.push_back(seeds1[i]); } else { // Mark as PT_INLINE_EQUATION type. seeds1[i]->set_type(PT_INLINE_EQUATION); } } for (int i = 0; i < seeds2.size(); ++i) { if (CheckForSeed2(indented_texts_left, foreground_density_th, seeds2[i])) { seeds2[i]->set_type(PT_EQUATION); cp_seeds_.push_back(seeds2[i]); } } } float EquationDetect::ComputeForegroundDensity(const TBOX& tbox) { #if LIBLEPT_MINOR_VERSION < 69 && LIBLEPT_MAJOR_VERSION <= 1 // This will disable the detector because no seed will be identified. return 1.0f; #else Pix *pix_bi = lang_tesseract_->pix_binary(); int pix_height = pixGetHeight(pix_bi); Box* box = boxCreate(tbox.left(), pix_height - tbox.top(), tbox.width(), tbox.height()); Pix *pix_sub = pixClipRectangle(pix_bi, box, NULL); l_float32 fract; pixForegroundFraction(pix_sub, &fract); pixDestroy(&pix_sub); boxDestroy(&box); return fract; #endif } bool EquationDetect::CheckSeedFgDensity(const float density_th, ColPartition* part) { ASSERT_HOST(part); // Split part horizontall, and check for each sub part. GenericVector<TBOX> sub_boxes; SplitCPHorLite(part, &sub_boxes); float parts_passed = 0.0; for (int i = 0; i < sub_boxes.size(); ++i) { float density = ComputeForegroundDensity(sub_boxes[i]); if (density < density_th) { parts_passed++; } } // If most sub parts passed, then we return true. const float kSeedPartRatioTh = 0.3; bool retval = (parts_passed / sub_boxes.size() >= kSeedPartRatioTh); return retval; } void EquationDetect::SplitCPHor(ColPartition* part, GenericVector<ColPartition*>* parts_splitted) { ASSERT_HOST(part && parts_splitted); if (part->median_width() == 0 || part->boxes_count() == 0) { return; } // Make a copy of part, and reset parts_splitted. ColPartition* right_part = part->CopyButDontOwnBlobs(); parts_splitted->delete_data_pointers(); parts_splitted->clear(); const double kThreshold = part->median_width() * 3.0; bool found_split = true; while (found_split) { found_split = false; BLOBNBOX_C_IT box_it(right_part->boxes()); // Blobs are sorted left side first. If blobs overlap, // the previous blob may have a "more right" right side. // Account for this by always keeping the largest "right" // so far. int previous_right = MIN_INT32; // Look for the next split in the partition. for (box_it.mark_cycle_pt(); !box_it.cycled_list(); box_it.forward()) { const TBOX& box = box_it.data()->bounding_box(); if (previous_right != MIN_INT32 && box.left() - previous_right > kThreshold) { // We have a split position. Split the partition in two pieces. // Insert the left piece in the grid and keep processing the right. int mid_x = (box.left() + previous_right) / 2; ColPartition* left_part = right_part; right_part = left_part->SplitAt(mid_x); parts_splitted->push_back(left_part); left_part->ComputeSpecialBlobsDensity(); found_split = true; break; } // The right side of the previous blobs. previous_right = MAX(previous_right, box.right()); } } // Add the last piece. right_part->ComputeSpecialBlobsDensity(); parts_splitted->push_back(right_part); } void EquationDetect::SplitCPHorLite(ColPartition* part, GenericVector<TBOX>* splitted_boxes) { ASSERT_HOST(part && splitted_boxes); splitted_boxes->clear(); if (part->median_width() == 0) { return; } const double kThreshold = part->median_width() * 3.0; // Blobs are sorted left side first. If blobs overlap, // the previous blob may have a "more right" right side. // Account for this by always keeping the largest "right" // so far. TBOX union_box; int previous_right = MIN_INT32; BLOBNBOX_C_IT box_it(part->boxes()); for (box_it.mark_cycle_pt(); !box_it.cycled_list(); box_it.forward()) { const TBOX& box = box_it.data()->bounding_box(); if (previous_right != MIN_INT32 && box.left() - previous_right > kThreshold) { // We have a split position. splitted_boxes->push_back(union_box); previous_right = MIN_INT32; } if (previous_right == MIN_INT32) { union_box = box; } else { union_box += box; } // The right side of the previous blobs. previous_right = MAX(previous_right, box.right()); } // Add the last piece. if (previous_right != MIN_INT32) { splitted_boxes->push_back(union_box); } } bool EquationDetect::CheckForSeed2( const GenericVector<int>& indented_texts_left, const float foreground_density_th, ColPartition* part) { ASSERT_HOST(part); const TBOX& box = part->bounding_box(); // Check if it is aligned with any indented_texts_left. if (!indented_texts_left.empty() && CountAlignment(indented_texts_left, box.left()) >= kLeftIndentAlignmentCountTh) { return false; } // Check the foreground density. if (ComputeForegroundDensity(box) > foreground_density_th) { return false; } return true; } int EquationDetect::CountAlignment( const GenericVector<int>& sorted_vec, const int val) const { if (sorted_vec.empty()) { return 0; } const int kDistTh = static_cast<int>(roundf(0.03 * resolution_)); int pos = sorted_vec.binary_search(val), count = 0; // Search left side. int index = pos; while (index >= 0 && abs(val - sorted_vec[index--]) < kDistTh) { count++; } // Search right side. index = pos + 1; while (index < sorted_vec.size() && sorted_vec[index++] - val < kDistTh) { count++; } return count; } void EquationDetect::IdentifyInlineParts() { ComputeCPsSuperBBox(); IdentifyInlinePartsHorizontal(); int textparts_linespacing = EstimateTextPartLineSpacing(); IdentifyInlinePartsVertical(true, textparts_linespacing); IdentifyInlinePartsVertical(false, textparts_linespacing); } void EquationDetect::ComputeCPsSuperBBox() { ColPartitionGridSearch gsearch(part_grid_); ColPartition *part = NULL; gsearch.StartFullSearch(); if (cps_super_bbox_) { delete cps_super_bbox_; } cps_super_bbox_ = new TBOX(); while ((part = gsearch.NextFullSearch()) != NULL) { (*cps_super_bbox_) += part->bounding_box(); } } void EquationDetect::IdentifyInlinePartsHorizontal() { ASSERT_HOST(cps_super_bbox_); GenericVector<ColPartition*> new_seeds; const int kMarginDiffTh = IntCastRounded( 0.5 * lang_tesseract_->source_resolution()); const int kGapTh = static_cast<int>(roundf( 1.0 * lang_tesseract_->source_resolution())); ColPartitionGridSearch search(part_grid_); search.SetUniqueMode(true); // The center x coordinate of the cp_super_bbox_. int cps_cx = cps_super_bbox_->left() + cps_super_bbox_->width() / 2; for (int i = 0; i < cp_seeds_.size(); ++i) { ColPartition* part = cp_seeds_[i]; const TBOX& part_box(part->bounding_box()); int left_margin = part_box.left() - cps_super_bbox_->left(), right_margin = cps_super_bbox_->right() - part_box.right(); bool right_to_left; if (left_margin + kMarginDiffTh < right_margin && left_margin < kMarginDiffTh) { // part is left aligned, so we search if it has any right neighbor. search.StartSideSearch( part_box.right(), part_box.top(), part_box.bottom()); right_to_left = false; } else if (left_margin > cps_cx) { // part locates on the right half on image, so search if it has any left // neighbor. search.StartSideSearch( part_box.left(), part_box.top(), part_box.bottom()); right_to_left = true; } else { // part is not an inline equation. new_seeds.push_back(part); continue; } ColPartition* neighbor = NULL; bool side_neighbor_found = false; while ((neighbor = search.NextSideSearch(right_to_left)) != NULL) { const TBOX& neighbor_box(neighbor->bounding_box()); if (!IsTextOrEquationType(neighbor->type()) || part_box.x_gap(neighbor_box) > kGapTh || !part_box.major_y_overlap(neighbor_box) || part_box.major_x_overlap(neighbor_box)) { continue; } // We have found one. Set the side_neighbor_found flag. side_neighbor_found = true; break; } if (!side_neighbor_found) { // Mark part as PT_INLINE_EQUATION. part->set_type(PT_INLINE_EQUATION); } else { // Check the geometric feature of neighbor. const TBOX& neighbor_box(neighbor->bounding_box()); if (neighbor_box.width() > part_box.width() && neighbor->type() != PT_EQUATION) { // Mark as PT_INLINE_EQUATION. part->set_type(PT_INLINE_EQUATION); } else { // part is not an inline equation type. new_seeds.push_back(part); } } } // Reset the cp_seeds_ using the new_seeds. cp_seeds_ = new_seeds; } int EquationDetect::EstimateTextPartLineSpacing() { ColPartitionGridSearch gsearch(part_grid_); // Get the y gap between text partitions; ColPartition *current = NULL, *prev = NULL; gsearch.StartFullSearch(); GenericVector<int> ygaps; while ((current = gsearch.NextFullSearch()) != NULL) { if (!PTIsTextType(current->type())) { continue; } if (prev != NULL) { const TBOX &current_box = current->bounding_box(); const TBOX &prev_box = prev->bounding_box(); // prev and current should be x major overlap and non y overlap. if (current_box.major_x_overlap(prev_box) && !current_box.y_overlap(prev_box)) { int gap = current_box.y_gap(prev_box); if (gap < MIN(current_box.height(), prev_box.height())) { // The gap should be smaller than the height of the bounding boxes. ygaps.push_back(gap); } } } prev = current; } if (ygaps.size() < 8) { // We do not have enough data. return -1; } // Compute the line spacing from ygaps: use the mean of the first half. ygaps.sort(); int spacing = 0, count; for (count = 0; count < ygaps.size() / 2; count++) { spacing += ygaps[count]; } return spacing / count; } void EquationDetect::IdentifyInlinePartsVertical( const bool top_to_bottom, const int textparts_linespacing) { if (cp_seeds_.empty()) { return; } // Sort cp_seeds_. if (top_to_bottom) { // From top to bottom. cp_seeds_.sort(&SortCPByTopReverse); } else { // From bottom to top. cp_seeds_.sort(&SortCPByBottom); } GenericVector<ColPartition*> new_seeds; for (int i = 0; i < cp_seeds_.size(); ++i) { ColPartition* part = cp_seeds_[i]; // If we sort cp_seeds_ from top to bottom, then for each cp_seeds_, we look // for its top neighbors, so that if two/more inline regions are connected // to each other, then we will identify the top one, and then use it to // identify the bottom one. if (IsInline(!top_to_bottom, textparts_linespacing, part)) { part->set_type(PT_INLINE_EQUATION); } else { new_seeds.push_back(part); } } cp_seeds_ = new_seeds; } bool EquationDetect::IsInline(const bool search_bottom, const int textparts_linespacing, ColPartition* part) { ASSERT_HOST(part != NULL); // Look for its nearest vertical neighbor that hardly overlaps in y but // largely overlaps in x. ColPartitionGridSearch search(part_grid_); ColPartition *neighbor = NULL; const TBOX& part_box(part->bounding_box()); const float kYGapRatioTh = 1.0; if (search_bottom) { search.StartVerticalSearch(part_box.left(), part_box.right(), part_box.bottom()); } else { search.StartVerticalSearch(part_box.left(), part_box.right(), part_box.top()); } search.SetUniqueMode(true); while ((neighbor = search.NextVerticalSearch(search_bottom)) != NULL) { const TBOX& neighbor_box(neighbor->bounding_box()); if (part_box.y_gap(neighbor_box) > kYGapRatioTh * MIN(part_box.height(), neighbor_box.height())) { // Finished searching. break; } if (!PTIsTextType(neighbor->type())) { continue; } // Check if neighbor and part is inline similar. const float kHeightRatioTh = 0.5; const int kYGapTh = textparts_linespacing > 0 ? textparts_linespacing + static_cast<int>(roundf(0.02 * resolution_)): static_cast<int>(roundf(0.05 * resolution_)); // Default value. if (part_box.x_overlap(neighbor_box) && // Location feature. part_box.y_gap(neighbor_box) <= kYGapTh && // Line spacing. // Geo feature. static_cast<float>(MIN(part_box.height(), neighbor_box.height())) / MAX(part_box.height(), neighbor_box.height()) > kHeightRatioTh) { return true; } } return false; } bool EquationDetect::CheckSeedBlobsCount(ColPartition* part) { if (!part) { return false; } const int kSeedMathBlobsCount = 2; const int kSeedMathDigitBlobsCount = 5; int blobs = part->boxes_count(), math_blobs = part->SpecialBlobsCount(BSTT_MATH), digit_blobs = part->SpecialBlobsCount(BSTT_DIGIT); if (blobs < kSeedBlobsCountTh || math_blobs <= kSeedMathBlobsCount || math_blobs + digit_blobs <= kSeedMathDigitBlobsCount) { return false; } return true; } bool EquationDetect::CheckSeedDensity( const float math_density_high, const float math_density_low, const ColPartition* part) const { ASSERT_HOST(part); float math_digit_density = part->SpecialBlobsDensity(BSTT_MATH) + part->SpecialBlobsDensity(BSTT_DIGIT); float italic_density = part->SpecialBlobsDensity(BSTT_ITALIC); if (math_digit_density > math_density_high) { return true; } if (math_digit_density + italic_density > kMathItalicDensityTh && math_digit_density > math_density_low) { return true; } return false; } EquationDetect::IndentType EquationDetect::IsIndented(ColPartition* part) { ASSERT_HOST(part); ColPartitionGridSearch search(part_grid_); ColPartition *neighbor = NULL; const TBOX& part_box(part->bounding_box()); const int kXGapTh = static_cast<int>(roundf(0.5 * resolution_)); const int kRadiusTh = static_cast<int>(roundf(3.0 * resolution_)); const int kYGapTh = static_cast<int>(roundf(0.5 * resolution_)); // Here we use a simple approximation algorithm: from the center of part, We // perform the radius search, and check if we can find a neighboring parition // that locates on the top/bottom left of part. search.StartRadSearch((part_box.left() + part_box.right()) / 2, (part_box.top() + part_box.bottom()) / 2, kRadiusTh); search.SetUniqueMode(true); bool left_indented = false, right_indented = false; while ((neighbor = search.NextRadSearch()) != NULL && (!left_indented || !right_indented)) { if (neighbor == part) { continue; } const TBOX& neighbor_box(neighbor->bounding_box()); if (part_box.major_y_overlap(neighbor_box) && part_box.x_gap(neighbor_box) < kXGapTh) { // When this happens, it is likely part is a fragment of an // over-segmented colpartition. So we return false. return NO_INDENT; } if (!IsTextOrEquationType(neighbor->type())) { continue; } // The neighbor should be above/below part, and overlap in x direction. if (!part_box.x_overlap(neighbor_box) || part_box.y_overlap(neighbor_box)) { continue; } if (part_box.y_gap(neighbor_box) < kYGapTh) { int left_gap = part_box.left() - neighbor_box.left(); int right_gap = neighbor_box.right() - part_box.right(); if (left_gap > kXGapTh) { left_indented = true; } if (right_gap > kXGapTh) { right_indented = true; } } } if (left_indented && right_indented) { return BOTH_INDENT; } if (left_indented) { return LEFT_INDENT; } if (right_indented) { return RIGHT_INDENT; } return NO_INDENT; } bool EquationDetect::ExpandSeed(ColPartition* seed) { if (seed == NULL || // This seed has been absorbed by other seeds. seed->IsVerticalType()) { // We skip vertical type right now. return false; } // Expand in four directions. GenericVector<ColPartition*> parts_to_merge; ExpandSeedHorizontal(true, seed, &parts_to_merge); ExpandSeedHorizontal(false, seed, &parts_to_merge); ExpandSeedVertical(true, seed, &parts_to_merge); ExpandSeedVertical(false, seed, &parts_to_merge); SearchByOverlap(seed, &parts_to_merge); if (parts_to_merge.empty()) { // We don't find any partition to merge. return false; } // Merge all partitions in parts_to_merge with seed. We first remove seed // from part_grid_ as its bounding box is going to expand. Then we add it // back after it aborbs all parts_to_merge parititions. part_grid_->RemoveBBox(seed); for (int i = 0; i < parts_to_merge.size(); ++i) { ColPartition* part = parts_to_merge[i]; if (part->type() == PT_EQUATION) { // If part is in cp_seeds_, then we mark it as NULL so that we won't // process it again. for (int j = 0; j < cp_seeds_.size(); ++j) { if (part == cp_seeds_[j]) { cp_seeds_[j] = NULL; break; } } } // part has already been removed from part_grid_ in function // ExpandSeedHorizontal/ExpandSeedVertical. seed->Absorb(part, NULL); } return true; } void EquationDetect::ExpandSeedHorizontal( const bool search_left, ColPartition* seed, GenericVector<ColPartition*>* parts_to_merge) { ASSERT_HOST(seed != NULL && parts_to_merge != NULL); const float kYOverlapTh = 0.6; const int kXGapTh = static_cast<int>(roundf(0.2 * resolution_)); ColPartitionGridSearch search(part_grid_); const TBOX& seed_box(seed->bounding_box()); int x = search_left ? seed_box.left() : seed_box.right(); search.StartSideSearch(x, seed_box.bottom(), seed_box.top()); search.SetUniqueMode(true); // Search iteratively. ColPartition *part = NULL; while ((part = search.NextSideSearch(search_left)) != NULL) { if (part == seed) { continue; } const TBOX& part_box(part->bounding_box()); if (part_box.x_gap(seed_box) > kXGapTh) { // Out of scope. break; } // Check part location. if ((part_box.left() >= seed_box.left() && search_left) || (part_box.right() <= seed_box.right() && !search_left)) { continue; } if (part->type() != PT_EQUATION) { // Non-equation type. // Skip PT_LINLINE_EQUATION and non text type. if (part->type() == PT_INLINE_EQUATION || (!IsTextOrEquationType(part->type()) && part->blob_type() != BRT_HLINE)) { continue; } // For other types, it should be the near small neighbor of seed. if (!IsNearSmallNeighbor(seed_box, part_box) || !CheckSeedNeighborDensity(part)) { continue; } } else { // Equation type, check the y overlap. if (part_box.y_overlap_fraction(seed_box) < kYOverlapTh && seed_box.y_overlap_fraction(part_box) < kYOverlapTh) { continue; } } // Passed the check, delete it from search and add into parts_to_merge. search.RemoveBBox(); parts_to_merge->push_back(part); } } void EquationDetect::ExpandSeedVertical( const bool search_bottom, ColPartition* seed, GenericVector<ColPartition*>* parts_to_merge) { ASSERT_HOST(seed != NULL && parts_to_merge != NULL && cps_super_bbox_ != NULL); const float kXOverlapTh = 0.4; const int kYGapTh = static_cast<int>(roundf(0.2 * resolution_)); ColPartitionGridSearch search(part_grid_); const TBOX& seed_box(seed->bounding_box()); int y = search_bottom ? seed_box.bottom() : seed_box.top(); search.StartVerticalSearch( cps_super_bbox_->left(), cps_super_bbox_->right(), y); search.SetUniqueMode(true); // Search iteratively. ColPartition *part = NULL; GenericVector<ColPartition*> parts; int skipped_min_top = INT_MAX, skipped_max_bottom = -1; while ((part = search.NextVerticalSearch(search_bottom)) != NULL) { if (part == seed) { continue; } const TBOX& part_box(part->bounding_box()); if (part_box.y_gap(seed_box) > kYGapTh) { // Out of scope. break; } // Check part location. if ((part_box.bottom() >= seed_box.bottom() && search_bottom) || (part_box.top() <= seed_box.top() && !search_bottom)) { continue; } bool skip_part = false; if (part->type() != PT_EQUATION) { // Non-equation type. // Skip PT_LINLINE_EQUATION and non text type. if (part->type() == PT_INLINE_EQUATION || (!IsTextOrEquationType(part->type()) && part->blob_type() != BRT_HLINE)) { skip_part = true; } else if (!IsNearSmallNeighbor(seed_box, part_box) || !CheckSeedNeighborDensity(part)) { // For other types, it should be the near small neighbor of seed. skip_part = true; } } else { // Equation type, check the x overlap. if (part_box.x_overlap_fraction(seed_box) < kXOverlapTh && seed_box.x_overlap_fraction(part_box) < kXOverlapTh) { skip_part = true; } } if (skip_part) { if (part->type() != PT_EQUATION) { if (skipped_min_top > part_box.top()) { skipped_min_top = part_box.top(); } if (skipped_max_bottom < part_box.bottom()) { skipped_max_bottom = part_box.bottom(); } } } else { parts.push_back(part); } } // For every part in parts, we need verify it is not above skipped_min_top // when search top, or not below skipped_max_bottom when search bottom. I.e., // we will skip a part if it looks like: // search bottom | search top // seed: ****************** | part: ********** // skipped: xxx | skipped: xxx // part: ********** | seed: *********** for (int i = 0; i < parts.size(); i++) { const TBOX& part_box(parts[i]->bounding_box()); if ((search_bottom && part_box.top() <= skipped_max_bottom) || (!search_bottom && part_box.bottom() >= skipped_min_top)) { continue; } // Add parts[i] into parts_to_merge, and delete it from part_grid_. parts_to_merge->push_back(parts[i]); part_grid_->RemoveBBox(parts[i]); } } bool EquationDetect::IsNearSmallNeighbor(const TBOX& seed_box, const TBOX& part_box) const { const int kXGapTh = static_cast<int>(roundf(0.25 * resolution_)); const int kYGapTh = static_cast<int>(roundf(0.05 * resolution_)); // Check geometric feature. if (part_box.height() > seed_box.height() || part_box.width() > seed_box.width()) { return false; } // Check overlap and distance. if ((!part_box.major_x_overlap(seed_box) || part_box.y_gap(seed_box) > kYGapTh) && (!part_box.major_y_overlap(seed_box) || part_box.x_gap(seed_box) > kXGapTh)) { return false; } return true; } bool EquationDetect::CheckSeedNeighborDensity(const ColPartition* part) const { ASSERT_HOST(part); if (part->boxes_count() < kSeedBlobsCountTh) { // Too few blobs, skip the check. return true; } // We check the math blobs density and the unclear blobs density. if (part->SpecialBlobsDensity(BSTT_MATH) + part->SpecialBlobsDensity(BSTT_DIGIT) > kMathDigitDensityTh1 || part->SpecialBlobsDensity(BSTT_UNCLEAR) > kUnclearDensityTh) { return true; } return false; } void EquationDetect::ProcessMathBlockSatelliteParts() { // Iterate over part_grid_, and find all parts that are text type but not // equation type. ColPartition *part = NULL; GenericVector<ColPartition*> text_parts; ColPartitionGridSearch gsearch(part_grid_); gsearch.StartFullSearch(); while ((part = gsearch.NextFullSearch()) != NULL) { if (part->type() == PT_FLOWING_TEXT || part->type() == PT_HEADING_TEXT) { text_parts.push_back(part); } } if (text_parts.empty()) { return; } // Compute the medium height of the text_parts. text_parts.sort(&SortCPByHeight); const TBOX& text_box = text_parts[text_parts.size() / 2]->bounding_box(); int med_height = text_box.height(); if (text_parts.size() % 2 == 0 && text_parts.size() > 1) { const TBOX& text_box = text_parts[text_parts.size() / 2 - 1]->bounding_box(); med_height = static_cast<int>(roundf( 0.5 * (text_box.height() + med_height))); } // Iterate every text_parts and check if it is a math block satellite. for (int i = 0; i < text_parts.size(); ++i) { const TBOX& text_box(text_parts[i]->bounding_box()); if (text_box.height() > med_height) { continue; } GenericVector<ColPartition*> math_blocks; if (!IsMathBlockSatellite(text_parts[i], &math_blocks)) { continue; } // Found. merge text_parts[i] with math_blocks. part_grid_->RemoveBBox(text_parts[i]); text_parts[i]->set_type(PT_EQUATION); for (int j = 0; j < math_blocks.size(); ++j) { part_grid_->RemoveBBox(math_blocks[j]); text_parts[i]->Absorb(math_blocks[j], NULL); } InsertPartAfterAbsorb(text_parts[i]); } } bool EquationDetect::IsMathBlockSatellite( ColPartition* part, GenericVector<ColPartition*>* math_blocks) { ASSERT_HOST(part != NULL && math_blocks != NULL); math_blocks->clear(); const TBOX& part_box(part->bounding_box()); // Find the top/bottom nearest neighbor of part. ColPartition *neighbors[2]; int y_gaps[2] = {INT_MAX, INT_MAX}; // The horizontal boundary of the neighbors. int neighbors_left = INT_MAX, neighbors_right = 0; for (int i = 0; i < 2; ++i) { neighbors[i] = SearchNNVertical(i != 0, part); if (neighbors[i]) { const TBOX& neighbor_box = neighbors[i]->bounding_box(); y_gaps[i] = neighbor_box.y_gap(part_box); if (neighbor_box.left() < neighbors_left) { neighbors_left = neighbor_box.left(); } if (neighbor_box.right() > neighbors_right) { neighbors_right = neighbor_box.right(); } } } if (neighbors[0] == neighbors[1]) { // This happens when part is inside neighbor. neighbors[1] = NULL; y_gaps[1] = INT_MAX; } // Check if part is within [neighbors_left, neighbors_right]. if (part_box.left() < neighbors_left || part_box.right() > neighbors_right) { return false; } // Get the index of the near one in neighbors. int index = y_gaps[0] < y_gaps[1] ? 0 : 1; // Check the near one. if (IsNearMathNeighbor(y_gaps[index], neighbors[index])) { math_blocks->push_back(neighbors[index]); } else { // If the near one failed the check, then we skip checking the far one. return false; } // Check the far one. index = 1 - index; if (IsNearMathNeighbor(y_gaps[index], neighbors[index])) { math_blocks->push_back(neighbors[index]); } return true; } ColPartition* EquationDetect::SearchNNVertical( const bool search_bottom, const ColPartition* part) { ASSERT_HOST(part); ColPartition *nearest_neighbor = NULL, *neighbor = NULL; const int kYGapTh = static_cast<int>(roundf(resolution_ * 0.5)); ColPartitionGridSearch search(part_grid_); search.SetUniqueMode(true); const TBOX& part_box(part->bounding_box()); int y = search_bottom ? part_box.bottom() : part_box.top(); search.StartVerticalSearch(part_box.left(), part_box.right(), y); int min_y_gap = INT_MAX; while ((neighbor = search.NextVerticalSearch(search_bottom)) != NULL) { if (neighbor == part || !IsTextOrEquationType(neighbor->type())) { continue; } const TBOX& neighbor_box(neighbor->bounding_box()); int y_gap = neighbor_box.y_gap(part_box); if (y_gap > kYGapTh) { // Out of scope. break; } if (!neighbor_box.major_x_overlap(part_box) || (search_bottom && neighbor_box.bottom() > part_box.bottom()) || (!search_bottom && neighbor_box.top() < part_box.top())) { continue; } if (y_gap < min_y_gap) { min_y_gap = y_gap; nearest_neighbor = neighbor; } } return nearest_neighbor; } bool EquationDetect::IsNearMathNeighbor( const int y_gap, const ColPartition *neighbor) const { if (!neighbor) { return false; } const int kYGapTh = static_cast<int>(roundf(resolution_ * 0.1)); return neighbor->type() == PT_EQUATION && y_gap <= kYGapTh; } void EquationDetect::GetOutputTiffName(const char* name, STRING* image_name) const { ASSERT_HOST(image_name && name); char page[50]; snprintf(page, sizeof(page), "%04d", page_count_); *image_name = STRING(lang_tesseract_->imagebasename) + page + name + ".tif"; } void EquationDetect::PaintSpecialTexts(const STRING& outfile) const { Pix *pix = NULL, *pixBi = lang_tesseract_->pix_binary(); pix = pixConvertTo32(pixBi); ColPartitionGridSearch gsearch(part_grid_); ColPartition* part = NULL; gsearch.StartFullSearch(); while ((part = gsearch.NextFullSearch()) != NULL) { BLOBNBOX_C_IT blob_it(part->boxes()); for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { RenderSpecialText(pix, blob_it.data()); } } pixWrite(outfile.string(), pix, IFF_TIFF_LZW); pixDestroy(&pix); } void EquationDetect::PaintColParts(const STRING& outfile) const { Pix *pix = pixConvertTo32(lang_tesseract_->BestPix()); ColPartitionGridSearch gsearch(part_grid_); gsearch.StartFullSearch(); ColPartition* part = NULL; while ((part = gsearch.NextFullSearch()) != NULL) { const TBOX& tbox = part->bounding_box(); Box *box = boxCreate(tbox.left(), pixGetHeight(pix) - tbox.top(), tbox.width(), tbox.height()); if (part->type() == PT_EQUATION) { pixRenderBoxArb(pix, box, 5, 255, 0, 0); } else if (part->type() == PT_INLINE_EQUATION) { pixRenderBoxArb(pix, box, 5, 0, 255, 0); } else { pixRenderBoxArb(pix, box, 5, 0, 0, 255); } boxDestroy(&box); } pixWrite(outfile.string(), pix, IFF_TIFF_LZW); pixDestroy(&pix); } void EquationDetect::PrintSpecialBlobsDensity(const ColPartition* part) const { ASSERT_HOST(part); TBOX box(part->bounding_box()); int h = pixGetHeight(lang_tesseract_->BestPix()); tprintf("Printing special blobs density values for ColParition (t=%d,b=%d) ", h - box.top(), h - box.bottom()); box.print(); tprintf("blobs count = %d, density = ", part->boxes_count()); for (int i = 0; i < BSTT_COUNT; ++i) { BlobSpecialTextType type = static_cast<BlobSpecialTextType>(i); tprintf("%d:%f ", i, part->SpecialBlobsDensity(type)); } tprintf("\n"); } }; // namespace tesseract
1080228-arabicocr11
ccmain/equationdetect.cpp
C++
asf20
52,372
// Copyright 2011 Google Inc. All Rights Reserved. // Author: rays@google.com (Ray Smith) /////////////////////////////////////////////////////////////////////// // File: cubeclassifier.h // Description: Cube implementation of a ShapeClassifier. // Author: Ray Smith // Created: Wed Nov 23 10:36:32 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 THIRD_PARTY_TESSERACT_CCMAIN_CUBECLASSIFIER_H_ #define THIRD_PARTY_TESSERACT_CCMAIN_CUBECLASSIFIER_H_ #include "shapeclassifier.h" namespace tesseract { class Classify; class CubeRecoContext; class ShapeTable; class TessClassifier; class Tesseract; class TrainingSample; struct UnicharRating; // Cube implementation of a ShapeClassifier. class CubeClassifier : public ShapeClassifier { public: explicit CubeClassifier(Tesseract* tesseract); virtual ~CubeClassifier(); // Classifies the given [training] sample, writing to results. // See ShapeClassifier for a full description. virtual int UnicharClassifySample(const TrainingSample& sample, Pix* page_pix, int debug, UNICHAR_ID keep_this, GenericVector<UnicharRating>* results); // Provides access to the ShapeTable that this classifier works with. virtual const ShapeTable* GetShapeTable() const; private: // Cube objects. CubeRecoContext* cube_cntxt_; const ShapeTable& shape_table_; }; // Combination of Tesseract class pruner with scoring by cube. class CubeTessClassifier : public ShapeClassifier { public: explicit CubeTessClassifier(Tesseract* tesseract); virtual ~CubeTessClassifier(); // Classifies the given [training] sample, writing to results. // See ShapeClassifier for a full description. virtual int UnicharClassifySample(const TrainingSample& sample, Pix* page_pix, int debug, UNICHAR_ID keep_this, GenericVector<UnicharRating>* results); // Provides access to the ShapeTable that this classifier works with. virtual const ShapeTable* GetShapeTable() const; private: // Cube objects. CubeRecoContext* cube_cntxt_; const ShapeTable& shape_table_; TessClassifier* pruner_; }; } // namespace tesseract #endif /* THIRD_PARTY_TESSERACT_CCMAIN_CUBECLASSIFIER_H_ */
1080228-arabicocr11
ccmain/cubeclassifier.h
C++
asf20
2,920
/********************************************************************** * File: pagesegmain.cpp * Description: Top-level page segmenter for Tesseract. * Author: Ray Smith * Created: Thu Sep 25 17:12:01 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. * **********************************************************************/ #ifdef _WIN32 #ifndef __GNUC__ #include <windows.h> #endif // __GNUC__ #ifndef unlink #include <io.h> #endif #else #include <unistd.h> #endif // _WIN32 #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "allheaders.h" #include "blobbox.h" #include "blread.h" #include "colfind.h" #include "equationdetect.h" #include "imagefind.h" #include "linefind.h" #include "makerow.h" #include "osdetect.h" #include "tabvector.h" #include "tesseractclass.h" #include "tessvars.h" #include "textord.h" #include "tordmain.h" #include "wordseg.h" namespace tesseract { /// Minimum believable resolution. const int kMinCredibleResolution = 70; /// Default resolution used if input in not believable. const int kDefaultResolution = 300; // Max erosions to perform in removing an enclosing circle. const int kMaxCircleErosions = 8; // Helper to remove an enclosing circle from an image. // If there isn't one, then the image will most likely get badly mangled. // The returned pix must be pixDestroyed after use. NULL may be returned // if the image doesn't meet the trivial conditions that it uses to determine // success. static Pix* RemoveEnclosingCircle(Pix* pixs) { Pix* pixsi = pixInvert(NULL, pixs); Pix* pixc = pixCreateTemplate(pixs); pixSetOrClearBorder(pixc, 1, 1, 1, 1, PIX_SET); pixSeedfillBinary(pixc, pixc, pixsi, 4); pixInvert(pixc, pixc); pixDestroy(&pixsi); Pix* pixt = pixAnd(NULL, pixs, pixc); l_int32 max_count; pixCountConnComp(pixt, 8, &max_count); // The count has to go up before we start looking for the minimum. l_int32 min_count = MAX_INT32; Pix* pixout = NULL; for (int i = 1; i < kMaxCircleErosions; i++) { pixDestroy(&pixt); pixErodeBrick(pixc, pixc, 3, 3); pixt = pixAnd(NULL, pixs, pixc); l_int32 count; pixCountConnComp(pixt, 8, &count); if (i == 1 || count > max_count) { max_count = count; min_count = count; } else if (i > 1 && count < min_count) { min_count = count; pixDestroy(&pixout); pixout = pixCopy(NULL, pixt); // Save the best. } else if (count >= min_count) { break; // We have passed by the best. } } pixDestroy(&pixt); pixDestroy(&pixc); return pixout; } /** * Segment the page according to the current value of tessedit_pageseg_mode. * pix_binary_ is used as the source image and should not be NULL. * On return the blocks list owns all the constructed page layout. */ int Tesseract::SegmentPage(const STRING* input_file, BLOCK_LIST* blocks, Tesseract* osd_tess, OSResults* osr) { ASSERT_HOST(pix_binary_ != NULL); int width = pixGetWidth(pix_binary_); int height = pixGetHeight(pix_binary_); // Get page segmentation mode. PageSegMode pageseg_mode = static_cast<PageSegMode>( static_cast<int>(tessedit_pageseg_mode)); // If a UNLV zone file can be found, use that instead of segmentation. if (!PSM_COL_FIND_ENABLED(pageseg_mode) && input_file != NULL && input_file->length() > 0) { STRING name = *input_file; const char* lastdot = strrchr(name.string(), '.'); if (lastdot != NULL) name[lastdot - name.string()] = '\0'; read_unlv_file(name, width, height, blocks); } if (blocks->empty()) { // No UNLV file present. Work according to the PageSegMode. // First make a single block covering the whole image. BLOCK_IT block_it(blocks); BLOCK* block = new BLOCK("", TRUE, 0, 0, 0, 0, width, height); block->set_right_to_left(right_to_left()); block_it.add_to_end(block); } else { // UNLV file present. Use PSM_SINGLE_BLOCK. pageseg_mode = PSM_SINGLE_BLOCK; } int auto_page_seg_ret_val = 0; TO_BLOCK_LIST to_blocks; if (PSM_OSD_ENABLED(pageseg_mode) || PSM_BLOCK_FIND_ENABLED(pageseg_mode) || PSM_SPARSE(pageseg_mode)) { auto_page_seg_ret_val = AutoPageSeg(pageseg_mode, blocks, &to_blocks, osd_tess, osr); if (pageseg_mode == PSM_OSD_ONLY) return auto_page_seg_ret_val; // To create blobs from the image region bounds uncomment this line: // to_blocks.clear(); // Uncomment to go back to the old mode. } else { deskew_ = FCOORD(1.0f, 0.0f); reskew_ = FCOORD(1.0f, 0.0f); if (pageseg_mode == PSM_CIRCLE_WORD) { Pix* pixcleaned = RemoveEnclosingCircle(pix_binary_); if (pixcleaned != NULL) { pixDestroy(&pix_binary_); pix_binary_ = pixcleaned; } } } if (auto_page_seg_ret_val < 0) { return -1; } if (blocks->empty()) { if (textord_debug_tabfind) tprintf("Empty page\n"); return 0; // AutoPageSeg found an empty page. } bool splitting = pageseg_devanagari_split_strategy != ShiroRekhaSplitter::NO_SPLIT; bool cjk_mode = textord_use_cjk_fp_model; textord_.TextordPage(pageseg_mode, reskew_, width, height, pix_binary_, pix_thresholds_, pix_grey_, splitting || cjk_mode, blocks, &to_blocks); return auto_page_seg_ret_val; } // Helper writes a grey image to a file for use by scrollviewer. // Normally for speed we don't display the image in the layout debug windows. // If textord_debug_images is true, we draw the image as a background to some // of the debug windows. printable determines whether these // images are optimized for printing instead of screen display. static void WriteDebugBackgroundImage(bool printable, Pix* pix_binary) { Pix* grey_pix = pixCreate(pixGetWidth(pix_binary), pixGetHeight(pix_binary), 8); // Printable images are light grey on white, but for screen display // they are black on dark grey so the other colors show up well. if (printable) { pixSetAll(grey_pix); pixSetMasked(grey_pix, pix_binary, 192); } else { pixSetAllArbitrary(grey_pix, 64); pixSetMasked(grey_pix, pix_binary, 0); } AlignedBlob::IncrementDebugPix(); pixWrite(AlignedBlob::textord_debug_pix().string(), grey_pix, IFF_PNG); pixDestroy(&grey_pix); } /** * Auto page segmentation. Divide the page image into blocks of uniform * text linespacing and images. * * Resolution (in ppi) is derived from the input image. * * The output goes in the blocks list with corresponding TO_BLOCKs in the * to_blocks list. * * If single_column is true, then no attempt is made to divide the image * into columns, but multiple blocks are still made if the text is of * non-uniform linespacing. * * If osd (orientation and script detection) is true then that is performed * as well. If only_osd is true, then only orientation and script detection is * performed. If osd is desired, (osd or only_osd) then osr_tess must be * another Tesseract that was initialized especially for osd, and the results * will be output into osr (orientation and script result). */ int Tesseract::AutoPageSeg(PageSegMode pageseg_mode, BLOCK_LIST* blocks, TO_BLOCK_LIST* to_blocks, Tesseract* osd_tess, OSResults* osr) { if (textord_debug_images) { WriteDebugBackgroundImage(textord_debug_printable, pix_binary_); } Pix* photomask_pix = NULL; Pix* musicmask_pix = NULL; // The blocks made by the ColumnFinder. Moved to blocks before return. BLOCK_LIST found_blocks; TO_BLOCK_LIST temp_blocks; bool single_column = !PSM_COL_FIND_ENABLED(pageseg_mode); bool osd_enabled = PSM_OSD_ENABLED(pageseg_mode); bool osd_only = pageseg_mode == PSM_OSD_ONLY; ColumnFinder* finder = SetupPageSegAndDetectOrientation( single_column, osd_enabled, osd_only, blocks, osd_tess, osr, &temp_blocks, &photomask_pix, &musicmask_pix); int result = 0; if (finder != NULL) { TO_BLOCK_IT to_block_it(&temp_blocks); TO_BLOCK* to_block = to_block_it.data(); if (musicmask_pix != NULL) { // TODO(rays) pass the musicmask_pix into FindBlocks and mark music // blocks separately. For now combine with photomask_pix. pixOr(photomask_pix, photomask_pix, musicmask_pix); } if (equ_detect_) { finder->SetEquationDetect(equ_detect_); } result = finder->FindBlocks(pageseg_mode, scaled_color_, scaled_factor_, to_block, photomask_pix, pix_thresholds_, pix_grey_, &found_blocks, to_blocks); if (result >= 0) finder->GetDeskewVectors(&deskew_, &reskew_); delete finder; } pixDestroy(&photomask_pix); pixDestroy(&musicmask_pix); if (result < 0) return result; blocks->clear(); BLOCK_IT block_it(blocks); // Move the found blocks to the input/output blocks. block_it.add_list_after(&found_blocks); if (textord_debug_images) { // The debug image is no longer needed so delete it. unlink(AlignedBlob::textord_debug_pix().string()); } return result; } // Helper adds all the scripts from sid_set converted to ids from osd_set to // allowed_ids. static void AddAllScriptsConverted(const UNICHARSET& sid_set, const UNICHARSET& osd_set, GenericVector<int>* allowed_ids) { for (int i = 0; i < sid_set.get_script_table_size(); ++i) { if (i != sid_set.null_sid()) { const char* script = sid_set.get_script_from_script_id(i); allowed_ids->push_back(osd_set.get_script_id_from_name(script)); } } } /** * Sets up auto page segmentation, determines the orientation, and corrects it. * Somewhat arbitrary chunk of functionality, factored out of AutoPageSeg to * facilitate testing. * photo_mask_pix is a pointer to a NULL pointer that will be filled on return * with the leptonica photo mask, which must be pixDestroyed by the caller. * to_blocks is an empty list that will be filled with (usually a single) * block that is used during layout analysis. This ugly API is required * because of the possibility of a unlv zone file. * TODO(rays) clean this up. * See AutoPageSeg for other arguments. * The returned ColumnFinder must be deleted after use. */ ColumnFinder* Tesseract::SetupPageSegAndDetectOrientation( bool single_column, bool osd, bool only_osd, BLOCK_LIST* blocks, Tesseract* osd_tess, OSResults* osr, TO_BLOCK_LIST* to_blocks, Pix** photo_mask_pix, Pix** music_mask_pix) { int vertical_x = 0; int vertical_y = 1; TabVector_LIST v_lines; TabVector_LIST h_lines; ICOORD bleft(0, 0); ASSERT_HOST(pix_binary_ != NULL); if (tessedit_dump_pageseg_images) { pixWrite("tessinput.png", pix_binary_, IFF_PNG); } // Leptonica is used to find the rule/separator lines in the input. LineFinder::FindAndRemoveLines(source_resolution_, textord_tabfind_show_vlines, pix_binary_, &vertical_x, &vertical_y, music_mask_pix, &v_lines, &h_lines); if (tessedit_dump_pageseg_images) pixWrite("tessnolines.png", pix_binary_, IFF_PNG); // Leptonica is used to find a mask of the photo regions in the input. *photo_mask_pix = ImageFind::FindImages(pix_binary_); if (tessedit_dump_pageseg_images) pixWrite("tessnoimages.png", pix_binary_, IFF_PNG); if (single_column) v_lines.clear(); // The rest of the algorithm uses the usual connected components. textord_.find_components(pix_binary_, blocks, to_blocks); TO_BLOCK_IT to_block_it(to_blocks); // There must be exactly one input block. // TODO(rays) handle new textline finding with a UNLV zone file. ASSERT_HOST(to_blocks->singleton()); TO_BLOCK* to_block = to_block_it.data(); TBOX blkbox = to_block->block->bounding_box(); ColumnFinder* finder = NULL; if (to_block->line_size >= 2) { finder = new ColumnFinder(static_cast<int>(to_block->line_size), blkbox.botleft(), blkbox.topright(), source_resolution_, textord_use_cjk_fp_model, textord_tabfind_aligned_gap_fraction, &v_lines, &h_lines, vertical_x, vertical_y); finder->SetupAndFilterNoise(*photo_mask_pix, to_block); if (equ_detect_) { equ_detect_->LabelSpecialText(to_block); } BLOBNBOX_CLIST osd_blobs; // osd_orientation is the number of 90 degree rotations to make the // characters upright. (See osdetect.h for precise definition.) // We want the text lines horizontal, (vertical text indicates vertical // textlines) which may conflict (eg vertically written CJK). int osd_orientation = 0; bool vertical_text = textord_tabfind_force_vertical_text; if (!vertical_text && textord_tabfind_vertical_text) { vertical_text = finder->IsVerticallyAlignedText(textord_tabfind_vertical_text_ratio, to_block, &osd_blobs); } if (osd && osd_tess != NULL && osr != NULL) { GenericVector<int> osd_scripts; if (osd_tess != this) { // We are running osd as part of layout analysis, so constrain the // scripts to those allowed by *this. AddAllScriptsConverted(unicharset, osd_tess->unicharset, &osd_scripts); for (int s = 0; s < sub_langs_.size(); ++s) { AddAllScriptsConverted(sub_langs_[s]->unicharset, osd_tess->unicharset, &osd_scripts); } } os_detect_blobs(&osd_scripts, &osd_blobs, osr, osd_tess); if (only_osd) { delete finder; return NULL; } osd_orientation = osr->best_result.orientation_id; double osd_score = osr->orientations[osd_orientation]; double osd_margin = min_orientation_margin * 2; for (int i = 0; i < 4; ++i) { if (i != osd_orientation && osd_score - osr->orientations[i] < osd_margin) { osd_margin = osd_score - osr->orientations[i]; } } int best_script_id = osr->best_result.script_id; const char* best_script_str = osd_tess->unicharset.get_script_from_script_id(best_script_id); bool cjk = best_script_id == osd_tess->unicharset.han_sid() || best_script_id == osd_tess->unicharset.hiragana_sid() || best_script_id == osd_tess->unicharset.katakana_sid() || strcmp("Japanese", best_script_str) == 0 || strcmp("Korean", best_script_str) == 0 || strcmp("Hangul", best_script_str) == 0; if (cjk) { finder->set_cjk_script(true); } if (osd_margin < min_orientation_margin) { // The margin is weak. if (!cjk && !vertical_text && osd_orientation == 2) { // upside down latin text is improbable with such a weak margin. tprintf("OSD: Weak margin (%.2f), horiz textlines, not CJK: " "Don't rotate.\n", osd_margin); osd_orientation = 0; } else { tprintf("OSD: Weak margin (%.2f) for %d blob text block, " "but using orientation anyway: %d\n", osd_blobs.length(), osd_margin, osd_orientation); } } } osd_blobs.shallow_clear(); finder->CorrectOrientation(to_block, vertical_text, osd_orientation); } return finder; } } // namespace tesseract.
1080228-arabicocr11
ccmain/pagesegmain.cpp
C++
asf20
16,216
/////////////////////////////////////////////////////////////////////// // File: ltrresultiterator.cpp // 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 14:32:09 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. // /////////////////////////////////////////////////////////////////////// #include "ltrresultiterator.h" #include "allheaders.h" #include "pageres.h" #include "strngs.h" #include "tesseractclass.h" namespace tesseract { LTRResultIterator::LTRResultIterator(PAGE_RES* page_res, Tesseract* tesseract, int scale, int scaled_yres, int rect_left, int rect_top, int rect_width, int rect_height) : PageIterator(page_res, tesseract, scale, scaled_yres, rect_left, rect_top, rect_width, rect_height), line_separator_("\n"), paragraph_separator_("\n") { } LTRResultIterator::~LTRResultIterator() { } // Returns the null terminated UTF-8 encoded text string for the current // object at the given level. Use delete [] to free after use. char* LTRResultIterator::GetUTF8Text(PageIteratorLevel level) const { if (it_->word() == NULL) return NULL; // Already at the end! STRING text; PAGE_RES_IT res_it(*it_); WERD_CHOICE* best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); if (level == RIL_SYMBOL) { text = res_it.word()->BestUTF8(blob_index_, false); } else if (level == RIL_WORD) { text = best_choice->unichar_string(); } else { bool eol = false; // end of line? bool eop = false; // end of paragraph? do { // for each paragraph in a block do { // for each text line in a paragraph do { // for each word in a text line best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); text += best_choice->unichar_string(); text += " "; res_it.forward(); eol = res_it.row() != res_it.prev_row(); } while (!eol); text.truncate_at(text.length() - 1); text += line_separator_; eop = res_it.block() != res_it.prev_block() || res_it.row()->row->para() != res_it.prev_row()->row->para(); } while (level != RIL_TEXTLINE && !eop); if (eop) text += paragraph_separator_; } while (level == RIL_BLOCK && res_it.block() == res_it.prev_block()); } int length = text.length() + 1; char* result = new char[length]; strncpy(result, text.string(), length); return result; } // Set the string inserted at the end of each text line. "\n" by default. void LTRResultIterator::SetLineSeparator(const char *new_line) { line_separator_ = new_line; } // Set the string inserted at the end of each paragraph. "\n" by default. void LTRResultIterator::SetParagraphSeparator(const char *new_para) { paragraph_separator_ = 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 LTRResultIterator::Confidence(PageIteratorLevel level) const { if (it_->word() == NULL) return 0.0f; // Already at the end! float mean_certainty = 0.0f; int certainty_count = 0; PAGE_RES_IT res_it(*it_); WERD_CHOICE* best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); switch (level) { case RIL_BLOCK: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.block() == res_it.prev_block()); break; case RIL_PARA: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.block() == res_it.prev_block() && res_it.row()->row->para() == res_it.prev_row()->row->para()); break; case RIL_TEXTLINE: do { best_choice = res_it.word()->best_choice; ASSERT_HOST(best_choice != NULL); mean_certainty += best_choice->certainty(); ++certainty_count; res_it.forward(); } while (res_it.row() == res_it.prev_row()); break; case RIL_WORD: mean_certainty += best_choice->certainty(); ++certainty_count; break; case RIL_SYMBOL: mean_certainty += best_choice->certainty(blob_index_); ++certainty_count; } if (certainty_count > 0) { mean_certainty /= certainty_count; float confidence = 100 + 5 * mean_certainty; if (confidence < 0.0f) confidence = 0.0f; if (confidence > 100.0f) confidence = 100.0f; return confidence; } return 0.0f; } // 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* LTRResultIterator::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 { if (it_->word() == NULL) return NULL; // Already at the end! if (it_->word()->fontinfo == NULL) { *font_id = -1; return NULL; // No font information. } const FontInfo& font_info = *it_->word()->fontinfo; *font_id = font_info.universal_id; *is_bold = font_info.is_bold(); *is_italic = font_info.is_italic(); *is_underlined = false; // TODO(rays) fix this! *is_monospace = font_info.is_fixed_pitch(); *is_serif = font_info.is_serif(); *is_smallcaps = it_->word()->small_caps; float row_height = it_->row()->row->x_height() + it_->row()->row->ascenders() - it_->row()->row->descenders(); // Convert from pixels to printers points. *pointsize = scaled_yres_ > 0 ? static_cast<int>(row_height * kPointsPerInch / scaled_yres_ + 0.5) : 0; return font_info.name; } // Returns the name of the language used to recognize this word. const char* LTRResultIterator::WordRecognitionLanguage() const { if (it_->word() == NULL || it_->word()->tesseract == NULL) return NULL; return it_->word()->tesseract->lang.string(); } // Return the overall directionality of this word. StrongScriptDirection LTRResultIterator::WordDirection() const { if (it_->word() == NULL) return DIR_NEUTRAL; bool has_rtl = it_->word()->AnyRtlCharsInWord(); bool has_ltr = it_->word()->AnyLtrCharsInWord(); if (has_rtl && !has_ltr) return DIR_RIGHT_TO_LEFT; if (has_ltr && !has_rtl) return DIR_LEFT_TO_RIGHT; if (!has_ltr && !has_rtl) return DIR_NEUTRAL; return DIR_MIX; } // Returns true if the current word was found in a dictionary. bool LTRResultIterator::WordIsFromDictionary() const { if (it_->word() == NULL) return false; // Already at the end! int permuter = it_->word()->best_choice->permuter(); return permuter == SYSTEM_DAWG_PERM || permuter == FREQ_DAWG_PERM || permuter == USER_DAWG_PERM; } // Returns true if the current word is numeric. bool LTRResultIterator::WordIsNumeric() const { if (it_->word() == NULL) return false; // Already at the end! int permuter = it_->word()->best_choice->permuter(); return permuter == NUMBER_PERM; } // Returns true if the word contains blamer information. bool LTRResultIterator::HasBlamerInfo() const { return it_->word() != NULL && it_->word()->blamer_bundle != NULL && it_->word()->blamer_bundle->HasDebugInfo(); } // Returns the pointer to ParamsTrainingBundle stored in the BlamerBundle // of the current word. const void *LTRResultIterator::GetParamsTrainingBundle() const { return (it_->word() != NULL && it_->word()->blamer_bundle != NULL) ? &(it_->word()->blamer_bundle->params_training_bundle()) : NULL; } // Returns the pointer to the string with blamer information for this word. // Assumes that the word's blamer_bundle is not NULL. const char *LTRResultIterator::GetBlamerDebug() const { return it_->word()->blamer_bundle->debug().string(); } // Returns the pointer to the string with misadaption information for this word. // Assumes that the word's blamer_bundle is not NULL. const char *LTRResultIterator::GetBlamerMisadaptionDebug() const { return it_->word()->blamer_bundle->misadaption_debug().string(); } // Returns true if a truth string was recorded for the current word. bool LTRResultIterator::HasTruthString() const { if (it_->word() == NULL) return false; // Already at the end! if (it_->word()->blamer_bundle == NULL || it_->word()->blamer_bundle->NoTruth()) { return false; // no truth information for this word } return true; } // Returns true if the given string is equivalent to the truth string for // the current word. bool LTRResultIterator::EquivalentToTruth(const char *str) const { if (!HasTruthString()) return false; ASSERT_HOST(it_->word()->uch_set != NULL); WERD_CHOICE str_wd(str, *(it_->word()->uch_set)); return it_->word()->blamer_bundle->ChoiceIsCorrect(&str_wd); } // Returns the null terminated UTF-8 encoded truth string for the current word. // Use delete [] to free after use. char* LTRResultIterator::WordTruthUTF8Text() const { if (!HasTruthString()) return NULL; STRING truth_text = it_->word()->blamer_bundle->TruthString(); int length = truth_text.length() + 1; char* result = new char[length]; strncpy(result, truth_text.string(), length); return result; } // Returns the null terminated UTF-8 encoded normalized OCR string for the // current word. Use delete [] to free after use. char* LTRResultIterator::WordNormedUTF8Text() const { if (it_->word() == NULL) return NULL; // Already at the end! STRING ocr_text; WERD_CHOICE* best_choice = it_->word()->best_choice; const UNICHARSET *unicharset = it_->word()->uch_set; ASSERT_HOST(best_choice != NULL); for (int i = 0; i < best_choice->length(); ++i) { ocr_text += unicharset->get_normed_unichar(best_choice->unichar_id(i)); } int length = ocr_text.length() + 1; char* result = new char[length]; strncpy(result, ocr_text.string(), length); return result; } // Returns a pointer to serialized choice lattice. // Fills lattice_size with the number of bytes in lattice data. const char *LTRResultIterator::WordLattice(int *lattice_size) const { if (it_->word() == NULL) return NULL; // Already at the end! if (it_->word()->blamer_bundle == NULL) return NULL; *lattice_size = it_->word()->blamer_bundle->lattice_size(); return it_->word()->blamer_bundle->lattice_data(); } // 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 LTRResultIterator::SymbolIsSuperscript() const { if (cblob_it_ == NULL && it_->word() != NULL) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_SUPERSCRIPT; return false; } // 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 LTRResultIterator::SymbolIsSubscript() const { if (cblob_it_ == NULL && it_->word() != NULL) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_SUBSCRIPT; return false; } // 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 LTRResultIterator::SymbolIsDropcap() const { if (cblob_it_ == NULL && it_->word() != NULL) return it_->word()->best_choice->BlobPosition(blob_index_) == SP_DROPCAP; return false; } ChoiceIterator::ChoiceIterator(const LTRResultIterator& result_it) { ASSERT_HOST(result_it.it_->word() != NULL); word_res_ = result_it.it_->word(); BLOB_CHOICE_LIST* choices = NULL; if (word_res_->ratings != NULL) choices = word_res_->GetBlobChoices(result_it.blob_index_); if (choices != NULL && !choices->empty()) { choice_it_ = new BLOB_CHOICE_IT(choices); choice_it_->mark_cycle_pt(); } else { choice_it_ = NULL; } } ChoiceIterator::~ChoiceIterator() { delete choice_it_; } // Moves to the next choice for the symbol and returns false if there // are none left. bool ChoiceIterator::Next() { if (choice_it_ == NULL) return false; choice_it_->forward(); return !choice_it_->cycled_list(); } // Returns the null terminated UTF-8 encoded text string for the current // choice. Do NOT use delete [] to free after use. const char* ChoiceIterator::GetUTF8Text() const { if (choice_it_ == NULL) return NULL; UNICHAR_ID id = choice_it_->data()->unichar_id(); return word_res_->uch_set->id_to_unichar_ext(id); } // Returns the confidence of the current choice. // The number should be interpreted as a percent probability. (0.0f-100.0f) float ChoiceIterator::Confidence() const { if (choice_it_ == NULL) return 0.0f; float confidence = 100 + 5 * choice_it_->data()->certainty(); if (confidence < 0.0f) confidence = 0.0f; if (confidence > 100.0f) confidence = 100.0f; return confidence; } } // namespace tesseract.
1080228-arabicocr11
ccmain/ltrresultiterator.cpp
C++
asf20
14,667
/********************************************************************** * File: tesseract_cube_combiner.h * Description: Declaration of the Tesseract & Cube results combiner Class * Author: Ahmad Abdulkader * Created: 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. * **********************************************************************/ // The TesseractCubeCombiner class provides the functionality of combining // the recognition results of Tesseract and Cube at the word level #ifndef TESSERACT_CCMAIN_TESSERACT_CUBE_COMBINER_H #define TESSERACT_CCMAIN_TESSERACT_CUBE_COMBINER_H #include <string> #include <vector> #include "pageres.h" #ifdef _WIN32 #include <windows.h> using namespace std; #endif #ifdef USE_STD_NAMESPACE using std::string; using std::vector; #endif namespace tesseract { class CubeObject; class NeuralNet; class CubeRecoContext; class WordAltList; class TesseractCubeCombiner { public: explicit TesseractCubeCombiner(CubeRecoContext *cube_cntxt); virtual ~TesseractCubeCombiner(); // There are 2 public methods for combining the results of tesseract // and cube. Both return the probability that the Tesseract result is // correct. The difference between the two interfaces is in how the // passed-in CubeObject is used. // The CubeObject parameter is used for 2 purposes: 1) to retrieve // cube's alt list, and 2) to compute cube's word cost for the // tesseract result. Both uses may modify the state of the // CubeObject (including the BeamSearch state) with a call to // RecognizeWord(). float CombineResults(WERD_RES *tess_res, CubeObject *cube_obj); // The alt_list parameter is expected to have been extracted from the // CubeObject that recognized the word to be combined. The cube_obj // parameter passed in is a separate instance to be used only by // the combiner. float CombineResults(WERD_RES *tess_res, CubeObject *cube_obj, WordAltList *alt_list); // Public method for computing the combiner features. The agreement // output parameter will be true if both answers are identical, // false otherwise. Modifies the cube_alt_list, so no assumptions // should be made about its state upon return. bool ComputeCombinerFeatures(const string &tess_res, int tess_confidence, CubeObject *cube_obj, WordAltList *cube_alt_list, vector<double> *features, bool *agreement); // Is the word valid according to Tesseract's language model bool ValidWord(const string &str); // Loads the combiner neural network from file, using cube_cntxt_ // to find path. bool LoadCombinerNet(); private: // Normalize a UTF-8 string. Converts the UTF-8 string to UTF32 and optionally // strips punc and/or normalizes case and then converts back string NormalizeString(const string &str, bool remove_punc, bool norm_case); // Compares 2 strings after optionally normalizing them and or stripping // punctuation int CompareStrings(const string &str1, const string &str2, bool ignore_punc, bool norm_case); NeuralNet *combiner_net_; // pointer to the combiner NeuralNet object CubeRecoContext *cube_cntxt_; // used for language ID and data paths }; } #endif // TESSERACT_CCMAIN_TESSERACT_CUBE_COMBINER_H
1080228-arabicocr11
ccmain/tesseract_cube_combiner.h
C++
asf20
3,967
/////////////////////////////////////////////////////////////////////// // 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" struct BlamerBundle; class C_BLOB_IT; class PAGE_RES; class PAGE_RES_IT; class WERD; struct Pix; struct Pta; 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; bool BoundingBox(PageIteratorLevel level, const int padding, int* left, int* top, int* right, int* bottom) const; /** * Returns the bounding rectangle of the object in a coordinate system of the * working image rectangle having its origin at (rect_left_, rect_top_) with * 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 the polygon outline of the current block. The returned Pta must * be ptaDestroy-ed after use. Note that the returned Pta lists the vertices * of the polygon, and the last edge is the line segment between the last * point and the first point. NULL will be returned if the iterator is * at the end of the document or layout analysis was not used. */ Pta* BlockPolygon() const; /** * Returns a binary image of the current object at the given level. * The position and size match the return from BoundingBoxInternal, and so * 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. * If you do not supply an original image, you will get a binary one. * Use pixDestroy to delete the image after use. */ Pix* GetImage(PageIteratorLevel level, int padding, Pix* original_img, int* left, int* top) const; /** * 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; // If the current WERD_RES (it_->word()) is not NULL, sets the BlamerBundle // of the current word to the given pointer (takes ownership of the pointer) // and returns true. // Can only be used when iterating on the word level. bool SetWordBlamerBundle(BlamerBundle *blamer_bundle); protected: /** * Sets up the internal data for iterating the blobs of a new word, then * 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__
1080228-arabicocr11
ccmain/pageiterator.h
C++
asf20
14,297
/****************************************************************** * File: output.cpp (Formerly output.c) * Description: Output pass * Author: Phil Cheatle * Created: Thu Aug 4 10:56:08 BST 1994 * * (C) Copyright 1994, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif #include <string.h> #include <ctype.h> #ifdef __UNIX__ #include <assert.h> #include <unistd.h> #include <errno.h> #endif #include "helpers.h" #include "tessvars.h" #include "control.h" #include "reject.h" #include "docqual.h" #include "output.h" #include "globals.h" #include "tesseractclass.h" #define EPAPER_EXT ".ep" #define PAGE_YSIZE 3508 #define CTRL_INSET '\024' //dc4=text inset #define CTRL_FONT '\016' //so=font change #define CTRL_DEFAULT '\017' //si=default font #define CTRL_SHIFT '\022' //dc2=x shift #define CTRL_TAB '\011' //tab #define CTRL_NEWLINE '\012' //newline #define CTRL_HARDLINE '\015' //cr /********************************************************************** * pixels_to_pts * * Convert an integer number of pixels to the nearest integer * number of points. **********************************************************************/ inT32 pixels_to_pts( //convert coords inT32 pixels, inT32 pix_res //resolution ) { float pts; //converted value pts = pixels * 72.0 / pix_res; return (inT32) (pts + 0.5); //round it } namespace tesseract { void Tesseract::output_pass( //Tess output pass //send to api PAGE_RES_IT &page_res_it, const TBOX *target_word_box) { BLOCK_RES *block_of_last_word; BOOL8 force_eol; //During output BLOCK *nextblock; //block of next word WERD *nextword; //next word page_res_it.restart_page (); block_of_last_word = NULL; while (page_res_it.word () != NULL) { check_debug_pt (page_res_it.word (), 120); if (target_word_box) { TBOX current_word_box=page_res_it.word ()->word->bounding_box(); FCOORD center_pt((current_word_box.right()+current_word_box.left())/2,(current_word_box.bottom()+current_word_box.top())/2); if (!target_word_box->contains(center_pt)) { page_res_it.forward (); continue; } } if (tessedit_write_block_separators && block_of_last_word != page_res_it.block ()) { block_of_last_word = page_res_it.block (); } force_eol = (tessedit_write_block_separators && (page_res_it.block () != page_res_it.next_block ())) || (page_res_it.next_word () == NULL); if (page_res_it.next_word () != NULL) nextword = page_res_it.next_word ()->word; else nextword = NULL; if (page_res_it.next_block () != NULL) nextblock = page_res_it.next_block ()->block; else nextblock = NULL; //regardless of tilde crunching write_results(page_res_it, determine_newline_type(page_res_it.word()->word, page_res_it.block()->block, nextword, nextblock), force_eol); page_res_it.forward(); } } /************************************************************************* * write_results() * * All recognition and rejection has now been done. Generate the following: * .txt file - giving the final best choices with NO highlighting * .raw file - giving the tesseract top choice output for each word * .map file - showing how the .txt file has been rejected in the .ep file * epchoice list - a list of one element per word, containing the text for the * epaper. Reject strings are inserted. * inset list - a list of bounding boxes of reject insets - indexed by the * reject strings in the epchoice text. *************************************************************************/ void Tesseract::write_results(PAGE_RES_IT &page_res_it, char newline_type, // type of newline BOOL8 force_eol) { // override tilde crunch? WERD_RES *word = page_res_it.word(); const UNICHARSET &uchset = *word->uch_set; int i; BOOL8 need_reject = FALSE; UNICHAR_ID space = uchset.unichar_to_id(" "); if ((word->unlv_crunch_mode != CR_NONE || word->best_choice->length() == 0) && !tessedit_zero_kelvin_rejection && !tessedit_word_for_word) { if ((word->unlv_crunch_mode != CR_DELETE) && (!stats_.tilde_crunch_written || ((word->unlv_crunch_mode == CR_KEEP_SPACE) && (word->word->space () > 0) && !word->word->flag (W_FUZZY_NON) && !word->word->flag (W_FUZZY_SP)))) { if (!word->word->flag (W_BOL) && (word->word->space () > 0) && !word->word->flag (W_FUZZY_NON) && !word->word->flag (W_FUZZY_SP)) { stats_.last_char_was_tilde = false; } need_reject = TRUE; } if ((need_reject && !stats_.last_char_was_tilde) || (force_eol && stats_.write_results_empty_block)) { /* Write a reject char - mark as rejected unless zero_rejection mode */ stats_.last_char_was_tilde = TRUE; stats_.tilde_crunch_written = true; stats_.last_char_was_newline = false; stats_.write_results_empty_block = false; } if ((word->word->flag (W_EOL) && !stats_.last_char_was_newline) || force_eol) { stats_.tilde_crunch_written = false; stats_.last_char_was_newline = true; stats_.last_char_was_tilde = false; } if (force_eol) stats_.write_results_empty_block = true; return; } /* NORMAL PROCESSING of non tilde crunched words */ stats_.tilde_crunch_written = false; if (newline_type) stats_.last_char_was_newline = true; else stats_.last_char_was_newline = false; stats_.write_results_empty_block = force_eol; // about to write a real word if (unlv_tilde_crunching && stats_.last_char_was_tilde && (word->word->space() == 0) && !(word->word->flag(W_REP_CHAR) && tessedit_write_rep_codes) && (word->best_choice->unichar_id(0) == space)) { /* Prevent adjacent tilde across words - we know that adjacent tildes within words have been removed */ word->MergeAdjacentBlobs(0); } if (newline_type || (word->word->flag (W_REP_CHAR) && tessedit_write_rep_codes)) stats_.last_char_was_tilde = false; else { if (word->reject_map.length () > 0) { if (word->best_choice->unichar_id(word->reject_map.length() - 1) == space) stats_.last_char_was_tilde = true; else stats_.last_char_was_tilde = false; } else if (word->word->space () > 0) stats_.last_char_was_tilde = false; /* else it is unchanged as there are no output chars */ } ASSERT_HOST (word->best_choice->length() == word->reject_map.length()); set_unlv_suspects(word); check_debug_pt (word, 120); if (tessedit_rejection_debug) { tprintf ("Dict word: \"%s\": %d\n", word->best_choice->debug_string().string(), dict_word(*(word->best_choice))); } if (!word->word->flag(W_REP_CHAR) || !tessedit_write_rep_codes) { if (tessedit_zero_rejection) { /* OVERRIDE ALL REJECTION MECHANISMS - ONLY REJECT TESS FAILURES */ for (i = 0; i < word->best_choice->length(); ++i) { if (word->reject_map[i].rejected()) word->reject_map[i].setrej_minimal_rej_accept(); } } if (tessedit_minimal_rejection) { /* OVERRIDE ALL REJECTION MECHANISMS - ONLY REJECT TESS FAILURES */ for (i = 0; i < word->best_choice->length(); ++i) { if ((word->best_choice->unichar_id(i) != space) && word->reject_map[i].rejected()) word->reject_map[i].setrej_minimal_rej_accept(); } } } } } // namespace tesseract /********************************************************************** * determine_newline_type * * Find whether we have a wrapping or hard newline. * Return FALSE if not at end of line. **********************************************************************/ char determine_newline_type( //test line ends WERD *word, //word to do BLOCK *block, //current block WERD *next_word, //next word BLOCK *next_block //block of next word ) { inT16 end_gap; //to right edge inT16 width; //of next word TBOX word_box; //bounding TBOX next_box; //next word TBOX block_box; //block bounding if (!word->flag (W_EOL)) return FALSE; //not end of line if (next_word == NULL || next_block == NULL || block != next_block) return CTRL_NEWLINE; if (next_word->space () > 0) return CTRL_HARDLINE; //it is tabbed word_box = word->bounding_box (); next_box = next_word->bounding_box (); block_box = block->bounding_box (); //gap to eol end_gap = block_box.right () - word_box.right (); end_gap -= (inT32) block->space (); width = next_box.right () - next_box.left (); // tprintf("end_gap=%d-%d=%d, width=%d-%d=%d, nl=%d\n", // block_box.right(),word_box.right(),end_gap, // next_box.right(),next_box.left(),width, // end_gap>width ? CTRL_HARDLINE : CTRL_NEWLINE); return end_gap > width ? CTRL_HARDLINE : CTRL_NEWLINE; } /************************************************************************* * get_rep_char() * Return the first accepted character from the repetition string. This is the * character which is repeated - as determined earlier by fix_rep_char() *************************************************************************/ namespace tesseract { UNICHAR_ID Tesseract::get_rep_char(WERD_RES *word) { // what char is repeated? int i; for (i = 0; ((i < word->reject_map.length()) && (word->reject_map[i].rejected())); ++i); if (i < word->reject_map.length()) { return word->best_choice->unichar_id(i); } else { return word->uch_set->unichar_to_id(unrecognised_char.string()); } } /************************************************************************* * SUSPECT LEVELS * * 0 - dont reject ANYTHING * 1,2 - partial rejection * 3 - BEST * * NOTE: to reject JUST tess failures in the .map file set suspect_level 3 and * tessedit_minimal_rejection. *************************************************************************/ void Tesseract::set_unlv_suspects(WERD_RES *word_res) { int len = word_res->reject_map.length(); const WERD_CHOICE &word = *(word_res->best_choice); const UNICHARSET &uchset = *word.unicharset(); int i; float rating_per_ch; if (suspect_level == 0) { for (i = 0; i < len; i++) { if (word_res->reject_map[i].rejected()) word_res->reject_map[i].setrej_minimal_rej_accept(); } return; } if (suspect_level >= 3) return; //Use defaults /* NOW FOR LEVELS 1 and 2 Find some stuff to unreject*/ if (safe_dict_word(word_res) && (count_alphas(word) > suspect_short_words)) { /* Unreject alphas in dictionary words */ for (i = 0; i < len; ++i) { if (word_res->reject_map[i].rejected() && uchset.get_isalpha(word.unichar_id(i))) word_res->reject_map[i].setrej_minimal_rej_accept(); } } rating_per_ch = word.rating() / word_res->reject_map.length(); if (rating_per_ch >= suspect_rating_per_ch) return; //Dont touch bad ratings if ((word_res->tess_accepted) || (rating_per_ch < suspect_accept_rating)) { /* Unreject any Tess Acceptable word - but NOT tess reject chs*/ for (i = 0; i < len; ++i) { if (word_res->reject_map[i].rejected() && (!uchset.eq(word.unichar_id(i), " "))) word_res->reject_map[i].setrej_minimal_rej_accept(); } } for (i = 0; i < len; i++) { if (word_res->reject_map[i].rejected()) { if (word_res->reject_map[i].flag(R_DOC_REJ)) word_res->reject_map[i].setrej_minimal_rej_accept(); if (word_res->reject_map[i].flag(R_BLOCK_REJ)) word_res->reject_map[i].setrej_minimal_rej_accept(); if (word_res->reject_map[i].flag(R_ROW_REJ)) word_res->reject_map[i].setrej_minimal_rej_accept(); } } if (suspect_level == 2) return; if (!suspect_constrain_1Il || (word_res->reject_map.length() <= suspect_short_words)) { for (i = 0; i < len; i++) { if (word_res->reject_map[i].rejected()) { if ((word_res->reject_map[i].flag(R_1IL_CONFLICT) || word_res->reject_map[i].flag(R_POSTNN_1IL))) word_res->reject_map[i].setrej_minimal_rej_accept(); if (!suspect_constrain_1Il && word_res->reject_map[i].flag(R_MM_REJECT)) word_res->reject_map[i].setrej_minimal_rej_accept(); } } } if (acceptable_word_string(*word_res->uch_set, word.unichar_string().string(), word.unichar_lengths().string()) != AC_UNACCEPTABLE || acceptable_number_string(word.unichar_string().string(), word.unichar_lengths().string())) { if (word_res->reject_map.length() > suspect_short_words) { for (i = 0; i < len; i++) { if (word_res->reject_map[i].rejected() && (!word_res->reject_map[i].perm_rejected() || word_res->reject_map[i].flag (R_1IL_CONFLICT) || word_res->reject_map[i].flag (R_POSTNN_1IL) || word_res->reject_map[i].flag (R_MM_REJECT))) { word_res->reject_map[i].setrej_minimal_rej_accept(); } } } } } inT16 Tesseract::count_alphas(const WERD_CHOICE &word) { int count = 0; for (int i = 0; i < word.length(); ++i) { if (word.unicharset()->get_isalpha(word.unichar_id(i))) count++; } return count; } inT16 Tesseract::count_alphanums(const WERD_CHOICE &word) { int count = 0; for (int i = 0; i < word.length(); ++i) { if (word.unicharset()->get_isalpha(word.unichar_id(i)) || word.unicharset()->get_isdigit(word.unichar_id(i))) count++; } return count; } BOOL8 Tesseract::acceptable_number_string(const char *s, const char *lengths) { BOOL8 prev_digit = FALSE; if (*lengths == 1 && *s == '(') s++; if (*lengths == 1 && ((*s == '$') || (*s == '.') || (*s == '+') || (*s == '-'))) s++; for (; *s != '\0'; s += *(lengths++)) { if (unicharset.get_isdigit(s, *lengths)) prev_digit = TRUE; else if (prev_digit && (*lengths == 1 && ((*s == '.') || (*s == ',') || (*s == '-')))) prev_digit = FALSE; else if (prev_digit && *lengths == 1 && (*(s + *lengths) == '\0') && ((*s == '%') || (*s == ')'))) return TRUE; else if (prev_digit && *lengths == 1 && (*s == '%') && (*(lengths + 1) == 1 && *(s + *lengths) == ')') && (*(s + *lengths + *(lengths + 1)) == '\0')) return TRUE; else return FALSE; } return TRUE; } } // namespace tesseract
1080228-arabicocr11
ccmain/output.cpp
C++
asf20
16,120
/////////////////////////////////////////////////////////////////////// // File: pgedit.h // Description: Page structure file editor // Author: Joern Wanke // Created: Wed Jul 18 10:05:01 PDT 2007 // // (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 PGEDIT_H #define PGEDIT_H #include "ocrblock.h" #include "ocrrow.h" #include "werd.h" #include "rect.h" #include "params.h" #include "tesseractclass.h" class ScrollView; class SVMenuNode; struct SVEvent; // A small event handler class to process incoming events to // this window. class PGEventHandler : public SVEventHandler { public: PGEventHandler(tesseract::Tesseract* tess) : tess_(tess) { } void Notify(const SVEvent* sve); private: tesseract::Tesseract* tess_; }; extern BLOCK_LIST *current_block_list; extern STRING_VAR_H (editor_image_win_name, "EditorImage", "Editor image window name"); extern INT_VAR_H (editor_image_xpos, 590, "Editor image X Pos"); extern INT_VAR_H (editor_image_ypos, 10, "Editor image Y Pos"); extern INT_VAR_H (editor_image_height, 680, "Editor image height"); extern INT_VAR_H (editor_image_width, 655, "Editor image width"); extern INT_VAR_H (editor_image_word_bb_color, BLUE, "Word bounding box colour"); extern INT_VAR_H (editor_image_blob_bb_color, YELLOW, "Blob bounding box colour"); extern INT_VAR_H (editor_image_text_color, WHITE, "Correct text colour"); extern STRING_VAR_H (editor_dbwin_name, "EditorDBWin", "Editor debug window name"); extern INT_VAR_H (editor_dbwin_xpos, 50, "Editor debug window X Pos"); extern INT_VAR_H (editor_dbwin_ypos, 500, "Editor debug window Y Pos"); extern INT_VAR_H (editor_dbwin_height, 24, "Editor debug window height"); extern INT_VAR_H (editor_dbwin_width, 80, "Editor debug window width"); extern STRING_VAR_H (editor_word_name, "BlnWords", "BL normalised word window"); extern INT_VAR_H (editor_word_xpos, 60, "Word window X Pos"); extern INT_VAR_H (editor_word_ypos, 510, "Word window Y Pos"); extern INT_VAR_H (editor_word_height, 240, "Word window height"); extern INT_VAR_H (editor_word_width, 655, "Word window width"); extern double_VAR_H (editor_smd_scale_factor, 1.0, "Scaling for smd image"); ScrollView* bln_word_window_handle(); //return handle void build_image_window(int width, int height); void display_bln_lines(ScrollView window, ScrollView::Color colour, float scale_factor, float y_offset, float minx, float maxx); //function to call void pgeditor_msg( //message display const char *msg); void pgeditor_show_point( //display coords SVEvent *event); //put bln word in box void show_point(PAGE_RES* page_res, float x, float y); #endif
1080228-arabicocr11
ccmain/pgedit.h
C++
asf20
3,544
/********************************************************************** * File: tessvars.h (Formerly tessvars.h) * Description: Variables and other globals for tessedit. * Author: Ray Smith * Created: Mon Apr 13 13:13:23 BST 1992 * * (C) Copyright 1992, 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 TESSVARS_H #define TESSVARS_H #include <stdio.h> extern FILE *debug_fp; // write debug stuff here #endif
1080228-arabicocr11
ccmain/tessvars.h
C
asf20
1,061
/********************************************************************** * File: tessedit.cpp (Formerly tessedit.c) * Description: Main program for merge of tess and editor. * Author: Ray Smith * Created: Tue Jan 07 15:21:46 GMT 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ #include "stderr.h" #include "basedir.h" #include "tessvars.h" #include "control.h" #include "reject.h" #include "pageres.h" #include "nwmain.h" #include "pgedit.h" #include "tprintf.h" #include "tessedit.h" #include "stopper.h" #include "intmatcher.h" #include "chop.h" #include "efio.h" #include "danerror.h" #include "globals.h" #include "tesseractclass.h" #include "params.h" #define VARDIR "configs/" /*variables files */ //config under api #define API_CONFIG "configs/api_config" ETEXT_DESC *global_monitor = NULL; // progress monitor namespace tesseract { // Read a "config" file containing a set of variable, value pairs. // Searches the standard places: tessdata/configs, tessdata/tessconfigs // and also accepts a relative or absolute path name. void Tesseract::read_config_file(const char *filename, SetParamConstraint constraint) { STRING path = datadir; path += "configs/"; path += filename; FILE* fp; if ((fp = fopen(path.string(), "rb")) != NULL) { fclose(fp); } else { path = datadir; path += "tessconfigs/"; path += filename; if ((fp = fopen(path.string(), "rb")) != NULL) { fclose(fp); } else { path = filename; } } ParamUtils::ReadParamsFile(path.string(), constraint, this->params()); } // Returns false if a unicharset file for the specified language was not found // or was invalid. // This function initializes TessdataManager. After TessdataManager is // no longer needed, TessdataManager::End() should be called. // // This function sets tessedit_oem_mode to the given OcrEngineMode oem, unless // it is OEM_DEFAULT, in which case the value of the variable will be obtained // from the language-specific config file (stored in [lang].traineddata), from // the config files specified on the command line or left as the default // OEM_TESSERACT_ONLY if none of the configs specify this variable. bool Tesseract::init_tesseract_lang_data( const char *arg0, const char *textbase, const char *language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector<STRING> *vars_vec, const GenericVector<STRING> *vars_values, bool set_only_non_debug_params) { // Set the basename, compute the data directory. main_setup(arg0, textbase); // Set the language data path prefix lang = language != NULL ? language : "eng"; language_data_path_prefix = datadir; language_data_path_prefix += lang; language_data_path_prefix += "."; // Initialize TessdataManager. STRING tessdata_path = language_data_path_prefix + kTrainedDataSuffix; if (!tessdata_manager.Init(tessdata_path.string(), tessdata_manager_debug_level)) { return false; } // If a language specific config file (lang.config) exists, load it in. if (tessdata_manager.SeekToStart(TESSDATA_LANG_CONFIG)) { ParamUtils::ReadParamsFromFp( tessdata_manager.GetDataFilePtr(), tessdata_manager.GetEndOffset(TESSDATA_LANG_CONFIG), SET_PARAM_CONSTRAINT_NONE, this->params()); if (tessdata_manager_debug_level) { tprintf("Loaded language config file\n"); } } SetParamConstraint set_params_constraint = set_only_non_debug_params ? SET_PARAM_CONSTRAINT_NON_DEBUG_ONLY : SET_PARAM_CONSTRAINT_NONE; // Load tesseract variables from config files. This is done after loading // language-specific variables from [lang].traineddata file, so that custom // config files can override values in [lang].traineddata file. for (int i = 0; i < configs_size; ++i) { read_config_file(configs[i], set_params_constraint); } // Set params specified in vars_vec (done after setting params from config // files, so that params in vars_vec can override those from files). if (vars_vec != NULL && vars_values != NULL) { for (int i = 0; i < vars_vec->size(); ++i) { if (!ParamUtils::SetParam((*vars_vec)[i].string(), (*vars_values)[i].string(), set_params_constraint, this->params())) { tprintf("Error setting param %s\n", (*vars_vec)[i].string()); exit(1); } } } if (((STRING &)tessedit_write_params_to_file).length() > 0) { FILE *params_file = fopen(tessedit_write_params_to_file.string(), "wb"); if (params_file != NULL) { ParamUtils::PrintParams(params_file, this->params()); fclose(params_file); if (tessdata_manager_debug_level > 0) { tprintf("Wrote parameters to %s\n", tessedit_write_params_to_file.string()); } } else { tprintf("Failed to open %s for writing params.\n", tessedit_write_params_to_file.string()); } } // Determine which ocr engine(s) should be loaded and used for recognition. if (oem != OEM_DEFAULT) tessedit_ocr_engine_mode.set_value(oem); if (tessdata_manager_debug_level) { tprintf("Loading Tesseract/Cube with tessedit_ocr_engine_mode %d\n", static_cast<int>(tessedit_ocr_engine_mode)); } // If we are only loading the config file (and so not planning on doing any // recognition) then there's nothing else do here. if (tessedit_init_config_only) { if (tessdata_manager_debug_level) { tprintf("Returning after loading config file\n"); } return true; } // Load the unicharset if (!tessdata_manager.SeekToStart(TESSDATA_UNICHARSET) || !unicharset.load_from_file(tessdata_manager.GetDataFilePtr())) { return false; } if (unicharset.size() > MAX_NUM_CLASSES) { tprintf("Error: Size of unicharset is greater than MAX_NUM_CLASSES\n"); return false; } if (tessdata_manager_debug_level) tprintf("Loaded unicharset\n"); right_to_left_ = unicharset.major_right_to_left(); // Setup initial unichar ambigs table and read universal ambigs. UNICHARSET encoder_unicharset; encoder_unicharset.CopyFrom(unicharset); unichar_ambigs.InitUnicharAmbigs(unicharset, use_ambigs_for_adaption); unichar_ambigs.LoadUniversal(encoder_unicharset, &unicharset); if (!tessedit_ambigs_training && tessdata_manager.SeekToStart(TESSDATA_AMBIGS)) { TFile ambigs_file; ambigs_file.Open(tessdata_manager.GetDataFilePtr(), tessdata_manager.GetEndOffset(TESSDATA_AMBIGS) + 1); unichar_ambigs.LoadUnicharAmbigs( encoder_unicharset, &ambigs_file, ambigs_debug_level, use_ambigs_for_adaption, &unicharset); if (tessdata_manager_debug_level) tprintf("Loaded ambigs\n"); } // Load Cube objects if necessary. if (tessedit_ocr_engine_mode == OEM_CUBE_ONLY) { ASSERT_HOST(init_cube_objects(false, &tessdata_manager)); if (tessdata_manager_debug_level) tprintf("Loaded Cube w/out combiner\n"); } else if (tessedit_ocr_engine_mode == OEM_TESSERACT_CUBE_COMBINED) { ASSERT_HOST(init_cube_objects(true, &tessdata_manager)); if (tessdata_manager_debug_level) tprintf("Loaded Cube with combiner\n"); } // Init ParamsModel. // Load pass1 and pass2 weights (for now these two sets are the same, but in // the future separate sets of weights can be generated). for (int p = ParamsModel::PTRAIN_PASS1; p < ParamsModel::PTRAIN_NUM_PASSES; ++p) { language_model_->getParamsModel().SetPass( static_cast<ParamsModel::PassEnum>(p)); if (tessdata_manager.SeekToStart(TESSDATA_PARAMS_MODEL)) { if (!language_model_->getParamsModel().LoadFromFp( lang.string(), tessdata_manager.GetDataFilePtr(), tessdata_manager.GetEndOffset(TESSDATA_PARAMS_MODEL))) { return false; } } } if (tessdata_manager_debug_level) language_model_->getParamsModel().Print(); return true; } // Helper returns true if the given string is in the vector of strings. static bool IsStrInList(const STRING& str, const GenericVector<STRING>& str_list) { for (int i = 0; i < str_list.size(); ++i) { if (str_list[i] == str) return true; } return false; } // Parse a string of the form [~]<lang>[+[~]<lang>]*. // Langs with no prefix get appended to to_load, provided they // are not in there already. // Langs with ~ prefix get appended to not_to_load, provided they are not in // there already. void Tesseract::ParseLanguageString(const char* lang_str, GenericVector<STRING>* to_load, GenericVector<STRING>* not_to_load) { STRING remains(lang_str); while (remains.length() > 0) { // Find the start of the lang code and which vector to add to. const char* start = remains.string(); while (*start == '+') ++start; GenericVector<STRING>* target = to_load; if (*start == '~') { target = not_to_load; ++start; } // Find the index of the end of the lang code in string start. int end = strlen(start); const char* plus = strchr(start, '+'); if (plus != NULL && plus - start < end) end = plus - start; STRING lang_code(start); lang_code.truncate_at(end); STRING next(start + end); remains = next; // Check whether lang_code is already in the target vector and add. if (!IsStrInList(lang_code, *target)) { if (tessdata_manager_debug_level) tprintf("Adding language '%s' to list\n", lang_code.string()); target->push_back(lang_code); } } } // Initialize for potentially a set of languages defined by the language // string and recursively any additional languages required by any language // traineddata file (via tessedit_load_sublangs in its config) that is loaded. // See init_tesseract_internal for args. int Tesseract::init_tesseract( const char *arg0, const char *textbase, const char *language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector<STRING> *vars_vec, const GenericVector<STRING> *vars_values, bool set_only_non_debug_params) { GenericVector<STRING> langs_to_load; GenericVector<STRING> langs_not_to_load; ParseLanguageString(language, &langs_to_load, &langs_not_to_load); sub_langs_.delete_data_pointers(); sub_langs_.clear(); // Find the first loadable lang and load into this. // Add any languages that this language requires bool loaded_primary = false; // Load the rest into sub_langs_. for (int lang_index = 0; lang_index < langs_to_load.size(); ++lang_index) { if (!IsStrInList(langs_to_load[lang_index], langs_not_to_load)) { const char *lang_str = langs_to_load[lang_index].string(); Tesseract *tess_to_init; if (!loaded_primary) { tess_to_init = this; } else { tess_to_init = new Tesseract; } int result = tess_to_init->init_tesseract_internal( arg0, textbase, lang_str, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params); if (!loaded_primary) { if (result < 0) { tprintf("Failed loading language '%s'\n", lang_str); } else { if (tessdata_manager_debug_level) tprintf("Loaded language '%s' as main language\n", lang_str); ParseLanguageString(tess_to_init->tessedit_load_sublangs.string(), &langs_to_load, &langs_not_to_load); loaded_primary = true; } } else { if (result < 0) { tprintf("Failed loading language '%s'\n", lang_str); delete tess_to_init; } else { if (tessdata_manager_debug_level) tprintf("Loaded language '%s' as secondary language\n", lang_str); sub_langs_.push_back(tess_to_init); // Add any languages that this language requires ParseLanguageString(tess_to_init->tessedit_load_sublangs.string(), &langs_to_load, &langs_not_to_load); } } } } if (!loaded_primary) { tprintf("Tesseract couldn't load any languages!\n"); return -1; // Couldn't load any language! } if (!sub_langs_.empty()) { // In multilingual mode word ratings have to be directly comparable, // so use the same language model weights for all languages: // use the primary language's params model if // tessedit_use_primary_params_model is set, // otherwise use default language model weights. if (tessedit_use_primary_params_model) { for (int s = 0; s < sub_langs_.size(); ++s) { sub_langs_[s]->language_model_->getParamsModel().Copy( this->language_model_->getParamsModel()); } tprintf("Using params model of the primary language\n"); if (tessdata_manager_debug_level) { this->language_model_->getParamsModel().Print(); } } else { this->language_model_->getParamsModel().Clear(); for (int s = 0; s < sub_langs_.size(); ++s) { sub_langs_[s]->language_model_->getParamsModel().Clear(); } if (tessdata_manager_debug_level) tprintf("Using default language params\n"); } } SetupUniversalFontIds(); return 0; } // Common initialization for a single language. // arg0 is the datapath for the tessdata directory, which could be the // path of the tessdata directory with no trailing /, or (if tessdata // lives in the same directory as the executable, the path of the executable, // hence the name arg0. // textbase is an optional output file basename (used only for training) // language is the language code to load. // oem controls which engine(s) will operate on the image // configs (argv) is an array of config filenames to load variables from. // May be NULL. // configs_size (argc) is the number of elements in configs. // vars_vec is an optional vector of variables to set. // vars_values is an optional corresponding vector of values for the variables // in vars_vec. // If set_only_init_params is true, then only the initialization variables // will be set. int Tesseract::init_tesseract_internal( const char *arg0, const char *textbase, const char *language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector<STRING> *vars_vec, const GenericVector<STRING> *vars_values, bool set_only_non_debug_params) { if (!init_tesseract_lang_data(arg0, textbase, language, oem, configs, configs_size, vars_vec, vars_values, set_only_non_debug_params)) { return -1; } if (tessedit_init_config_only) { tessdata_manager.End(); return 0; } // If only Cube will be used, skip loading Tesseract classifier's // pre-trained templates. bool init_tesseract_classifier = (tessedit_ocr_engine_mode == OEM_TESSERACT_ONLY || tessedit_ocr_engine_mode == OEM_TESSERACT_CUBE_COMBINED); // If only Cube will be used and if it has its own Unicharset, // skip initializing permuter and loading Tesseract Dawgs. bool init_dict = !(tessedit_ocr_engine_mode == OEM_CUBE_ONLY && tessdata_manager.SeekToStart(TESSDATA_CUBE_UNICHARSET)); program_editup(textbase, init_tesseract_classifier, init_dict); tessdata_manager.End(); return 0; //Normal exit } // Helper builds the all_fonts table by adding new fonts from new_fonts. static void CollectFonts(const UnicityTable<FontInfo>& new_fonts, UnicityTable<FontInfo>* all_fonts) { for (int i = 0; i < new_fonts.size(); ++i) { // UnicityTable uniques as we go. all_fonts->push_back(new_fonts.get(i)); } } // Helper assigns an id to lang_fonts using the index in all_fonts table. static void AssignIds(const UnicityTable<FontInfo>& all_fonts, UnicityTable<FontInfo>* lang_fonts) { for (int i = 0; i < lang_fonts->size(); ++i) { int index = all_fonts.get_id(lang_fonts->get(i)); lang_fonts->get_mutable(i)->universal_id = index; } } // Set the universal_id member of each font to be unique among all // instances of the same font loaded. void Tesseract::SetupUniversalFontIds() { // Note that we can get away with bitwise copying FontInfo in // all_fonts, as it is a temporary structure and we avoid setting the // delete callback. UnicityTable<FontInfo> all_fonts; all_fonts.set_compare_callback(NewPermanentTessCallback(CompareFontInfo)); // Create the universal ID table. CollectFonts(get_fontinfo_table(), &all_fonts); for (int i = 0; i < sub_langs_.size(); ++i) { CollectFonts(sub_langs_[i]->get_fontinfo_table(), &all_fonts); } // Assign ids from the table to each font table. AssignIds(all_fonts, &get_fontinfo_table()); for (int i = 0; i < sub_langs_.size(); ++i) { AssignIds(all_fonts, &sub_langs_[i]->get_fontinfo_table()); } font_table_size_ = all_fonts.size(); } // init the LM component int Tesseract::init_tesseract_lm(const char *arg0, const char *textbase, const char *language) { if (!init_tesseract_lang_data(arg0, textbase, language, OEM_TESSERACT_ONLY, NULL, 0, NULL, NULL, false)) return -1; getDict().Load(Dict::GlobalDawgCache()); tessdata_manager.End(); return 0; } void Tesseract::end_tesseract() { end_recog(); } /* Define command type identifiers */ enum CMD_EVENTS { ACTION_1_CMD_EVENT, RECOG_WERDS, RECOG_PSEUDO, ACTION_2_CMD_EVENT }; } // namespace tesseract
1080228-arabicocr11
ccmain/tessedit.cpp
C++
asf20
18,381
/********************************************************************** * File: pgedit.cpp (Formerly pgeditor.c) * Description: Page structure file editor * Author: Phil Cheatle * Created: Thu Oct 10 16:25:24 BST 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "pgedit.h" #include <ctype.h> #include <math.h> #include "blread.h" #include "control.h" #include "paramsd.h" #include "pageres.h" #include "tordmain.h" #include "scrollview.h" #include "svmnode.h" #include "statistc.h" #include "tesseractclass.h" #include "werdit.h" #ifndef GRAPHICS_DISABLED #define ASC_HEIGHT (2 * kBlnBaselineOffset + kBlnXHeight) #define X_HEIGHT (kBlnBaselineOffset + kBlnXHeight) #define BL_HEIGHT kBlnBaselineOffset #define DESC_HEIGHT 0 #define MAXSPACING 128 /*max expected spacing in pix */ const ERRCODE EMPTYBLOCKLIST = "No blocks to edit"; enum CMD_EVENTS { NULL_CMD_EVENT, CHANGE_DISP_CMD_EVENT, DUMP_WERD_CMD_EVENT, SHOW_POINT_CMD_EVENT, SHOW_BLN_WERD_CMD_EVENT, DEBUG_WERD_CMD_EVENT, BLAMER_CMD_EVENT, BOUNDING_BOX_CMD_EVENT, CORRECT_TEXT_CMD_EVENT, POLYGONAL_CMD_EVENT, BL_NORM_CMD_EVENT, BITMAP_CMD_EVENT, IMAGE_CMD_EVENT, BLOCKS_CMD_EVENT, BASELINES_CMD_EVENT, UNIFORM_DISP_CMD_EVENT, REFRESH_CMD_EVENT, QUIT_CMD_EVENT, RECOG_WERDS, RECOG_PSEUDO, SHOW_BLOB_FEATURES, SHOW_SUBSCRIPT_CMD_EVENT, SHOW_SUPERSCRIPT_CMD_EVENT, SHOW_ITALIC_CMD_EVENT, SHOW_BOLD_CMD_EVENT, SHOW_UNDERLINE_CMD_EVENT, SHOW_FIXEDPITCH_CMD_EVENT, SHOW_SERIF_CMD_EVENT, SHOW_SMALLCAPS_CMD_EVENT, SHOW_DROPCAPS_CMD_EVENT, }; enum ColorationMode { CM_RAINBOW, CM_SUBSCRIPT, CM_SUPERSCRIPT, CM_ITALIC, CM_BOLD, CM_UNDERLINE, CM_FIXEDPITCH, CM_SERIF, CM_SMALLCAPS, CM_DROPCAPS }; /* * * Some global data * */ ScrollView* image_win; ParamsEditor* pe; bool stillRunning = false; #ifdef __UNIX__ FILE *debug_window = NULL; // opened on demand #endif ScrollView* bln_word_window = NULL; // baseline norm words CMD_EVENTS mode = CHANGE_DISP_CMD_EVENT; // selected words op bool recog_done = false; // recog_all_words was called // These variables should remain global, since they are only used for the // debug mode (in which only a single Tesseract thread/instance will be exist). BITS16 word_display_mode; static ColorationMode color_mode = CM_RAINBOW; BOOL8 display_image = FALSE; BOOL8 display_blocks = FALSE; BOOL8 display_baselines = FALSE; PAGE_RES *current_page_res = NULL; STRING_VAR(editor_image_win_name, "EditorImage", "Editor image window name"); INT_VAR(editor_image_xpos, 590, "Editor image X Pos"); INT_VAR(editor_image_ypos, 10, "Editor image Y Pos"); INT_VAR(editor_image_menuheight, 50, "Add to image height for menu bar"); INT_VAR(editor_image_word_bb_color, ScrollView::BLUE, "Word bounding box colour"); INT_VAR(editor_image_blob_bb_color, ScrollView::YELLOW, "Blob bounding box colour"); INT_VAR(editor_image_text_color, ScrollView::WHITE, "Correct text colour"); STRING_VAR(editor_dbwin_name, "EditorDBWin", "Editor debug window name"); INT_VAR(editor_dbwin_xpos, 50, "Editor debug window X Pos"); INT_VAR(editor_dbwin_ypos, 500, "Editor debug window Y Pos"); INT_VAR(editor_dbwin_height, 24, "Editor debug window height"); INT_VAR(editor_dbwin_width, 80, "Editor debug window width"); STRING_VAR(editor_word_name, "BlnWords", "BL normalized word window"); INT_VAR(editor_word_xpos, 60, "Word window X Pos"); INT_VAR(editor_word_ypos, 510, "Word window Y Pos"); INT_VAR(editor_word_height, 240, "Word window height"); INT_VAR(editor_word_width, 655, "Word window width"); STRING_VAR(editor_debug_config_file, "", "Config file to apply to single words"); class BlnEventHandler : public SVEventHandler { public: void Notify(const SVEvent* sv_event) { if (sv_event->type == SVET_DESTROY) bln_word_window = NULL; else if (sv_event->type == SVET_CLICK) show_point(current_page_res, sv_event->x, sv_event->y); } }; /** * bln_word_window_handle() * * @return a WINDOW for the word window, creating it if necessary */ ScrollView* bln_word_window_handle() { // return handle // not opened yet if (bln_word_window == NULL) { pgeditor_msg("Creating BLN word window..."); bln_word_window = new ScrollView(editor_word_name.string(), editor_word_xpos, editor_word_ypos, editor_word_width, editor_word_height, 4000, 4000, true); BlnEventHandler* a = new BlnEventHandler(); bln_word_window->AddEventHandler(a); pgeditor_msg("Creating BLN word window...Done"); } return bln_word_window; } /** * build_image_window() * * Destroy the existing image window if there is one. Work out how big the * new window needs to be. Create it and re-display. */ void build_image_window(int width, int height) { if (image_win != NULL) { delete image_win; } image_win = new ScrollView(editor_image_win_name.string(), editor_image_xpos, editor_image_ypos, width + 1, height + editor_image_menuheight + 1, width, height, true); } /** * display_bln_lines() * * Display normalized baseline, x-height, ascender limit and descender limit */ void display_bln_lines(ScrollView* window, ScrollView::Color colour, float scale_factor, float y_offset, float minx, float maxx) { window->Pen(colour); window->Line(minx, y_offset + scale_factor * DESC_HEIGHT, maxx, y_offset + scale_factor * DESC_HEIGHT); window->Line(minx, y_offset + scale_factor * BL_HEIGHT, maxx, y_offset + scale_factor * BL_HEIGHT); window->Line(minx, y_offset + scale_factor * X_HEIGHT, maxx, y_offset + scale_factor * X_HEIGHT); window->Line(minx, y_offset + scale_factor * ASC_HEIGHT, maxx, y_offset + scale_factor * ASC_HEIGHT); } /** * notify() * * Event handler that processes incoming events, either forwarding * them to process_cmd_win_event or process_image_event. * */ void PGEventHandler::Notify(const SVEvent* event) { char myval = '0'; if (event->type == SVET_POPUP) { pe->Notify(event); } // These are handled by ParamsEditor else if (event->type == SVET_EXIT) { stillRunning = false; } else if (event->type == SVET_MENU) { if (strcmp(event->parameter, "true") == 0) { myval = 'T'; } else if (strcmp(event->parameter, "false") == 0) { myval = 'F'; } tess_->process_cmd_win_event(event->command_id, &myval); } else { tess_->process_image_event(*event); } } /** * build_menu() * * Construct the menu tree used by the command window */ namespace tesseract { SVMenuNode *Tesseract::build_menu_new() { SVMenuNode* parent_menu; SVMenuNode* root_menu_item = new SVMenuNode(); SVMenuNode* modes_menu_item = root_menu_item->AddChild("MODES"); modes_menu_item->AddChild("Change Display", CHANGE_DISP_CMD_EVENT); modes_menu_item->AddChild("Dump Word", DUMP_WERD_CMD_EVENT); modes_menu_item->AddChild("Show Point", SHOW_POINT_CMD_EVENT); modes_menu_item->AddChild("Show BL Norm Word", SHOW_BLN_WERD_CMD_EVENT); modes_menu_item->AddChild("Config Words", DEBUG_WERD_CMD_EVENT); modes_menu_item->AddChild("Recog Words", RECOG_WERDS); modes_menu_item->AddChild("Recog Blobs", RECOG_PSEUDO); modes_menu_item->AddChild("Show Blob Features", SHOW_BLOB_FEATURES); parent_menu = root_menu_item->AddChild("DISPLAY"); parent_menu->AddChild("Blamer", BLAMER_CMD_EVENT, FALSE); parent_menu->AddChild("Bounding Boxes", BOUNDING_BOX_CMD_EVENT, FALSE); parent_menu->AddChild("Correct Text", CORRECT_TEXT_CMD_EVENT, FALSE); parent_menu->AddChild("Polygonal Approx", POLYGONAL_CMD_EVENT, FALSE); parent_menu->AddChild("Baseline Normalized", BL_NORM_CMD_EVENT, FALSE); parent_menu->AddChild("Edge Steps", BITMAP_CMD_EVENT, TRUE); parent_menu->AddChild("Subscripts", SHOW_SUBSCRIPT_CMD_EVENT); parent_menu->AddChild("Superscripts", SHOW_SUPERSCRIPT_CMD_EVENT); parent_menu->AddChild("Italics", SHOW_ITALIC_CMD_EVENT); parent_menu->AddChild("Bold", SHOW_BOLD_CMD_EVENT); parent_menu->AddChild("Underline", SHOW_UNDERLINE_CMD_EVENT); parent_menu->AddChild("FixedPitch", SHOW_FIXEDPITCH_CMD_EVENT); parent_menu->AddChild("Serifs", SHOW_SERIF_CMD_EVENT); parent_menu->AddChild("SmallCaps", SHOW_SMALLCAPS_CMD_EVENT); parent_menu->AddChild("DropCaps", SHOW_DROPCAPS_CMD_EVENT); parent_menu = root_menu_item->AddChild("OTHER"); parent_menu->AddChild("Quit", QUIT_CMD_EVENT); parent_menu->AddChild("Show Image", IMAGE_CMD_EVENT, FALSE); parent_menu->AddChild("ShowBlock Outlines", BLOCKS_CMD_EVENT, FALSE); parent_menu->AddChild("Show Baselines", BASELINES_CMD_EVENT, FALSE); parent_menu->AddChild("Uniform Display", UNIFORM_DISP_CMD_EVENT); parent_menu->AddChild("Refresh Display", REFRESH_CMD_EVENT); return root_menu_item; } /** * do_re_display() * * Redisplay page */ void Tesseract::do_re_display( BOOL8 (tesseract::Tesseract::*word_painter)(PAGE_RES_IT* pr_it)) { int block_count = 1; image_win->Clear(); if (display_image != 0) { image_win->Image(pix_binary_, 0, 0); } PAGE_RES_IT pr_it(current_page_res); for (WERD_RES* word = pr_it.word(); word != NULL; word = pr_it.forward()) { (this->*word_painter)(&pr_it); if (display_baselines && pr_it.row() != pr_it.prev_row()) pr_it.row()->row->plot_baseline(image_win, ScrollView::GREEN); if (display_blocks && pr_it.block() != pr_it.prev_block()) pr_it.block()->block->plot(image_win, block_count++, ScrollView::RED); } image_win->Update(); } /** * pgeditor_main() * * Top level editor operation: * Setup a new window and an according event handler * */ void Tesseract::pgeditor_main(int width, int height, PAGE_RES *page_res) { current_page_res = page_res; if (current_page_res->block_res_list.empty()) return; recog_done = false; stillRunning = true; build_image_window(width, height); word_display_mode.turn_on_bit(DF_EDGE_STEP); do_re_display(&tesseract::Tesseract::word_set_display); #ifndef GRAPHICS_DISABLED pe = new ParamsEditor(this, image_win); #endif PGEventHandler pgEventHandler(this); image_win->AddEventHandler(&pgEventHandler); image_win->AddMessageBox(); SVMenuNode* svMenuRoot = build_menu_new(); svMenuRoot->BuildMenu(image_win); image_win->SetVisible(true); image_win->AwaitEvent(SVET_DESTROY); image_win->AddEventHandler(NULL); } } // namespace tesseract /** * pgeditor_msg() * * Display a message - in the command window if there is one, or to stdout */ void pgeditor_msg( // message display const char *msg) { image_win->AddMessage(msg); } /** * pgeditor_show_point() * * Display the coordinates of a point in the command window */ void pgeditor_show_point( // display coords SVEvent *event) { image_win->AddMessage("Pointing at(%d, %d)", event->x, event->y); } /** * process_cmd_win_event() * * Process a command returned from the command window * (Just call the appropriate command handler) */ namespace tesseract { BOOL8 Tesseract::process_cmd_win_event( // UI command semantics inT32 cmd_event, // which menu item? char *new_value // any prompt data ) { char msg[160]; BOOL8 exit = FALSE; color_mode = CM_RAINBOW; // Run recognition on the full page if needed. switch (cmd_event) { case BLAMER_CMD_EVENT: case SHOW_SUBSCRIPT_CMD_EVENT: case SHOW_SUPERSCRIPT_CMD_EVENT: case SHOW_ITALIC_CMD_EVENT: case SHOW_BOLD_CMD_EVENT: case SHOW_UNDERLINE_CMD_EVENT: case SHOW_FIXEDPITCH_CMD_EVENT: case SHOW_SERIF_CMD_EVENT: case SHOW_SMALLCAPS_CMD_EVENT: case SHOW_DROPCAPS_CMD_EVENT: if (!recog_done) { recog_all_words(current_page_res, NULL, NULL, NULL, 0); recog_done = true; } break; default: break; } switch (cmd_event) { case NULL_CMD_EVENT: break; case CHANGE_DISP_CMD_EVENT: case DUMP_WERD_CMD_EVENT: case SHOW_POINT_CMD_EVENT: case SHOW_BLN_WERD_CMD_EVENT: case RECOG_WERDS: case RECOG_PSEUDO: case SHOW_BLOB_FEATURES: mode =(CMD_EVENTS) cmd_event; break; case DEBUG_WERD_CMD_EVENT: mode = DEBUG_WERD_CMD_EVENT; word_config_ = image_win->ShowInputDialog("Config File Name"); break; case BOUNDING_BOX_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_BOX); else word_display_mode.turn_off_bit(DF_BOX); mode = CHANGE_DISP_CMD_EVENT; break; case BLAMER_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_BLAMER); else word_display_mode.turn_off_bit(DF_BLAMER); do_re_display(&tesseract::Tesseract::word_display); mode = CHANGE_DISP_CMD_EVENT; break; case CORRECT_TEXT_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_TEXT); else word_display_mode.turn_off_bit(DF_TEXT); mode = CHANGE_DISP_CMD_EVENT; break; case POLYGONAL_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_POLYGONAL); else word_display_mode.turn_off_bit(DF_POLYGONAL); mode = CHANGE_DISP_CMD_EVENT; break; case BL_NORM_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_BN_POLYGONAL); else word_display_mode.turn_off_bit(DF_BN_POLYGONAL); mode = CHANGE_DISP_CMD_EVENT; break; case BITMAP_CMD_EVENT: if (new_value[0] == 'T') word_display_mode.turn_on_bit(DF_EDGE_STEP); else word_display_mode.turn_off_bit(DF_EDGE_STEP); mode = CHANGE_DISP_CMD_EVENT; break; case UNIFORM_DISP_CMD_EVENT: do_re_display(&tesseract::Tesseract::word_set_display); break; case IMAGE_CMD_EVENT: display_image =(new_value[0] == 'T'); do_re_display(&tesseract::Tesseract::word_display); break; case BLOCKS_CMD_EVENT: display_blocks =(new_value[0] == 'T'); do_re_display(&tesseract::Tesseract::word_display); break; case BASELINES_CMD_EVENT: display_baselines =(new_value[0] == 'T'); do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_SUBSCRIPT_CMD_EVENT: color_mode = CM_SUBSCRIPT; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_SUPERSCRIPT_CMD_EVENT: color_mode = CM_SUPERSCRIPT; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_ITALIC_CMD_EVENT: color_mode = CM_ITALIC; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_BOLD_CMD_EVENT: color_mode = CM_BOLD; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_UNDERLINE_CMD_EVENT: color_mode = CM_UNDERLINE; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_FIXEDPITCH_CMD_EVENT: color_mode = CM_FIXEDPITCH; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_SERIF_CMD_EVENT: color_mode = CM_SERIF; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_SMALLCAPS_CMD_EVENT: color_mode = CM_SMALLCAPS; do_re_display(&tesseract::Tesseract::word_display); break; case SHOW_DROPCAPS_CMD_EVENT: color_mode = CM_DROPCAPS; do_re_display(&tesseract::Tesseract::word_display); break; case REFRESH_CMD_EVENT: do_re_display(&tesseract::Tesseract::word_display); break; case QUIT_CMD_EVENT: exit = TRUE; ScrollView::Exit(); break; default: sprintf(msg, "Unrecognised event " INT32FORMAT "(%s)", cmd_event, new_value); image_win->AddMessage(msg); break; } return exit; } /** * process_image_event() * * User has done something in the image window - mouse down or up. Work out * what it is and do something with it. * If DOWN - just remember where it was. * If UP - for each word in the selected area do the operation defined by * the current mode. */ void Tesseract::process_image_event( // action in image win const SVEvent &event) { // The following variable should remain static, since it is used by // debug editor, which uses a single Tesseract instance. static ICOORD down; ICOORD up; TBOX selection_box; char msg[80]; switch(event.type) { case SVET_SELECTION: if (event.type == SVET_SELECTION) { down.set_x(event.x + event.x_size); down.set_y(event.y + event.y_size); if (mode == SHOW_POINT_CMD_EVENT) show_point(current_page_res, event.x, event.y); } up.set_x(event.x); up.set_y(event.y); selection_box = TBOX(down, up); switch(mode) { case CHANGE_DISP_CMD_EVENT: process_selected_words( current_page_res, selection_box, &tesseract::Tesseract::word_blank_and_set_display); break; case DUMP_WERD_CMD_EVENT: process_selected_words(current_page_res, selection_box, &tesseract::Tesseract::word_dumper); break; case SHOW_BLN_WERD_CMD_EVENT: process_selected_words(current_page_res, selection_box, &tesseract::Tesseract::word_bln_display); break; case DEBUG_WERD_CMD_EVENT: debug_word(current_page_res, selection_box); break; case SHOW_POINT_CMD_EVENT: break; // ignore up event case RECOG_WERDS: image_win->AddMessage("Recogging selected words"); this->process_selected_words(current_page_res, selection_box, &Tesseract::recog_interactive); break; case RECOG_PSEUDO: image_win->AddMessage("Recogging selected blobs"); recog_pseudo_word(current_page_res, selection_box); break; case SHOW_BLOB_FEATURES: blob_feature_display(current_page_res, selection_box); break; default: sprintf(msg, "Mode %d not yet implemented", mode); image_win->AddMessage(msg); break; } default: break; } } /** * debug_word * * Process the whole image, but load word_config_ for the selected word(s). */ void Tesseract::debug_word(PAGE_RES* page_res, const TBOX &selection_box) { ResetAdaptiveClassifier(); recog_all_words(page_res, NULL, &selection_box, word_config_.string(), 0); } } // namespace tesseract /** * show_point() * * Show coords of point, blob bounding box, word bounding box and offset from * row baseline */ void show_point(PAGE_RES* page_res, float x, float y) { FCOORD pt(x, y); PAGE_RES_IT pr_it(page_res); char msg[160]; char *msg_ptr = msg; msg_ptr += sprintf(msg_ptr, "Pt:(%0.3f, %0.3f) ", x, y); for (WERD_RES* word = pr_it.word(); word != NULL; word = pr_it.forward()) { if (pr_it.row() != pr_it.prev_row() && pr_it.row()->row->bounding_box().contains(pt)) { msg_ptr += sprintf(msg_ptr, "BL(x)=%0.3f ", pr_it.row()->row->base_line(x)); } if (word->word->bounding_box().contains(pt)) { TBOX box = word->word->bounding_box(); msg_ptr += sprintf(msg_ptr, "Wd(%d, %d)/(%d, %d) ", box.left(), box.bottom(), box.right(), box.top()); C_BLOB_IT cblob_it(word->word->cblob_list()); for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list(); cblob_it.forward()) { C_BLOB* cblob = cblob_it.data(); box = cblob->bounding_box(); if (box.contains(pt)) { msg_ptr += sprintf(msg_ptr, "CBlb(%d, %d)/(%d, %d) ", box.left(), box.bottom(), box.right(), box.top()); } } } } image_win->AddMessage(msg); } /********************************************************************** * WERD PROCESSOR FUNCTIONS * ======================== * * These routines are invoked by one or more of: * process_all_words() * process_selected_words() * or * process_all_words_it() * process_selected_words_it() * for each word to be processed **********************************************************************/ /** * word_blank_and_set_display() Word processor * * Blank display of word then redisplay word according to current display mode * settings */ #endif // GRAPHICS_DISABLED namespace tesseract { #ifndef GRAPHICS_DISABLED BOOL8 Tesseract:: word_blank_and_set_display(PAGE_RES_IT* pr_it) { pr_it->word()->word->bounding_box().plot(image_win, ScrollView::BLACK, ScrollView::BLACK); return word_set_display(pr_it); } /** * word_bln_display() * * Normalize word and display in word window */ BOOL8 Tesseract::word_bln_display(PAGE_RES_IT* pr_it) { WERD_RES* word_res = pr_it->word(); if (word_res->chopped_word == NULL) { // Setup word normalization parameters. word_res->SetupForRecognition(unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL, classify_bln_numeric_mode, textord_use_cjk_fp_model, poly_allow_detailed_fx, pr_it->row()->row, pr_it->block()->block); } bln_word_window_handle()->Clear(); display_bln_lines(bln_word_window_handle(), ScrollView::CYAN, 1.0, 0.0f, -1000.0f, 1000.0f); C_BLOB_IT it(word_res->word->cblob_list()); ScrollView::Color color = WERD::NextColor(ScrollView::BLACK); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { it.data()->plot_normed(word_res->denorm, color, ScrollView::BROWN, bln_word_window_handle()); color = WERD::NextColor(color); } bln_word_window_handle()->Update(); return TRUE; } /** * word_display() Word Processor * * Display a word according to its display modes */ BOOL8 Tesseract::word_display(PAGE_RES_IT* pr_it) { WERD_RES* word_res = pr_it->word(); WERD* word = word_res->word; TBOX word_bb; // word bounding box int word_height; // ht of word BB BOOL8 displayed_something = FALSE; float shift; // from bot left C_BLOB_IT c_it; // cblob iterator if (color_mode != CM_RAINBOW && word_res->box_word != NULL) { BoxWord* box_word = word_res->box_word; WERD_CHOICE* best_choice = word_res->best_choice; int length = box_word->length(); if (word_res->fontinfo == NULL) return false; const FontInfo& font_info = *word_res->fontinfo; for (int i = 0; i < length; ++i) { ScrollView::Color color = ScrollView::GREEN; switch (color_mode) { case CM_SUBSCRIPT: if (best_choice->BlobPosition(i) == SP_SUBSCRIPT) color = ScrollView::RED; break; case CM_SUPERSCRIPT: if (best_choice->BlobPosition(i) == SP_SUPERSCRIPT) color = ScrollView::RED; break; case CM_ITALIC: if (font_info.is_italic()) color = ScrollView::RED; break; case CM_BOLD: if (font_info.is_bold()) color = ScrollView::RED; break; case CM_FIXEDPITCH: if (font_info.is_fixed_pitch()) color = ScrollView::RED; break; case CM_SERIF: if (font_info.is_serif()) color = ScrollView::RED; break; case CM_SMALLCAPS: if (word_res->small_caps) color = ScrollView::RED; break; case CM_DROPCAPS: if (best_choice->BlobPosition(i) == SP_DROPCAP) color = ScrollView::RED; break; // TODO(rays) underline is currently completely unsupported. case CM_UNDERLINE: default: break; } image_win->Pen(color); TBOX box = box_word->BlobBox(i); image_win->Rectangle(box.left(), box.bottom(), box.right(), box.top()); } return true; } /* Note the double coercions of(COLOUR)((inT32)editor_image_word_bb_color) etc. are to keep the compiler happy. */ // display bounding box if (word->display_flag(DF_BOX)) { word->bounding_box().plot(image_win, (ScrollView::Color)((inT32) editor_image_word_bb_color), (ScrollView::Color)((inT32) editor_image_word_bb_color)); ScrollView::Color c = (ScrollView::Color) ((inT32) editor_image_blob_bb_color); image_win->Pen(c); c_it.set_to_list(word->cblob_list()); for (c_it.mark_cycle_pt(); !c_it.cycled_list(); c_it.forward()) c_it.data()->bounding_box().plot(image_win); displayed_something = TRUE; } // display edge steps if (word->display_flag(DF_EDGE_STEP)) { // edgesteps available word->plot(image_win); // rainbow colors displayed_something = TRUE; } // display poly approx if (word->display_flag(DF_POLYGONAL)) { // need to convert TWERD* tword = TWERD::PolygonalCopy(poly_allow_detailed_fx, word); tword->plot(image_win); delete tword; displayed_something = TRUE; } // Display correct text and blamer information. STRING text; STRING blame; if (word->display_flag(DF_TEXT) && word->text() != NULL) { text = word->text(); } if (word->display_flag(DF_BLAMER) && !(word_res->blamer_bundle != NULL && word_res->blamer_bundle->incorrect_result_reason() == IRR_CORRECT)) { text = ""; const BlamerBundle *blamer_bundle = word_res->blamer_bundle; if (blamer_bundle == NULL) { text += "NULL"; } else { text = blamer_bundle->TruthString(); } text += " -> "; STRING best_choice_str; if (word_res->best_choice == NULL) { best_choice_str = "NULL"; } else { word_res->best_choice->string_and_lengths(&best_choice_str, NULL); } text += best_choice_str; IncorrectResultReason reason = (blamer_bundle == NULL) ? IRR_PAGE_LAYOUT : blamer_bundle->incorrect_result_reason(); ASSERT_HOST(reason < IRR_NUM_REASONS) blame += " ["; blame += BlamerBundle::IncorrectReasonName(reason); blame += "]"; } if (text.length() > 0) { word_bb = word->bounding_box(); image_win->Pen(ScrollView::RED); word_height = word_bb.height(); int text_height = 0.50 * word_height; if (text_height > 20) text_height = 20; image_win->TextAttributes("Arial", text_height, false, false, false); shift = (word_height < word_bb.width()) ? 0.25 * word_height : 0.0f; image_win->Text(word_bb.left() + shift, word_bb.bottom() + 0.25 * word_height, text.string()); if (blame.length() > 0) { image_win->Text(word_bb.left() + shift, word_bb.bottom() + 0.25 * word_height - text_height, blame.string()); } displayed_something = TRUE; } if (!displayed_something) // display BBox anyway word->bounding_box().plot(image_win, (ScrollView::Color)((inT32) editor_image_word_bb_color), (ScrollView::Color)((inT32) editor_image_word_bb_color)); return TRUE; } #endif // GRAPHICS_DISABLED /** * word_dumper() * * Dump members to the debug window */ BOOL8 Tesseract::word_dumper(PAGE_RES_IT* pr_it) { if (pr_it->block()->block != NULL) { tprintf("\nBlock data...\n"); pr_it->block()->block->print(NULL, FALSE); } tprintf("\nRow data...\n"); pr_it->row()->row->print(NULL); tprintf("\nWord data...\n"); WERD_RES* word_res = pr_it->word(); word_res->word->print(); if (word_res->blamer_bundle != NULL && wordrec_debug_blamer && word_res->blamer_bundle->incorrect_result_reason() != IRR_CORRECT) { tprintf("Current blamer debug: %s\n", word_res->blamer_bundle->debug().string()); } return TRUE; } #ifndef GRAPHICS_DISABLED /** * word_set_display() Word processor * * Display word according to current display mode settings */ BOOL8 Tesseract::word_set_display(PAGE_RES_IT* pr_it) { WERD* word = pr_it->word()->word; word->set_display_flag(DF_BOX, word_display_mode.bit(DF_BOX)); word->set_display_flag(DF_TEXT, word_display_mode.bit(DF_TEXT)); word->set_display_flag(DF_POLYGONAL, word_display_mode.bit(DF_POLYGONAL)); word->set_display_flag(DF_EDGE_STEP, word_display_mode.bit(DF_EDGE_STEP)); word->set_display_flag(DF_BN_POLYGONAL, word_display_mode.bit(DF_BN_POLYGONAL)); word->set_display_flag(DF_BLAMER, word_display_mode.bit(DF_BLAMER)); return word_display(pr_it); } // page_res is non-const because the iterator doesn't know if you are going // to change the items it points to! Really a const here though. void Tesseract::blob_feature_display(PAGE_RES* page_res, const TBOX& selection_box) { PAGE_RES_IT* it = make_pseudo_word(page_res, selection_box); if (it != NULL) { WERD_RES* word_res = it->word(); word_res->x_height = it->row()->row->x_height(); word_res->SetupForRecognition(unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL, classify_bln_numeric_mode, textord_use_cjk_fp_model, poly_allow_detailed_fx, it->row()->row, it->block()->block); TWERD* bln_word = word_res->chopped_word; TBLOB* bln_blob = bln_word->blobs[0]; INT_FX_RESULT_STRUCT fx_info; GenericVector<INT_FEATURE_STRUCT> bl_features; GenericVector<INT_FEATURE_STRUCT> cn_features; Classify::ExtractFeatures(*bln_blob, classify_nonlinear_norm, &bl_features, &cn_features, &fx_info, NULL); // Display baseline features. ScrollView* bl_win = CreateFeatureSpaceWindow("BL Features", 512, 0); ClearFeatureSpaceWindow(baseline, bl_win); for (int f = 0; f < bl_features.size(); ++f) RenderIntFeature(bl_win, &bl_features[f], ScrollView::GREEN); bl_win->Update(); // Display cn features. ScrollView* cn_win = CreateFeatureSpaceWindow("CN Features", 512, 0); ClearFeatureSpaceWindow(character, cn_win); for (int f = 0; f < cn_features.size(); ++f) RenderIntFeature(cn_win, &cn_features[f], ScrollView::GREEN); cn_win->Update(); it->DeleteCurrentWord(); delete it; } } #endif // GRAPHICS_DISABLED } // namespace tesseract
1080228-arabicocr11
ccmain/pgedit.cpp
C++
asf20
32,310
/****************************************************************** * File: cube_control.cpp * Description: Tesseract class methods for invoking cube convolutional * neural network word recognizer. * Author: Raquel Romano * Created: September 2009 * **********************************************************************/ // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "allheaders.h" #include "cube_object.h" #include "cube_reco_context.h" #include "tesseractclass.h" #include "tesseract_cube_combiner.h" namespace tesseract { /********************************************************************** * convert_prob_to_tess_certainty * * Normalize a probability in the range [0.0, 1.0] to a tesseract * certainty in the range [-20.0, 0.0] **********************************************************************/ static float convert_prob_to_tess_certainty(float prob) { return (prob - 1.0) * 20.0; } /********************************************************************** * char_box_to_tbox * * Create a TBOX from a character bounding box. If nonzero, the * x_offset accounts for any additional padding of the word box that * should be taken into account. * **********************************************************************/ TBOX char_box_to_tbox(Box* char_box, TBOX word_box, int x_offset) { l_int32 left; l_int32 top; l_int32 width; l_int32 height; l_int32 right; l_int32 bottom; boxGetGeometry(char_box, &left, &top, &width, &height); left += word_box.left() - x_offset; right = left + width; top = word_box.bottom() + word_box.height() - top; bottom = top - height; return TBOX(left, bottom, right, top); } /********************************************************************** * extract_cube_state * * Extract CharSamp objects and character bounding boxes from the * CubeObject's state. The caller should free both structres. * **********************************************************************/ bool Tesseract::extract_cube_state(CubeObject* cube_obj, int* num_chars, Boxa** char_boxes, CharSamp*** char_samples) { if (!cube_obj) { if (cube_debug_level > 0) { tprintf("Cube WARNING (extract_cube_state): Invalid cube object " "passed to extract_cube_state\n"); } return false; } // Note that the CubeObject accessors return either the deslanted or // regular objects search object or beam search object, whichever // was used in the last call to Recognize() CubeSearchObject* cube_search_obj = cube_obj->SrchObj(); if (!cube_search_obj) { if (cube_debug_level > 0) { tprintf("Cube WARNING (Extract_cube_state): Could not retrieve " "cube's search object in extract_cube_state.\n"); } return false; } BeamSearch *beam_search_obj = cube_obj->BeamObj(); if (!beam_search_obj) { if (cube_debug_level > 0) { tprintf("Cube WARNING (Extract_cube_state): Could not retrieve " "cube's beam search object in extract_cube_state.\n"); } return false; } // Get the character samples and bounding boxes by backtracking // through the beam search path int best_node_index = beam_search_obj->BestPresortedNodeIndex(); *char_samples = beam_search_obj->BackTrack( cube_search_obj, best_node_index, num_chars, NULL, char_boxes); if (!*char_samples) return false; return true; } /********************************************************************** * create_cube_box_word * * Fill the given BoxWord with boxes from character bounding * boxes. The char_boxes have local coordinates w.r.t. the * word bounding box, i.e., the left-most character bbox of each word * has (0,0) left-top coord, but the BoxWord must be defined in page * coordinates. **********************************************************************/ bool Tesseract::create_cube_box_word(Boxa *char_boxes, int num_chars, TBOX word_box, BoxWord* box_word) { if (!box_word) { if (cube_debug_level > 0) { tprintf("Cube WARNING (create_cube_box_word): Invalid box_word.\n"); } return false; } // Find the x-coordinate of left-most char_box, which could be // nonzero if the word image was padded before recognition took place. int x_offset = -1; for (int i = 0; i < num_chars; ++i) { Box* char_box = boxaGetBox(char_boxes, i, L_CLONE); if (x_offset < 0 || char_box->x < x_offset) { x_offset = char_box->x; } boxDestroy(&char_box); } for (int i = 0; i < num_chars; ++i) { Box* char_box = boxaGetBox(char_boxes, i, L_CLONE); TBOX tbox = char_box_to_tbox(char_box, word_box, x_offset); boxDestroy(&char_box); box_word->InsertBox(i, tbox); } return true; } /********************************************************************** * init_cube_objects * * Instantiates Tesseract object's CubeRecoContext and TesseractCubeCombiner. * Returns false if cube context could not be created or if load_combiner is * true, but the combiner could not be loaded. **********************************************************************/ bool Tesseract::init_cube_objects(bool load_combiner, TessdataManager *tessdata_manager) { ASSERT_HOST(cube_cntxt_ == NULL); ASSERT_HOST(tess_cube_combiner_ == NULL); // Create the cube context object cube_cntxt_ = CubeRecoContext::Create(this, tessdata_manager, &unicharset); if (cube_cntxt_ == NULL) { if (cube_debug_level > 0) { tprintf("Cube WARNING (Tesseract::init_cube_objects()): Failed to " "instantiate CubeRecoContext\n"); } return false; } // Create the combiner object and load the combiner net for target languages. if (load_combiner) { tess_cube_combiner_ = new tesseract::TesseractCubeCombiner(cube_cntxt_); if (!tess_cube_combiner_ || !tess_cube_combiner_->LoadCombinerNet()) { delete cube_cntxt_; cube_cntxt_ = NULL; if (tess_cube_combiner_ != NULL) { delete tess_cube_combiner_; tess_cube_combiner_ = NULL; } if (cube_debug_level > 0) tprintf("Cube ERROR (Failed to instantiate TesseractCubeCombiner\n"); return false; } } return true; } /********************************************************************** * run_cube_combiner * * Iterates through tesseract's results and calls cube on each word, * combining the results with the existing tesseract result. **********************************************************************/ void Tesseract::run_cube_combiner(PAGE_RES *page_res) { if (page_res == NULL || tess_cube_combiner_ == NULL) return; PAGE_RES_IT page_res_it(page_res); // Iterate through the word results and call cube on each word. for (page_res_it.restart_page(); page_res_it.word () != NULL; page_res_it.forward()) { BLOCK* block = page_res_it.block()->block; if (block->poly_block() != NULL && !block->poly_block()->IsText()) continue; // Don't deal with non-text blocks. WERD_RES* word = page_res_it.word(); // Skip cube entirely if tesseract's certainty is greater than threshold. int combiner_run_thresh = convert_prob_to_tess_certainty( cube_cntxt_->Params()->CombinerRunThresh()); if (word->best_choice->certainty() >= combiner_run_thresh) { continue; } // Use the same language as Tesseract used for the word. Tesseract* lang_tess = word->tesseract; // Setup a trial WERD_RES in which to classify with cube. WERD_RES cube_word; cube_word.InitForRetryRecognition(*word); cube_word.SetupForRecognition(lang_tess->unicharset, this, BestPix(), OEM_CUBE_ONLY, NULL, false, false, false, page_res_it.row()->row, page_res_it.block()->block); CubeObject *cube_obj = lang_tess->cube_recognize_word( page_res_it.block()->block, &cube_word); if (cube_obj != NULL) lang_tess->cube_combine_word(cube_obj, &cube_word, word); delete cube_obj; } } /********************************************************************** * cube_word_pass1 * * Recognizes a single word using (only) cube. Compatible with * Tesseract's classify_word_pass1/classify_word_pass2. **********************************************************************/ void Tesseract::cube_word_pass1(BLOCK* block, ROW *row, WERD_RES *word) { CubeObject *cube_obj = cube_recognize_word(block, word); delete cube_obj; } /********************************************************************** * cube_recognize_word * * Cube recognizer to recognize a single word as with classify_word_pass1 * but also returns the cube object in case the combiner is needed. **********************************************************************/ CubeObject* Tesseract::cube_recognize_word(BLOCK* block, WERD_RES* word) { if (!cube_binary_ || !cube_cntxt_) { if (cube_debug_level > 0 && !cube_binary_) tprintf("Tesseract::run_cube(): NULL binary image.\n"); word->SetupFake(unicharset); return NULL; } TBOX word_box = word->word->bounding_box(); if (block != NULL && (block->re_rotation().x() != 1.0f || block->re_rotation().y() != 0.0f)) { // TODO(rays) We have to rotate the bounding box to get the true coords. // This will be achieved in the future via DENORM. // In the mean time, cube can't process this word. if (cube_debug_level > 0) { tprintf("Cube can't process rotated word at:"); word_box.print(); } word->SetupFake(unicharset); return NULL; } CubeObject* cube_obj = new tesseract::CubeObject( cube_cntxt_, cube_binary_, word_box.left(), pixGetHeight(cube_binary_) - word_box.top(), word_box.width(), word_box.height()); if (!cube_recognize(cube_obj, block, word)) { delete cube_obj; return NULL; } return cube_obj; } /********************************************************************** * cube_combine_word * * Combines the cube and tesseract results for a single word, leaving the * result in tess_word. **********************************************************************/ void Tesseract::cube_combine_word(CubeObject* cube_obj, WERD_RES* cube_word, WERD_RES* tess_word) { float combiner_prob = tess_cube_combiner_->CombineResults(tess_word, cube_obj); // If combiner probability is greater than tess/cube combiner // classifier threshold, i.e. tesseract wins, then just return the // tesseract result unchanged, as the combiner knows nothing about how // correct the answer is. If cube and tesseract agree, then improve the // scores before returning. WERD_CHOICE* tess_best = tess_word->best_choice; WERD_CHOICE* cube_best = cube_word->best_choice; if (cube_debug_level || classify_debug_level) { tprintf("Combiner prob = %g vs threshold %g\n", combiner_prob, cube_cntxt_->Params()->CombinerClassifierThresh()); } if (combiner_prob >= cube_cntxt_->Params()->CombinerClassifierThresh()) { if (tess_best->unichar_string() == cube_best->unichar_string()) { // Cube and tess agree, so improve the scores. tess_best->set_rating(tess_best->rating() / 2); tess_best->set_certainty(tess_best->certainty() / 2); } return; } // Cube wins. // It is better for the language combiner to have all tesseract scores, // so put them in the cube result. cube_best->set_rating(tess_best->rating()); cube_best->set_certainty(tess_best->certainty()); if (cube_debug_level || classify_debug_level) { tprintf("Cube INFO: tesseract result replaced by cube: %s -> %s\n", tess_best->unichar_string().string(), cube_best->unichar_string().string()); } tess_word->ConsumeWordResults(cube_word); } /********************************************************************** * cube_recognize * * Call cube on the current word, and write the result to word. * Sets up a fake result and returns false if something goes wrong. **********************************************************************/ bool Tesseract::cube_recognize(CubeObject *cube_obj, BLOCK* block, WERD_RES *word) { // Run cube WordAltList *cube_alt_list = cube_obj->RecognizeWord(); if (!cube_alt_list || cube_alt_list->AltCount() <= 0) { if (cube_debug_level > 0) { tprintf("Cube returned nothing for word at:"); word->word->bounding_box().print(); } word->SetupFake(unicharset); return false; } // Get cube's best result and its probability, mapped to tesseract's // certainty range char_32 *cube_best_32 = cube_alt_list->Alt(0); double cube_prob = CubeUtils::Cost2Prob(cube_alt_list->AltCost(0)); float cube_certainty = convert_prob_to_tess_certainty(cube_prob); string cube_best_str; CubeUtils::UTF32ToUTF8(cube_best_32, &cube_best_str); // Retrieve Cube's character bounding boxes and CharSamples, // corresponding to the most recent call to RecognizeWord(). Boxa *char_boxes = NULL; CharSamp **char_samples = NULL;; int num_chars; if (!extract_cube_state(cube_obj, &num_chars, &char_boxes, &char_samples) && cube_debug_level > 0) { tprintf("Cube WARNING (Tesseract::cube_recognize): Cannot extract " "cube state.\n"); word->SetupFake(unicharset); return false; } // Convert cube's character bounding boxes to a BoxWord. BoxWord cube_box_word; TBOX tess_word_box = word->word->bounding_box(); if (word->denorm.block() != NULL) tess_word_box.rotate(word->denorm.block()->re_rotation()); bool box_word_success = create_cube_box_word(char_boxes, num_chars, tess_word_box, &cube_box_word); boxaDestroy(&char_boxes); if (!box_word_success) { if (cube_debug_level > 0) { tprintf("Cube WARNING (Tesseract::cube_recognize): Could not " "create cube BoxWord\n"); } word->SetupFake(unicharset); return false; } // Fill tesseract result's fields with cube results fill_werd_res(cube_box_word, cube_best_str.c_str(), word); // Create cube's best choice. BLOB_CHOICE** choices = new BLOB_CHOICE*[num_chars]; for (int i = 0; i < num_chars; ++i) { UNICHAR_ID uch_id = cube_cntxt_->CharacterSet()->UnicharID(char_samples[i]->StrLabel()); choices[i] = new BLOB_CHOICE(uch_id, -cube_certainty, cube_certainty, -1, -1, 0, 0, 0, 0, BCC_STATIC_CLASSIFIER); } word->FakeClassifyWord(num_chars, choices); // within a word, cube recognizes the word in reading order. word->best_choice->set_unichars_in_script_order(true); delete [] choices; delete [] char_samples; // Some sanity checks ASSERT_HOST(word->best_choice->length() == word->reject_map.length()); if (cube_debug_level || classify_debug_level) { tprintf("Cube result: %s r=%g, c=%g\n", word->best_choice->unichar_string().string(), word->best_choice->rating(), word->best_choice->certainty()); } return true; } /********************************************************************** * fill_werd_res * * Fill Tesseract's word result fields with cube's. * **********************************************************************/ void Tesseract::fill_werd_res(const BoxWord& cube_box_word, const char* cube_best_str, WERD_RES* tess_werd_res) { delete tess_werd_res->box_word; tess_werd_res->box_word = new BoxWord(cube_box_word); tess_werd_res->box_word->ClipToOriginalWord(tess_werd_res->denorm.block(), tess_werd_res->word); // Fill text and remaining fields tess_werd_res->word->set_text(cube_best_str); tess_werd_res->tess_failed = FALSE; tess_werd_res->tess_accepted = tess_acceptable_word(tess_werd_res); // There is no output word, so we can' call AdaptableWord, but then I don't // think we need to. Fudge the result with accepted. tess_werd_res->tess_would_adapt = tess_werd_res->tess_accepted; // Set word to done, i.e., ignore all of tesseract's tests for rejection tess_werd_res->done = tess_werd_res->tess_accepted; } } // namespace tesseract
1080228-arabicocr11
ccmain/cube_control.cpp
C++
asf20
16,734
/********************************************************************** * File: fixxht.cpp (Formerly fixxht.c) * Description: Improve x_ht and look out for case inconsistencies * Author: Phil Cheatle * Created: Thu Aug 5 14:11:08 BST 1993 * * (C) Copyright 1992, 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. * **********************************************************************/ #include <string.h> #include <ctype.h> #include "params.h" #include "float2int.h" #include "tesseractclass.h" namespace tesseract { // Fixxht overview. // Premise: Initial estimate of x-height is adequate most of the time, but // occasionally it is incorrect. Most notable causes of failure are: // 1. Small caps, where the top of the caps is the same as the body text // xheight. For small caps words the xheight needs to be reduced to correctly // recognize the caps in the small caps word. // 2. All xheight lines, such as summer. Here the initial estimate will have // guessed that the blob tops are caps and will have placed the xheight too low. // 3. Noise/logos beside words, or changes in font size on a line. Such // things can blow the statistics and cause an incorrect estimate. // // Algorithm. // Compare the vertical position (top only) of alphnumerics in a word with // the range of positions in training data (in the unicharset). // See CountMisfitTops. If any characters disagree sufficiently with the // initial xheight estimate, then recalculate the xheight, re-run OCR on // the word, and if the number of vertical misfits goes down, along with // either the word rating or certainty, then keep the new xheight. // The new xheight is calculated as follows:ComputeCompatibleXHeight // For each alphanumeric character that has a vertically misplaced top // (a misfit), yet its bottom is within the acceptable range (ie it is not // likely a sub-or super-script) calculate the range of acceptable xheight // positions from its range of tops, and give each value in the range a // number of votes equal to the distance of its top from its acceptance range. // The x-height position with the median of the votes becomes the new // x-height. This assumes that most characters will be correctly recognized // even if the x-height is incorrect. This is not a terrible assumption, but // it is not great. An improvement would be to use a classifier that does // not care about vertical position or scaling at all. // If the max-min top of a unicharset char is bigger than kMaxCharTopRange // then the char top cannot be used to judge misfits or suggest a new top. const int kMaxCharTopRange = 48; // Returns the number of misfit blob tops in this word. int Tesseract::CountMisfitTops(WERD_RES *word_res) { int bad_blobs = 0; int num_blobs = word_res->rebuild_word->NumBlobs(); for (int blob_id = 0; blob_id < num_blobs; ++blob_id) { TBLOB* blob = word_res->rebuild_word->blobs[blob_id]; UNICHAR_ID class_id = word_res->best_choice->unichar_id(blob_id); if (unicharset.get_isalpha(class_id) || unicharset.get_isdigit(class_id)) { int top = blob->bounding_box().top(); if (top >= INT_FEAT_RANGE) top = INT_FEAT_RANGE - 1; int min_bottom, max_bottom, min_top, max_top; unicharset.get_top_bottom(class_id, &min_bottom, &max_bottom, &min_top, &max_top); if (max_top - min_top > kMaxCharTopRange) continue; bool bad = top < min_top - x_ht_acceptance_tolerance || top > max_top + x_ht_acceptance_tolerance; if (bad) ++bad_blobs; if (debug_x_ht_level >= 1) { tprintf("Class %s is %s with top %d vs limits of %d->%d, +/-%d\n", unicharset.id_to_unichar(class_id), bad ? "Misfit" : "OK", top, min_top, max_top, static_cast<int>(x_ht_acceptance_tolerance)); } } } return bad_blobs; } // Returns a new x-height maximally compatible with the result in word_res. // See comment above for overall algorithm. float Tesseract::ComputeCompatibleXheight(WERD_RES *word_res) { STATS top_stats(0, MAX_UINT8); int num_blobs = word_res->rebuild_word->NumBlobs(); for (int blob_id = 0; blob_id < num_blobs; ++blob_id) { TBLOB* blob = word_res->rebuild_word->blobs[blob_id]; UNICHAR_ID class_id = word_res->best_choice->unichar_id(blob_id); if (unicharset.get_isalpha(class_id) || unicharset.get_isdigit(class_id)) { int top = blob->bounding_box().top(); // Clip the top to the limit of normalized feature space. if (top >= INT_FEAT_RANGE) top = INT_FEAT_RANGE - 1; int bottom = blob->bounding_box().bottom(); int min_bottom, max_bottom, min_top, max_top; unicharset.get_top_bottom(class_id, &min_bottom, &max_bottom, &min_top, &max_top); // Chars with a wild top range would mess up the result so ignore them. if (max_top - min_top > kMaxCharTopRange) continue; int misfit_dist = MAX((min_top - x_ht_acceptance_tolerance) - top, top - (max_top + x_ht_acceptance_tolerance)); int height = top - kBlnBaselineOffset; if (debug_x_ht_level >= 20) { tprintf("Class %s: height=%d, bottom=%d,%d top=%d,%d, actual=%d,%d : ", unicharset.id_to_unichar(class_id), height, min_bottom, max_bottom, min_top, max_top, bottom, top); } // Use only chars that fit in the expected bottom range, and where // the range of tops is sensibly near the xheight. if (min_bottom <= bottom + x_ht_acceptance_tolerance && bottom - x_ht_acceptance_tolerance <= max_bottom && min_top > kBlnBaselineOffset && max_top - kBlnBaselineOffset >= kBlnXHeight && misfit_dist > 0) { // Compute the x-height position using proportionality between the // actual height and expected height. int min_xht = DivRounded(height * kBlnXHeight, max_top - kBlnBaselineOffset); int max_xht = DivRounded(height * kBlnXHeight, min_top - kBlnBaselineOffset); if (debug_x_ht_level >= 20) { tprintf(" xht range min=%d, max=%d\n", min_xht, max_xht); } // The range of expected heights gets a vote equal to the distance // of the actual top from the expected top. for (int y = min_xht; y <= max_xht; ++y) top_stats.add(y, misfit_dist); } else if (debug_x_ht_level >= 20) { tprintf(" already OK\n"); } } } if (top_stats.get_total() == 0) return 0.0f; // The new xheight is just the median vote, which is then scaled out // of BLN space back to pixel space to get the x-height in pixel space. float new_xht = top_stats.median(); if (debug_x_ht_level >= 20) { tprintf("Median xht=%f\n", new_xht); tprintf("Mode20:A: New x-height = %f (norm), %f (orig)\n", new_xht, new_xht / word_res->denorm.y_scale()); } // The xheight must change by at least x_ht_min_change to be used. if (fabs(new_xht - kBlnXHeight) >= x_ht_min_change) return new_xht / word_res->denorm.y_scale(); else return 0.0f; } } // namespace tesseract
1080228-arabicocr11
ccmain/fixxht.cpp
C++
asf20
7,863
/////////////////////////////////////////////////////////////////////// // 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" template <typename T> class GenericVector; template <typename T> class GenericVectorEqEq; 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<StrongScriptDirection> &word_dirs, GenericVectorEqEq<int> *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<int> *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<StrongScriptDirection> *ssd, GenericVectorEqEq<int> *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<int> *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__
1080228-arabicocr11
ccmain/resultiterator.h
C++
asf20
8,919
/********************************************************************** * File: applybox.cpp (Formerly applybox.c) * Description: Re segment rows according to box file data * Author: Phil Cheatle * Created: Wed Nov 24 09:11:23 GMT 1993 * * (C) Copyright 1993, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #endif #include <ctype.h> #include <string.h> #ifdef __UNIX__ #include <assert.h> #include <errno.h> #endif #include "allheaders.h" #include "boxread.h" #include "chopper.h" #include "pageres.h" #include "unichar.h" #include "unicharset.h" #include "tesseractclass.h" #include "genericvector.h" // Max number of blobs to classify together in FindSegmentation. const int kMaxGroupSize = 4; // Max fraction of median allowed as deviation in xheight before switching // to median. const double kMaxXHeightDeviationFraction = 0.125; /************************************************************************* * The box file is assumed to contain box definitions, one per line, of the * following format for blob-level boxes: * <UTF8 str> <left> <bottom> <right> <top> <page id> * and for word/line-level boxes: * WordStr <left> <bottom> <right> <top> <page id> #<space-delimited word str> * NOTES: * The boxes use tesseract coordinates, i.e. 0,0 is at BOTTOM-LEFT. * * <page id> is 0-based, and the page number is used for multipage input (tiff). * * In the blob-level form, each line represents a recognizable unit, which may * be several UTF-8 bytes, but there is a bounding box around each recognizable * unit, and no classifier is needed to train in this mode (bootstrapping.) * * In the word/line-level form, the line begins with the literal "WordStr", and * the bounding box bounds either a whole line or a whole word. The recognizable * units in the word/line are listed after the # at the end of the line and * are space delimited, ignoring any original spaces on the line. * Eg. * word -> #w o r d * multi word line -> #m u l t i w o r d l i n e * The recognizable units must be space-delimited in order to allow multiple * unicodes to be used for a single recognizable unit, eg Hindi. * In this mode, the classifier must have been pre-trained with the desired * character set, or it will not be able to find the character segmentations. *************************************************************************/ namespace tesseract { static void clear_any_old_text(BLOCK_LIST *block_list) { BLOCK_IT block_it(block_list); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { ROW_IT row_it(block_it.data()->row_list()); for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { WERD_IT word_it(row_it.data()->word_list()); for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { word_it.data()->set_text(""); } } } } // Applies the box file based on the image name fname, and resegments // the words in the block_list (page), with: // blob-mode: one blob per line in the box file, words as input. // word/line-mode: one blob per space-delimited unit after the #, and one word // per line in the box file. (See comment above for box file format.) // If find_segmentation is true, (word/line mode) then the classifier is used // to re-segment words/lines to match the space-delimited truth string for // each box. In this case, the input box may be for a word or even a whole // text line, and the output words will contain multiple blobs corresponding // to the space-delimited input string. // With find_segmentation false, no classifier is needed, but the chopper // can still be used to correctly segment touching characters with the help // of the input boxes. // In the returned PAGE_RES, the WERD_RES are setup as they would be returned // from normal classification, ie. with a word, chopped_word, rebuild_word, // seam_array, denorm, box_word, and best_state, but NO best_choice or // raw_choice, as they would require a UNICHARSET, which we aim to avoid. // Instead, the correct_text member of WERD_RES is set, and this may be later // converted to a best_choice using CorrectClassifyWords. CorrectClassifyWords // is not required before calling ApplyBoxTraining. PAGE_RES* Tesseract::ApplyBoxes(const STRING& fname, bool find_segmentation, BLOCK_LIST *block_list) { GenericVector<TBOX> boxes; GenericVector<STRING> texts, full_texts; if (!ReadAllBoxes(applybox_page, true, fname, &boxes, &texts, &full_texts, NULL)) { return NULL; // Can't do it. } int box_count = boxes.size(); int box_failures = 0; // Add an empty everything to the end. boxes.push_back(TBOX()); texts.push_back(STRING()); full_texts.push_back(STRING()); // In word mode, we use the boxes to make a word for each box, but // in blob mode we use the existing words and maximally chop them first. PAGE_RES* page_res = find_segmentation ? NULL : SetupApplyBoxes(boxes, block_list); clear_any_old_text(block_list); for (int i = 0; i < boxes.size() - 1; i++) { bool foundit = false; if (page_res != NULL) { if (i == 0) { foundit = ResegmentCharBox(page_res, NULL, boxes[i], boxes[i + 1], full_texts[i].string()); } else { foundit = ResegmentCharBox(page_res, &boxes[i-1], boxes[i], boxes[i + 1], full_texts[i].string()); } } else { foundit = ResegmentWordBox(block_list, boxes[i], boxes[i + 1], texts[i].string()); } if (!foundit) { box_failures++; ReportFailedBox(i, boxes[i], texts[i].string(), "FAILURE! Couldn't find a matching blob"); } } if (page_res == NULL) { // In word/line mode, we now maximally chop all the words and resegment // them with the classifier. page_res = SetupApplyBoxes(boxes, block_list); ReSegmentByClassification(page_res); } if (applybox_debug > 0) { tprintf("APPLY_BOXES:\n"); tprintf(" Boxes read from boxfile: %6d\n", box_count); if (box_failures > 0) tprintf(" Boxes failed resegmentation: %6d\n", box_failures); } TidyUp(page_res); return page_res; } // Helper computes median xheight in the image. static double MedianXHeight(BLOCK_LIST *block_list) { BLOCK_IT block_it(block_list); STATS xheights(0, block_it.data()->bounding_box().height()); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { ROW_IT row_it(block_it.data()->row_list()); for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { xheights.add(IntCastRounded(row_it.data()->x_height()), 1); } } return xheights.median(); } // Any row xheight that is significantly different from the median is set // to the median. void Tesseract::PreenXHeights(BLOCK_LIST *block_list) { double median_xheight = MedianXHeight(block_list); double max_deviation = kMaxXHeightDeviationFraction * median_xheight; // Strip all fuzzy space markers to simplify the PAGE_RES. BLOCK_IT b_it(block_list); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { BLOCK* block = b_it.data(); ROW_IT r_it(block->row_list()); for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward ()) { ROW* row = r_it.data(); float diff = fabs(row->x_height() - median_xheight); if (diff > max_deviation) { if (applybox_debug) { tprintf("row xheight=%g, but median xheight = %g\n", row->x_height(), median_xheight); } row->set_x_height(static_cast<float>(median_xheight)); } } } } // Builds a PAGE_RES from the block_list in the way required for ApplyBoxes: // All fuzzy spaces are removed, and all the words are maximally chopped. PAGE_RES* Tesseract::SetupApplyBoxes(const GenericVector<TBOX>& boxes, BLOCK_LIST *block_list) { PreenXHeights(block_list); // Strip all fuzzy space markers to simplify the PAGE_RES. BLOCK_IT b_it(block_list); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { BLOCK* block = b_it.data(); ROW_IT r_it(block->row_list()); for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward ()) { ROW* row = r_it.data(); WERD_IT w_it(row->word_list()); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD* word = w_it.data(); if (word->cblob_list()->empty()) { delete w_it.extract(); } else { word->set_flag(W_FUZZY_SP, false); word->set_flag(W_FUZZY_NON, false); } } } } PAGE_RES* page_res = new PAGE_RES(false, block_list, NULL); PAGE_RES_IT pr_it(page_res); WERD_RES* word_res; while ((word_res = pr_it.word()) != NULL) { MaximallyChopWord(boxes, pr_it.block()->block, pr_it.row()->row, word_res); pr_it.forward(); } return page_res; } // Tests the chopper by exhaustively running chop_one_blob. // The word_res will contain filled chopped_word, seam_array, denorm, // box_word and best_state for the maximally chopped word. void Tesseract::MaximallyChopWord(const GenericVector<TBOX>& boxes, BLOCK* block, ROW* row, WERD_RES* word_res) { if (!word_res->SetupForRecognition(unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL, classify_bln_numeric_mode, textord_use_cjk_fp_model, poly_allow_detailed_fx, row, block)) { word_res->CloneChoppedToRebuild(); return; } if (chop_debug) { tprintf("Maximally chopping word at:"); word_res->word->bounding_box().print(); } GenericVector<BLOB_CHOICE*> blob_choices; ASSERT_HOST(!word_res->chopped_word->blobs.empty()); float rating = static_cast<float>(MAX_INT8); for (int i = 0; i < word_res->chopped_word->NumBlobs(); ++i) { // The rating and certainty are not quite arbitrary. Since // select_blob_to_chop uses the worst certainty to choose, they all have // to be different, so starting with MAX_INT8, subtract 1/8 for each blob // in here, and then divide by e each time they are chopped, which // should guarantee a set of unequal values for the whole tree of blobs // produced, however much chopping is required. The chops are thus only // limited by the ability of the chopper to find suitable chop points, // and not by the value of the certainties. BLOB_CHOICE* choice = new BLOB_CHOICE(0, rating, -rating, -1, -1, 0, 0, 0, 0, BCC_FAKE); blob_choices.push_back(choice); rating -= 0.125f; } const double e = exp(1.0); // The base of natural logs. int blob_number; int right_chop_index = 0; if (!assume_fixed_pitch_char_segment) { // We only chop if the language is not fixed pitch like CJK. SEAM* seam = NULL; while ((seam = chop_one_blob(boxes, blob_choices, word_res, &blob_number)) != NULL) { word_res->InsertSeam(blob_number, seam); BLOB_CHOICE* left_choice = blob_choices[blob_number]; rating = left_choice->rating() / e; left_choice->set_rating(rating); left_choice->set_certainty(-rating); // combine confidence w/ serial # BLOB_CHOICE* right_choice = new BLOB_CHOICE(++right_chop_index, rating - 0.125f, -rating, -1, -1, 0, 0, 0, 0, BCC_FAKE); blob_choices.insert(right_choice, blob_number + 1); } } word_res->CloneChoppedToRebuild(); word_res->FakeClassifyWord(blob_choices.size(), &blob_choices[0]); } // Helper to compute the dispute resolution metric. // Disputed blob resolution. The aim is to give the blob to the most // appropriate boxfile box. Most of the time it is obvious, but if // two boxfile boxes overlap significantly it is not. If a small boxfile // box takes most of the blob, and a large boxfile box does too, then // we want the small boxfile box to get it, but if the small box // is much smaller than the blob, we don't want it to get it. // Details of the disputed blob resolution: // Given a box with area A, and a blob with area B, with overlap area C, // then the miss metric is (A-C)(B-C)/(AB) and the box with minimum // miss metric gets the blob. static double BoxMissMetric(const TBOX& box1, const TBOX& box2) { int overlap_area = box1.intersection(box2).area(); double miss_metric = box1.area()- overlap_area; miss_metric /= box1.area(); miss_metric *= box2.area() - overlap_area; miss_metric /= box2.area(); return miss_metric; } // Gather consecutive blobs that match the given box into the best_state // and corresponding correct_text. // Fights over which box owns which blobs are settled by pre-chopping and // applying the blobs to box or next_box with the least non-overlap. // Returns false if the box was in error, which can only be caused by // failing to find an appropriate blob for a box. // This means that occasionally, blobs may be incorrectly segmented if the // chopper fails to find a suitable chop point. bool Tesseract::ResegmentCharBox(PAGE_RES* page_res, const TBOX *prev_box, const TBOX& box, const TBOX& next_box, const char* correct_text) { if (applybox_debug > 1) { tprintf("\nAPPLY_BOX: in ResegmentCharBox() for %s\n", correct_text); } PAGE_RES_IT page_res_it(page_res); WERD_RES* word_res; for (word_res = page_res_it.word(); word_res != NULL; word_res = page_res_it.forward()) { if (!word_res->box_word->bounding_box().major_overlap(box)) continue; if (applybox_debug > 1) { tprintf("Checking word box:"); word_res->box_word->bounding_box().print(); } int word_len = word_res->box_word->length(); for (int i = 0; i < word_len; ++i) { TBOX char_box = TBOX(); int blob_count = 0; for (blob_count = 0; i + blob_count < word_len; ++blob_count) { TBOX blob_box = word_res->box_word->BlobBox(i + blob_count); if (!blob_box.major_overlap(box)) break; if (word_res->correct_text[i + blob_count].length() > 0) break; // Blob is claimed already. double current_box_miss_metric = BoxMissMetric(blob_box, box); double next_box_miss_metric = BoxMissMetric(blob_box, next_box); if (applybox_debug > 2) { tprintf("Checking blob:"); blob_box.print(); tprintf("Current miss metric = %g, next = %g\n", current_box_miss_metric, next_box_miss_metric); } if (current_box_miss_metric > next_box_miss_metric) break; // Blob is a better match for next box. char_box += blob_box; } if (blob_count > 0) { if (applybox_debug > 1) { tprintf("Index [%d, %d) seem good.\n", i, i + blob_count); } if (!char_box.almost_equal(box, 3) && (box.x_gap(next_box) < -3 || (prev_box != NULL && prev_box->x_gap(box) < -3))) { return false; } // We refine just the box_word, best_state and correct_text here. // The rebuild_word is made in TidyUp. // blob_count blobs are put together to match the box. Merge the // box_word boxes, save the blob_count in the state and the text. word_res->box_word->MergeBoxes(i, i + blob_count); word_res->best_state[i] = blob_count; word_res->correct_text[i] = correct_text; if (applybox_debug > 2) { tprintf("%d Blobs match: blob box:", blob_count); word_res->box_word->BlobBox(i).print(); tprintf("Matches box:"); box.print(); tprintf("With next box:"); next_box.print(); } // Eliminated best_state and correct_text entries for the consumed // blobs. for (int j = 1; j < blob_count; ++j) { word_res->best_state.remove(i + 1); word_res->correct_text.remove(i + 1); } // Assume that no box spans multiple source words, so we are done with // this box. if (applybox_debug > 1) { tprintf("Best state = "); for (int j = 0; j < word_res->best_state.size(); ++j) { tprintf("%d ", word_res->best_state[j]); } tprintf("\n"); tprintf("Correct text = [[ "); for (int j = 0; j < word_res->correct_text.size(); ++j) { tprintf("%s ", word_res->correct_text[j].string()); } tprintf("]]\n"); } return true; } } } if (applybox_debug > 0) { tprintf("FAIL!\n"); } return false; // Failure. } // Consume all source blobs that strongly overlap the given box, // putting them into a new word, with the correct_text label. // Fights over which box owns which blobs are settled by // applying the blobs to box or next_box with the least non-overlap. // Returns false if the box was in error, which can only be caused by // failing to find an overlapping blob for a box. bool Tesseract::ResegmentWordBox(BLOCK_LIST *block_list, const TBOX& box, const TBOX& next_box, const char* correct_text) { if (applybox_debug > 1) { tprintf("\nAPPLY_BOX: in ResegmentWordBox() for %s\n", correct_text); } WERD* new_word = NULL; BLOCK_IT b_it(block_list); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { BLOCK* block = b_it.data(); if (!box.major_overlap(block->bounding_box())) continue; ROW_IT r_it(block->row_list()); for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) { ROW* row = r_it.data(); if (!box.major_overlap(row->bounding_box())) continue; WERD_IT w_it(row->word_list()); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD* word = w_it.data(); if (applybox_debug > 2) { tprintf("Checking word:"); word->bounding_box().print(); } if (word->text() != NULL && word->text()[0] != '\0') continue; // Ignore words that are already done. if (!box.major_overlap(word->bounding_box())) continue; C_BLOB_IT blob_it(word->cblob_list()); for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { C_BLOB* blob = blob_it.data(); TBOX blob_box = blob->bounding_box(); if (!blob_box.major_overlap(box)) continue; double current_box_miss_metric = BoxMissMetric(blob_box, box); double next_box_miss_metric = BoxMissMetric(blob_box, next_box); if (applybox_debug > 2) { tprintf("Checking blob:"); blob_box.print(); tprintf("Current miss metric = %g, next = %g\n", current_box_miss_metric, next_box_miss_metric); } if (current_box_miss_metric > next_box_miss_metric) continue; // Blob is a better match for next box. if (applybox_debug > 2) { tprintf("Blob match: blob:"); blob_box.print(); tprintf("Matches box:"); box.print(); tprintf("With next box:"); next_box.print(); } if (new_word == NULL) { // Make a new word with a single blob. new_word = word->shallow_copy(); new_word->set_text(correct_text); w_it.add_to_end(new_word); } C_BLOB_IT new_blob_it(new_word->cblob_list()); new_blob_it.add_to_end(blob_it.extract()); } } } } if (new_word == NULL && applybox_debug > 0) tprintf("FAIL!\n"); return new_word != NULL; } // Resegments the words by running the classifier in an attempt to find the // correct segmentation that produces the required string. void Tesseract::ReSegmentByClassification(PAGE_RES* page_res) { PAGE_RES_IT pr_it(page_res); WERD_RES* word_res; for (; (word_res = pr_it.word()) != NULL; pr_it.forward()) { WERD* word = word_res->word; if (word->text() == NULL || word->text()[0] == '\0') continue; // Ignore words that have no text. // Convert the correct text to a vector of UNICHAR_ID GenericVector<UNICHAR_ID> target_text; if (!ConvertStringToUnichars(word->text(), &target_text)) { tprintf("APPLY_BOX: FAILURE: can't find class_id for '%s'\n", word->text()); pr_it.DeleteCurrentWord(); continue; } if (!FindSegmentation(target_text, word_res)) { tprintf("APPLY_BOX: FAILURE: can't find segmentation for '%s'\n", word->text()); pr_it.DeleteCurrentWord(); continue; } } } // Converts the space-delimited string of utf8 text to a vector of UNICHAR_ID. // Returns false if an invalid UNICHAR_ID is encountered. bool Tesseract::ConvertStringToUnichars(const char* utf8, GenericVector<UNICHAR_ID>* class_ids) { for (int step = 0; *utf8 != '\0'; utf8 += step) { const char* next_space = strchr(utf8, ' '); if (next_space == NULL) next_space = utf8 + strlen(utf8); step = next_space - utf8; UNICHAR_ID class_id = unicharset.unichar_to_id(utf8, step); if (class_id == INVALID_UNICHAR_ID) { return false; } while (utf8[step] == ' ') ++step; class_ids->push_back(class_id); } return true; } // Resegments the word to achieve the target_text from the classifier. // Returns false if the re-segmentation fails. // Uses brute-force combination of up to kMaxGroupSize adjacent blobs, and // applies a full search on the classifier results to find the best classified // segmentation. As a compromise to obtain better recall, 1-1 ambiguity // substitutions ARE used. bool Tesseract::FindSegmentation(const GenericVector<UNICHAR_ID>& target_text, WERD_RES* word_res) { // Classify all required combinations of blobs and save results in choices. int word_length = word_res->box_word->length(); GenericVector<BLOB_CHOICE_LIST*>* choices = new GenericVector<BLOB_CHOICE_LIST*>[word_length]; for (int i = 0; i < word_length; ++i) { for (int j = 1; j <= kMaxGroupSize && i + j <= word_length; ++j) { BLOB_CHOICE_LIST* match_result = classify_piece( word_res->seam_array, i, i + j - 1, "Applybox", word_res->chopped_word, word_res->blamer_bundle); if (applybox_debug > 2) { tprintf("%d+%d:", i, j); print_ratings_list("Segment:", match_result, unicharset); } choices[i].push_back(match_result); } } // Search the segmentation graph for the target text. Must be an exact // match. Using wildcards makes it difficult to find the correct // segmentation even when it is there. word_res->best_state.clear(); GenericVector<int> search_segmentation; float best_rating = 0.0f; SearchForText(choices, 0, word_length, target_text, 0, 0.0f, &search_segmentation, &best_rating, &word_res->best_state); for (int i = 0; i < word_length; ++i) choices[i].delete_data_pointers(); delete [] choices; if (word_res->best_state.empty()) { // Build the original segmentation and if it is the same length as the // truth, assume it will do. int blob_count = 1; for (int s = 0; s < word_res->seam_array.size(); ++s) { SEAM* seam = word_res->seam_array[s]; if (seam->split1 == NULL) { word_res->best_state.push_back(blob_count); blob_count = 1; } else { ++blob_count; } } word_res->best_state.push_back(blob_count); if (word_res->best_state.size() != target_text.size()) { word_res->best_state.clear(); // No good. Original segmentation bad size. return false; } } word_res->correct_text.clear(); for (int i = 0; i < target_text.size(); ++i) { word_res->correct_text.push_back( STRING(unicharset.id_to_unichar(target_text[i]))); } return true; } // Recursive helper to find a match to the target_text (from text_index // position) in the choices (from choices_pos position). // Choices is an array of GenericVectors, of length choices_length, with each // element representing a starting position in the word, and the // GenericVector holding classification results for a sequence of consecutive // blobs, with index 0 being a single blob, index 1 being 2 blobs etc. void Tesseract::SearchForText(const GenericVector<BLOB_CHOICE_LIST*>* choices, int choices_pos, int choices_length, const GenericVector<UNICHAR_ID>& target_text, int text_index, float rating, GenericVector<int>* segmentation, float* best_rating, GenericVector<int>* best_segmentation) { const UnicharAmbigsVector& table = getDict().getUnicharAmbigs().dang_ambigs(); for (int length = 1; length <= choices[choices_pos].size(); ++length) { // Rating of matching choice or worst choice if no match. float choice_rating = 0.0f; // Find the corresponding best BLOB_CHOICE. BLOB_CHOICE_IT choice_it(choices[choices_pos][length - 1]); for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) { BLOB_CHOICE* choice = choice_it.data(); choice_rating = choice->rating(); UNICHAR_ID class_id = choice->unichar_id(); if (class_id == target_text[text_index]) { break; } // Search ambigs table. if (class_id < table.size() && table[class_id] != NULL) { AmbigSpec_IT spec_it(table[class_id]); for (spec_it.mark_cycle_pt(); !spec_it.cycled_list(); spec_it.forward()) { const AmbigSpec *ambig_spec = spec_it.data(); // We'll only do 1-1. if (ambig_spec->wrong_ngram[1] == INVALID_UNICHAR_ID && ambig_spec->correct_ngram_id == target_text[text_index]) break; } if (!spec_it.cycled_list()) break; // Found an ambig. } } if (choice_it.cycled_list()) continue; // No match. segmentation->push_back(length); if (choices_pos + length == choices_length && text_index + 1 == target_text.size()) { // This is a complete match. If the rating is good record a new best. if (applybox_debug > 2) { tprintf("Complete match, rating = %g, best=%g, seglength=%d, best=%d\n", rating + choice_rating, *best_rating, segmentation->size(), best_segmentation->size()); } if (best_segmentation->empty() || rating + choice_rating < *best_rating) { *best_segmentation = *segmentation; *best_rating = rating + choice_rating; } } else if (choices_pos + length < choices_length && text_index + 1 < target_text.size()) { if (applybox_debug > 3) { tprintf("Match found for %d=%s:%s, at %d+%d, recursing...\n", target_text[text_index], unicharset.id_to_unichar(target_text[text_index]), choice_it.data()->unichar_id() == target_text[text_index] ? "Match" : "Ambig", choices_pos, length); } SearchForText(choices, choices_pos + length, choices_length, target_text, text_index + 1, rating + choice_rating, segmentation, best_rating, best_segmentation); if (applybox_debug > 3) { tprintf("End recursion for %d=%s\n", target_text[text_index], unicharset.id_to_unichar(target_text[text_index])); } } segmentation->truncate(segmentation->size() - 1); } } // Counts up the labelled words and the blobs within. // Deletes all unused or emptied words, counting the unused ones. // Resets W_BOL and W_EOL flags correctly. // Builds the rebuild_word and rebuilds the box_word and the best_choice. void Tesseract::TidyUp(PAGE_RES* page_res) { int ok_blob_count = 0; int bad_blob_count = 0; int ok_word_count = 0; int unlabelled_words = 0; PAGE_RES_IT pr_it(page_res); WERD_RES* word_res; for (; (word_res = pr_it.word()) != NULL; pr_it.forward()) { int ok_in_word = 0; int blob_count = word_res->correct_text.size(); WERD_CHOICE* word_choice = new WERD_CHOICE(word_res->uch_set, blob_count); word_choice->set_permuter(TOP_CHOICE_PERM); for (int c = 0; c < blob_count; ++c) { if (word_res->correct_text[c].length() > 0) { ++ok_in_word; } // Since we only need a fake word_res->best_choice, the actual // unichar_ids do not matter. Which is fortunate, since TidyUp() // can be called while training Tesseract, at the stage where // unicharset is not meaningful yet. word_choice->append_unichar_id_space_allocated( INVALID_UNICHAR_ID, word_res->best_state[c], 1.0f, -1.0f); } if (ok_in_word > 0) { ok_blob_count += ok_in_word; bad_blob_count += word_res->correct_text.size() - ok_in_word; word_res->LogNewRawChoice(word_choice); word_res->LogNewCookedChoice(1, false, word_choice); } else { ++unlabelled_words; if (applybox_debug > 0) { tprintf("APPLY_BOXES: Unlabelled word at :"); word_res->word->bounding_box().print(); } pr_it.DeleteCurrentWord(); delete word_choice; } } pr_it.restart_page(); for (; (word_res = pr_it.word()) != NULL; pr_it.forward()) { // Denormalize back to a BoxWord. word_res->RebuildBestState(); word_res->SetupBoxWord(); word_res->word->set_flag(W_BOL, pr_it.prev_row() != pr_it.row()); word_res->word->set_flag(W_EOL, pr_it.next_row() != pr_it.row()); } if (applybox_debug > 0) { tprintf(" Found %d good blobs.\n", ok_blob_count); if (bad_blob_count > 0) { tprintf(" Leaving %d unlabelled blobs in %d words.\n", bad_blob_count, ok_word_count); } if (unlabelled_words > 0) tprintf(" %d remaining unlabelled words deleted.\n", unlabelled_words); } } // Logs a bad box by line in the box file and box coords. void Tesseract::ReportFailedBox(int boxfile_lineno, TBOX box, const char *box_ch, const char *err_msg) { tprintf("APPLY_BOXES: boxfile line %d/%s ((%d,%d),(%d,%d)): %s\n", boxfile_lineno + 1, box_ch, box.left(), box.bottom(), box.right(), box.top(), err_msg); } // Creates a fake best_choice entry in each WERD_RES with the correct text. void Tesseract::CorrectClassifyWords(PAGE_RES* page_res) { PAGE_RES_IT pr_it(page_res); for (WERD_RES *word_res = pr_it.word(); word_res != NULL; word_res = pr_it.forward()) { WERD_CHOICE* choice = new WERD_CHOICE(word_res->uch_set, word_res->correct_text.size()); for (int i = 0; i < word_res->correct_text.size(); ++i) { // The part before the first space is the real ground truth, and the // rest is the bounding box location and page number. GenericVector<STRING> tokens; word_res->correct_text[i].split(' ', &tokens); UNICHAR_ID char_id = unicharset.unichar_to_id(tokens[0].string()); choice->append_unichar_id_space_allocated(char_id, word_res->best_state[i], 0.0f, 0.0f); } word_res->ClearWordChoices(); word_res->LogNewRawChoice(choice); word_res->LogNewCookedChoice(1, false, choice); } } // Calls LearnWord to extract features for labelled blobs within each word. // Features are written to the given filename. void Tesseract::ApplyBoxTraining(const STRING& filename, PAGE_RES* page_res) { PAGE_RES_IT pr_it(page_res); int word_count = 0; for (WERD_RES *word_res = pr_it.word(); word_res != NULL; word_res = pr_it.forward()) { LearnWord(filename.string(), word_res); ++word_count; } tprintf("Generated training data for %d words\n", word_count); } } // namespace tesseract
1080228-arabicocr11
ccmain/applybox.cpp
C++
asf20
33,203
/////////////////////////////////////////////////////////////////////// // File: osdetect.h // Description: Orientation and script detection. // Author: Samuel Charron // Ranjith Unnikrishnan // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCMAIN_OSDETECT_H__ #define TESSERACT_CCMAIN_OSDETECT_H__ #include "strngs.h" #include "unicharset.h" class TO_BLOCK_LIST; class BLOBNBOX; class BLOB_CHOICE_LIST; class BLOBNBOX_CLIST; namespace tesseract { class Tesseract; } // Max number of scripts in ICU + "NULL" + Japanese and Korean + Fraktur const int kMaxNumberOfScripts = 116 + 1 + 2 + 1; struct OSBestResult { OSBestResult() : orientation_id(0), script_id(0), sconfidence(0.0), oconfidence(0.0) {} int orientation_id; int script_id; float sconfidence; float oconfidence; }; struct OSResults { OSResults() : unicharset(NULL) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < kMaxNumberOfScripts; ++j) scripts_na[i][j] = 0; orientations[i] = 0; } } void update_best_orientation(); // Set the estimate of the orientation to the given id. void set_best_orientation(int orientation_id); // Update/Compute the best estimate of the script assuming the given // orientation id. void update_best_script(int orientation_id); // Return the index of the script with the highest score for this orientation. TESS_API int get_best_script(int orientation_id) const; // Accumulate scores with given OSResults instance and update the best script. void accumulate(const OSResults& osr); // Print statistics. void print_scores(void) const; void print_scores(int orientation_id) const; // Array holding scores for each orientation id [0,3]. // Orientation ids [0..3] map to [0, 270, 180, 90] degree orientations of the // page respectively, where the values refer to the amount of clockwise // rotation to be applied to the page for the text to be upright and readable. float orientations[4]; // Script confidence scores for each of 4 possible orientations. float scripts_na[4][kMaxNumberOfScripts]; UNICHARSET* unicharset; OSBestResult best_result; }; class OrientationDetector { public: OrientationDetector(const GenericVector<int>* allowed_scripts, OSResults* results); bool detect_blob(BLOB_CHOICE_LIST* scores); int get_orientation(); private: OSResults* osr_; tesseract::Tesseract* tess_; const GenericVector<int>* allowed_scripts_; }; class ScriptDetector { public: ScriptDetector(const GenericVector<int>* allowed_scripts, OSResults* osr, tesseract::Tesseract* tess); void detect_blob(BLOB_CHOICE_LIST* scores); bool must_stop(int orientation); private: OSResults* osr_; static const char* korean_script_; static const char* japanese_script_; static const char* fraktur_script_; int korean_id_; int japanese_id_; int katakana_id_; int hiragana_id_; int han_id_; int hangul_id_; int latin_id_; int fraktur_id_; tesseract::Tesseract* tess_; const GenericVector<int>* allowed_scripts_; }; int orientation_and_script_detection(STRING& filename, OSResults*, tesseract::Tesseract*); int os_detect(TO_BLOCK_LIST* port_blocks, OSResults* osr, tesseract::Tesseract* tess); int os_detect_blobs(const GenericVector<int>* allowed_scripts, BLOBNBOX_CLIST* blob_list, OSResults* osr, tesseract::Tesseract* tess); bool os_detect_blob(BLOBNBOX* bbox, OrientationDetector* o, ScriptDetector* s, OSResults*, tesseract::Tesseract* tess); // Helper method to convert an orientation index to its value in degrees. // The value represents the amount of clockwise rotation in degrees that must be // applied for the text to be upright (readable). TESS_API const int OrientationIdToValue(const int& id); #endif // TESSERACT_CCMAIN_OSDETECT_H__
1080228-arabicocr11
ccmain/osdetect.h
C++
asf20
4,677
/////////////////////////////////////////////////////////////////////// // File: thresholder.h // Description: Base API for thresolding images in tesseract. // Author: Ray Smith // Created: Mon May 12 11:00:15 PDT 2008 // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCMAIN_THRESHOLDER_H__ #define TESSERACT_CCMAIN_THRESHOLDER_H__ #include "platform.h" #include "publictypes.h" struct Pix; namespace tesseract { /// Base class for all tesseract image thresholding classes. /// Specific classes can add new thresholding methods by /// overriding ThresholdToPix. /// Each instance deals with a single image, but the design is intended to /// be useful for multiple calls to SetRectangle and ThresholdTo* if /// desired. class TESS_API ImageThresholder { public: ImageThresholder(); virtual ~ImageThresholder(); /// Destroy the Pix if there is one, freeing memory. virtual void Clear(); /// Return true if no image has been set. bool IsEmpty() const; /// SetImage makes a copy of all the image data, so it may be deleted /// immediately after this call. /// Greyscale of 8 and color of 24 or 32 bits per pixel may be given. /// Palette color images will not work properly and must be converted to /// 24 bit. /// Binary images of 1 bit per pixel may also be given but they must be /// byte packed with the MSB of the first byte being the first pixel, and a /// one pixel is WHITE. For binary images set bytes_per_pixel=0. void SetImage(const unsigned char* imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line); /// Store the coordinates of the rectangle to process for later use. /// Doesn't actually do any thresholding. void SetRectangle(int left, int top, int width, int height); /// Get enough parameters to be able to rebuild bounding boxes in the /// original image (not just within the rectangle). /// Left and top are enough with top-down coordinates, but /// the height of the rectangle and the image are needed for bottom-up. virtual void GetImageSizes(int* left, int* top, int* width, int* height, int* imagewidth, int* imageheight); /// Return true if the source image is color. bool IsColor() const { return pix_channels_ >= 3; } /// Returns true if the source image is binary. bool IsBinary() const { return pix_channels_ == 0; } int GetScaleFactor() const { return scale_; } // Set the resolution of the source image in pixels per inch. // This should be called right after SetImage(), and will let us return // appropriate font sizes for the text. void SetSourceYResolution(int ppi) { yres_ = ppi; estimated_res_ = ppi; } int GetSourceYResolution() const { return yres_; } int GetScaledYResolution() const { return scale_ * yres_; } // Set the resolution of the source image in pixels per inch, as estimated // by the thresholder from the text size found during thresholding. // This value will be used to set internal size thresholds during recognition // and will not influence the output "point size." The default value is // the same as the source resolution. (yres_) void SetEstimatedResolution(int ppi) { estimated_res_ = ppi; } // Returns the estimated resolution, including any active scaling. // This value will be used to set internal size thresholds during recognition. int GetScaledEstimatedResolution() const { return scale_ * estimated_res_; } /// Pix vs raw, which to use? Pix is the preferred input for efficiency, /// since raw buffers are copied. /// SetImage for Pix clones its input, so the source pix may be pixDestroyed /// immediately after, but may not go away until after the Thresholder has /// finished with it. void SetImage(const Pix* pix); /// Threshold the source image as efficiently as possible to the output Pix. /// Creates a Pix and sets pix to point to the resulting pointer. /// Caller must use pixDestroy to free the created Pix. virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix** pix); // Gets a pix that contains an 8 bit threshold value at each pixel. The // returned pix may be an integer reduction of the binary image such that // the scale factor may be inferred from the ratio of the sizes, even down // to the extreme of a 1x1 pixel thresholds image. // Ideally the 8 bit threshold should be the exact threshold used to generate // the binary image in ThresholdToPix, but this is not a hard constraint. // Returns NULL if the input is binary. PixDestroy after use. virtual Pix* GetPixRectThresholds(); /// Get a clone/copy of the source image rectangle. /// The returned Pix must be pixDestroyed. /// This function will be used in the future by the page layout analysis, and /// the layout analysis that uses it will only be available with Leptonica, /// so there is no raw equivalent. Pix* GetPixRect(); // Get a clone/copy of the source image rectangle, reduced to greyscale, // and at the same resolution as the output binary. // The returned Pix must be pixDestroyed. // Provided to the classifier to extract features from the greyscale image. virtual Pix* GetPixRectGrey(); protected: // ---------------------------------------------------------------------- // Utility functions that may be useful components for other thresholders. /// Common initialization shared between SetImage methods. virtual void Init(); /// Return true if we are processing the full image. bool IsFullImage() const { return rect_left_ == 0 && rect_top_ == 0 && rect_width_ == image_width_ && rect_height_ == image_height_; } // Otsu thresholds the rectangle, taking the rectangle from *this. void OtsuThresholdRectToPix(Pix* src_pix, Pix** out_pix) const; /// Threshold the rectangle, taking everything except the src_pix /// from the class, using thresholds/hi_values to the output pix. /// NOTE that num_channels is the size of the thresholds and hi_values // arrays and also the bytes per pixel in src_pix. void ThresholdRectToPix(Pix* src_pix, int num_channels, const int* thresholds, const int* hi_values, Pix** pix) const; protected: /// Clone or other copy of the source Pix. /// The pix will always be PixDestroy()ed on destruction of the class. Pix* pix_; int image_width_; //< Width of source pix_. int image_height_; //< Height of source pix_. int pix_channels_; //< Number of 8-bit channels in pix_. int pix_wpl_; //< Words per line of pix_. // Limits of image rectangle to be processed. int scale_; //< Scale factor from original image. int yres_; //< y pixels/inch in source image. int estimated_res_; //< Resolution estimate from text size. int rect_left_; int rect_top_; int rect_width_; int rect_height_; }; } // namespace tesseract. #endif // TESSERACT_CCMAIN_THRESHOLDER_H__
1080228-arabicocr11
ccmain/thresholder.h
C++
asf20
7,847
AM_CPPFLAGS += \ -DUSE_STD_NAMESPACE \ -I$(top_srcdir)/ccutil -I$(top_srcdir)/ccstruct \ -I$(top_srcdir)/viewer \ -I$(top_srcdir)/classify -I$(top_srcdir)/dict \ -I$(top_srcdir)/wordrec -I$(top_srcdir)/cutil \ -I$(top_srcdir)/neural_networks/runtime -I$(top_srcdir)/cube \ -I$(top_srcdir)/textord -I$(top_srcdir)/opencl if USE_OPENCL AM_CPPFLAGS += -I$(OPENCL_HDR_PATH) endif if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS \ -fvisibility=hidden -fvisibility-inlines-hidden endif include_HEADERS = \ thresholder.h ltrresultiterator.h pageiterator.h resultiterator.h \ osdetect.h noinst_HEADERS = \ control.h cube_reco_context.h cubeclassifier.h docqual.h \ equationdetect.h fixspace.h mutableiterator.h \ output.h paragraphs.h paragraphs_internal.h paramsd.h pgedit.h \ reject.h tessbox.h tessedit.h tesseractclass.h \ tesseract_cube_combiner.h tessvars.h werdit.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_main.la else lib_LTLIBRARIES = libtesseract_main.la libtesseract_main_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_main_la_LIBADD = \ ../wordrec/libtesseract_wordrec.la \ ../textord/libtesseract_textord.la \ ../ccutil/libtesseract_ccutil.la \ ../ccstruct/libtesseract_ccstruct.la \ ../viewer/libtesseract_viewer.la \ ../dict/libtesseract_dict.la \ ../classify/libtesseract_classify.la \ ../cutil/libtesseract_cutil.la \ ../cube/libtesseract_cube.la \ ../opencl/libtesseract_opencl.la endif libtesseract_main_la_SOURCES = \ adaptions.cpp applybox.cpp \ control.cpp cube_control.cpp cube_reco_context.cpp cubeclassifier.cpp \ docqual.cpp equationdetect.cpp fixspace.cpp fixxht.cpp \ ltrresultiterator.cpp \ osdetect.cpp output.cpp pageiterator.cpp pagesegmain.cpp \ pagewalk.cpp par_control.cpp paragraphs.cpp paramsd.cpp pgedit.cpp recogtraining.cpp \ reject.cpp resultiterator.cpp superscript.cpp \ tesseract_cube_combiner.cpp \ tessbox.cpp tessedit.cpp tesseractclass.cpp tessvars.cpp \ tfacepp.cpp thresholder.cpp \ werdit.cpp
1080228-arabicocr11
ccmain/Makefile.am
Makefile
asf20
2,087
/////////////////////////////////////////////////////////////////////// // 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 "unichar.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. const void *GetParamsTrainingBundle() const; // Returns a pointer to the string with blamer information for this word. // Assumes that the word's blamer_bundle is not NULL. 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 true if a truth string was recorded for the current word. bool HasTruthString() const; // Returns true if the given string is equivalent to the truth string for // the current word. bool EquivalentToTruth(const char *str) const; // Returns a null terminated UTF-8 encoded truth string for the current word. // Use delete [] to free after use. char* WordTruthUTF8Text() const; // Returns a null terminated UTF-8 encoded normalized OCR string for the // current word. Use delete [] to free after use. char* WordNormedUTF8Text() const; // Returns a pointer to serialized choice lattice. // Fills lattice_size with the number of bytes in lattice data. const char *WordLattice(int *lattice_size) const; // ============= 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__
1080228-arabicocr11
ccmain/ltrresultiterator.h
C++
asf20
9,235
/********************************************************************** * File: reject.cpp (Formerly reject.c) * Description: Rejection functions used in tessedit * Author: Phil Cheatle * Created: Wed Sep 23 16:50:21 BST 1992 * * (C) Copyright 1992, 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. * **********************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4244) // Conversion warnings #pragma warning(disable:4305) // int/float warnings #endif #include "tessvars.h" #ifdef __UNIX__ #include <assert.h> #include <errno.h> #endif #include "scanutils.h" #include <ctype.h> #include <string.h> #include "genericvector.h" #include "reject.h" #include "control.h" #include "docqual.h" #include "globaloc.h" // For err_exit. #include "globals.h" #include "helpers.h" #include "tesseractclass.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif CLISTIZEH (STRING) CLISTIZE (STRING) /************************************************************************* * set_done() * * Set the done flag based on the word acceptability criteria *************************************************************************/ namespace tesseract { void Tesseract::set_done(WERD_RES *word, inT16 pass) { word->done = word->tess_accepted && (strchr(word->best_choice->unichar_string().string(), ' ') == NULL); bool word_is_ambig = word->best_choice->dangerous_ambig_found(); bool word_from_dict = word->best_choice->permuter() == SYSTEM_DAWG_PERM || word->best_choice->permuter() == FREQ_DAWG_PERM || word->best_choice->permuter() == USER_DAWG_PERM; if (word->done && (pass == 1) && (!word_from_dict || word_is_ambig) && one_ell_conflict(word, FALSE)) { if (tessedit_rejection_debug) tprintf("one_ell_conflict detected\n"); word->done = FALSE; } if (word->done && ((!word_from_dict && word->best_choice->permuter() != NUMBER_PERM) || word_is_ambig)) { if (tessedit_rejection_debug) tprintf("non-dict or ambig word detected\n"); word->done = FALSE; } if (tessedit_rejection_debug) { tprintf("set_done(): done=%d\n", word->done); word->best_choice->print(""); } } /************************************************************************* * make_reject_map() * * Sets the done flag to indicate whether the resylt is acceptable. * * Sets a reject map for the word. *************************************************************************/ void Tesseract::make_reject_map(WERD_RES *word, ROW *row, inT16 pass) { int i; int offset; flip_0O(word); check_debug_pt(word, -1); // For trap only set_done(word, pass); // Set acceptance word->reject_map.initialise(word->best_choice->unichar_lengths().length()); reject_blanks(word); /* 0: Rays original heuristic - the baseline */ if (tessedit_reject_mode == 0) { if (!word->done) reject_poor_matches(word); } else if (tessedit_reject_mode == 5) { /* 5: Reject I/1/l from words where there is no strong contextual confirmation; the whole of any unacceptable words (incl PERM rej of dubious 1/I/ls); and the whole of any words which are very small */ if (kBlnXHeight / word->denorm.y_scale() <= min_sane_x_ht_pixels) { word->reject_map.rej_word_small_xht(); } else { one_ell_conflict(word, TRUE); /* Originally the code here just used the done flag. Now I have duplicated and unpacked the conditions for setting the done flag so that each mechanism can be turned on or off independently. This works WITHOUT affecting the done flag setting. */ if (rej_use_tess_accepted && !word->tess_accepted) word->reject_map.rej_word_not_tess_accepted (); if (rej_use_tess_blanks && (strchr (word->best_choice->unichar_string().string (), ' ') != NULL)) word->reject_map.rej_word_contains_blanks (); WERD_CHOICE* best_choice = word->best_choice; if (rej_use_good_perm) { if ((best_choice->permuter() == SYSTEM_DAWG_PERM || best_choice->permuter() == FREQ_DAWG_PERM || best_choice->permuter() == USER_DAWG_PERM) && (!rej_use_sensible_wd || acceptable_word_string(*word->uch_set, best_choice->unichar_string().string(), best_choice->unichar_lengths().string()) != AC_UNACCEPTABLE)) { // PASSED TEST } else if (best_choice->permuter() == NUMBER_PERM) { if (rej_alphas_in_number_perm) { for (i = 0, offset = 0; best_choice->unichar_string()[offset] != '\0'; offset += best_choice->unichar_lengths()[i++]) { if (word->reject_map[i].accepted() && word->uch_set->get_isalpha( best_choice->unichar_string().string() + offset, best_choice->unichar_lengths()[i])) word->reject_map[i].setrej_bad_permuter(); // rej alpha } } } else { word->reject_map.rej_word_bad_permuter(); } } /* Ambig word rejection was here once !!*/ } } else { tprintf("BAD tessedit_reject_mode\n"); err_exit(); } if (tessedit_image_border > -1) reject_edge_blobs(word); check_debug_pt (word, 10); if (tessedit_rejection_debug) { tprintf("Permuter Type = %d\n", word->best_choice->permuter ()); tprintf("Certainty: %f Rating: %f\n", word->best_choice->certainty (), word->best_choice->rating ()); tprintf("Dict word: %d\n", dict_word(*(word->best_choice))); } flip_hyphens(word); check_debug_pt(word, 20); } } // namespace tesseract void reject_blanks(WERD_RES *word) { inT16 i; inT16 offset; for (i = 0, offset = 0; word->best_choice->unichar_string()[offset] != '\0'; offset += word->best_choice->unichar_lengths()[i], i += 1) { if (word->best_choice->unichar_string()[offset] == ' ') //rej unrecognised blobs word->reject_map[i].setrej_tess_failure (); } } namespace tesseract { void Tesseract::reject_I_1_L(WERD_RES *word) { inT16 i; inT16 offset; for (i = 0, offset = 0; word->best_choice->unichar_string()[offset] != '\0'; offset += word->best_choice->unichar_lengths()[i], i += 1) { if (STRING (conflict_set_I_l_1). contains (word->best_choice->unichar_string()[offset])) { //rej 1Il conflict word->reject_map[i].setrej_1Il_conflict (); } } } } // namespace tesseract void reject_poor_matches(WERD_RES *word) { float threshold = compute_reject_threshold(word->best_choice); for (int i = 0; i < word->best_choice->length(); ++i) { if (word->best_choice->unichar_id(i) == UNICHAR_SPACE) word->reject_map[i].setrej_tess_failure(); else if (word->best_choice->certainty(i) < threshold) word->reject_map[i].setrej_poor_match(); } } /********************************************************************** * compute_reject_threshold * * Set a rejection threshold for this word. * Initially this is a trivial function which looks for the largest * gap in the certainty value. **********************************************************************/ float compute_reject_threshold(WERD_CHOICE* word) { float threshold; // rejection threshold float bestgap = 0.0f; // biggest gap float gapstart; // bottom of gap // super iterator BLOB_CHOICE_IT choice_it; // real iterator int blob_count = word->length(); GenericVector<float> ratings; ratings.init_to_size(blob_count, 0.0f); for (int i = 0; i < blob_count; ++i) { ratings[i] = word->certainty(i); } ratings.sort(); gapstart = ratings[0] - 1; // all reject if none better if (blob_count >= 3) { for (int index = 0; index < blob_count - 1; index++) { if (ratings[index + 1] - ratings[index] > bestgap) { bestgap = ratings[index + 1] - ratings[index]; // find biggest gapstart = ratings[index]; } } } threshold = gapstart + bestgap / 2; return threshold; } /************************************************************************* * reject_edge_blobs() * * If the word is perilously close to the edge of the image, reject those blobs * in the word which are too close to the edge as they could be clipped. *************************************************************************/ namespace tesseract { void Tesseract::reject_edge_blobs(WERD_RES *word) { TBOX word_box = word->word->bounding_box(); // Use the box_word as it is already denormed back to image coordinates. int blobcount = word->box_word->length(); if (word_box.left() < tessedit_image_border || word_box.bottom() < tessedit_image_border || word_box.right() + tessedit_image_border > ImageWidth() - 1 || word_box.top() + tessedit_image_border > ImageHeight() - 1) { ASSERT_HOST(word->reject_map.length() == blobcount); for (int blobindex = 0; blobindex < blobcount; blobindex++) { TBOX blob_box = word->box_word->BlobBox(blobindex); if (blob_box.left() < tessedit_image_border || blob_box.bottom() < tessedit_image_border || blob_box.right() + tessedit_image_border > ImageWidth() - 1 || blob_box.top() + tessedit_image_border > ImageHeight() - 1) { word->reject_map[blobindex].setrej_edge_char(); // Close to edge } } } } /********************************************************************** * one_ell_conflict() * * Identify words where there is a potential I/l/1 error. * - A bundle of contextual heuristics! **********************************************************************/ BOOL8 Tesseract::one_ell_conflict(WERD_RES *word_res, BOOL8 update_map) { const char *word; const char *lengths; inT16 word_len; //its length inT16 first_alphanum_index_; inT16 first_alphanum_offset_; inT16 i; inT16 offset; BOOL8 non_conflict_set_char; //non conf set a/n? BOOL8 conflict = FALSE; BOOL8 allow_1s; ACCEPTABLE_WERD_TYPE word_type; BOOL8 dict_perm_type; BOOL8 dict_word_ok; int dict_word_type; word = word_res->best_choice->unichar_string().string (); lengths = word_res->best_choice->unichar_lengths().string(); word_len = strlen (lengths); /* If there are no occurrences of the conflict set characters then the word is OK. */ if (strpbrk (word, conflict_set_I_l_1.string ()) == NULL) return FALSE; /* There is a conflict if there are NO other (confirmed) alphanumerics apart from those in the conflict set. */ for (i = 0, offset = 0, non_conflict_set_char = FALSE; (i < word_len) && !non_conflict_set_char; offset += lengths[i++]) non_conflict_set_char = (word_res->uch_set->get_isalpha(word + offset, lengths[i]) || word_res->uch_set->get_isdigit(word + offset, lengths[i])) && !STRING (conflict_set_I_l_1).contains (word[offset]); if (!non_conflict_set_char) { if (update_map) reject_I_1_L(word_res); return TRUE; } /* If the word is accepted by a dawg permuter, and the first alpha character is "I" or "l", check to see if the alternative is also a dawg word. If it is, then there is a potential error otherwise the word is ok. */ dict_perm_type = (word_res->best_choice->permuter () == SYSTEM_DAWG_PERM) || (word_res->best_choice->permuter () == USER_DAWG_PERM) || (rej_trust_doc_dawg && (word_res->best_choice->permuter () == DOC_DAWG_PERM)) || (word_res->best_choice->permuter () == FREQ_DAWG_PERM); dict_word_type = dict_word(*(word_res->best_choice)); dict_word_ok = (dict_word_type > 0) && (rej_trust_doc_dawg || (dict_word_type != DOC_DAWG_PERM)); if ((rej_1Il_use_dict_word && dict_word_ok) || (rej_1Il_trust_permuter_type && dict_perm_type) || (dict_perm_type && dict_word_ok)) { first_alphanum_index_ = first_alphanum_index (word, lengths); first_alphanum_offset_ = first_alphanum_offset (word, lengths); if (lengths[first_alphanum_index_] == 1 && word[first_alphanum_offset_] == 'I') { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'l'; if (safe_dict_word(word_res) > 0) { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'I'; if (update_map) word_res->reject_map[first_alphanum_index_]. setrej_1Il_conflict(); return TRUE; } else { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'I'; return FALSE; } } if (lengths[first_alphanum_index_] == 1 && word[first_alphanum_offset_] == 'l') { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'I'; if (safe_dict_word(word_res) > 0) { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'l'; if (update_map) word_res->reject_map[first_alphanum_index_]. setrej_1Il_conflict(); return TRUE; } else { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'l'; return FALSE; } } return FALSE; } /* NEW 1Il code. The old code relied on permuter types too much. In fact, tess will use TOP_CHOICE permute for good things like "palette". In this code the string is examined independently to see if it looks like a well formed word. */ /* REGARDLESS OF PERMUTER, see if flipping a leading I/l generates a dictionary word. */ first_alphanum_index_ = first_alphanum_index (word, lengths); first_alphanum_offset_ = first_alphanum_offset (word, lengths); if (lengths[first_alphanum_index_] == 1 && word[first_alphanum_offset_] == 'l') { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'I'; if (safe_dict_word(word_res) > 0) return FALSE; else word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'l'; } else if (lengths[first_alphanum_index_] == 1 && word[first_alphanum_offset_] == 'I') { word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'l'; if (safe_dict_word(word_res) > 0) return FALSE; else word_res->best_choice->unichar_string()[first_alphanum_offset_] = 'I'; } /* For strings containing digits: If there are no alphas OR the numeric permuter liked the word, reject any non 1 conflict chs Else reject all conflict chs */ if (word_contains_non_1_digit (word, lengths)) { allow_1s = (alpha_count (word, lengths) == 0) || (word_res->best_choice->permuter () == NUMBER_PERM); inT16 offset; conflict = FALSE; for (i = 0, offset = 0; word[offset] != '\0'; offset += word_res->best_choice->unichar_lengths()[i++]) { if ((!allow_1s || (word[offset] != '1')) && STRING (conflict_set_I_l_1).contains (word[offset])) { if (update_map) word_res->reject_map[i].setrej_1Il_conflict (); conflict = TRUE; } } return conflict; } /* For anything else. See if it conforms to an acceptable word type. If so, treat accordingly. */ word_type = acceptable_word_string(*word_res->uch_set, word, lengths); if ((word_type == AC_LOWER_CASE) || (word_type == AC_INITIAL_CAP)) { first_alphanum_index_ = first_alphanum_index (word, lengths); first_alphanum_offset_ = first_alphanum_offset (word, lengths); if (STRING (conflict_set_I_l_1).contains (word[first_alphanum_offset_])) { if (update_map) word_res->reject_map[first_alphanum_index_]. setrej_1Il_conflict (); return TRUE; } else return FALSE; } else if (word_type == AC_UPPER_CASE) { return FALSE; } else { if (update_map) reject_I_1_L(word_res); return TRUE; } } inT16 Tesseract::first_alphanum_index(const char *word, const char *word_lengths) { inT16 i; inT16 offset; for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) { if (unicharset.get_isalpha(word + offset, word_lengths[i]) || unicharset.get_isdigit(word + offset, word_lengths[i])) return i; } return -1; } inT16 Tesseract::first_alphanum_offset(const char *word, const char *word_lengths) { inT16 i; inT16 offset; for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) { if (unicharset.get_isalpha(word + offset, word_lengths[i]) || unicharset.get_isdigit(word + offset, word_lengths[i])) return offset; } return -1; } inT16 Tesseract::alpha_count(const char *word, const char *word_lengths) { inT16 i; inT16 offset; inT16 count = 0; for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) { if (unicharset.get_isalpha (word + offset, word_lengths[i])) count++; } return count; } BOOL8 Tesseract::word_contains_non_1_digit(const char *word, const char *word_lengths) { inT16 i; inT16 offset; for (i = 0, offset = 0; word[offset] != '\0'; offset += word_lengths[i++]) { if (unicharset.get_isdigit (word + offset, word_lengths[i]) && (word_lengths[i] != 1 || word[offset] != '1')) return TRUE; } return FALSE; } /************************************************************************* * dont_allow_1Il() * Dont unreject LONE accepted 1Il conflict set chars *************************************************************************/ void Tesseract::dont_allow_1Il(WERD_RES *word) { int i = 0; int offset; int word_len = word->reject_map.length(); const char *s = word->best_choice->unichar_string().string(); const char *lengths = word->best_choice->unichar_lengths().string(); BOOL8 accepted_1Il = FALSE; for (i = 0, offset = 0; i < word_len; offset += word->best_choice->unichar_lengths()[i++]) { if (word->reject_map[i].accepted()) { if (STRING(conflict_set_I_l_1).contains(s[offset])) { accepted_1Il = TRUE; } else { if (word->uch_set->get_isalpha(s + offset, lengths[i]) || word->uch_set->get_isdigit(s + offset, lengths[i])) return; // >=1 non 1Il ch accepted } } } if (!accepted_1Il) return; //Nothing to worry about for (i = 0, offset = 0; i < word_len; offset += word->best_choice->unichar_lengths()[i++]) { if (STRING(conflict_set_I_l_1).contains(s[offset]) && word->reject_map[i].accepted()) word->reject_map[i].setrej_postNN_1Il(); } } inT16 Tesseract::count_alphanums(WERD_RES *word_res) { int count = 0; const WERD_CHOICE *best_choice = word_res->best_choice; for (int i = 0; i < word_res->reject_map.length(); ++i) { if ((word_res->reject_map[i].accepted()) && (word_res->uch_set->get_isalpha(best_choice->unichar_id(i)) || word_res->uch_set->get_isdigit(best_choice->unichar_id(i)))) { count++; } } return count; } // reject all if most rejected. void Tesseract::reject_mostly_rejects(WERD_RES *word) { /* Reject the whole of the word if the fraction of rejects exceeds a limit */ if ((float) word->reject_map.reject_count() / word->reject_map.length() >= rej_whole_of_mostly_reject_word_fract) word->reject_map.rej_word_mostly_rej(); } BOOL8 Tesseract::repeated_nonalphanum_wd(WERD_RES *word, ROW *row) { inT16 char_quality; inT16 accepted_char_quality; if (word->best_choice->unichar_lengths().length() <= 1) return FALSE; if (!STRING(ok_repeated_ch_non_alphanum_wds). contains(word->best_choice->unichar_string()[0])) return FALSE; UNICHAR_ID uch_id = word->best_choice->unichar_id(0); for (int i = 1; i < word->best_choice->length(); ++i) { if (word->best_choice->unichar_id(i) != uch_id) return FALSE; } word_char_quality(word, row, &char_quality, &accepted_char_quality); if ((word->best_choice->unichar_lengths().length () == char_quality) && (char_quality == accepted_char_quality)) return TRUE; else return FALSE; } inT16 Tesseract::safe_dict_word(const WERD_RES *werd_res) { const WERD_CHOICE &word = *werd_res->best_choice; int dict_word_type = werd_res->tesseract->dict_word(word); return dict_word_type == DOC_DAWG_PERM ? 0 : dict_word_type; } // Note: After running this function word_res->ratings // might not contain the right BLOB_CHOICE corresponding to each character // in word_res->best_choice. void Tesseract::flip_hyphens(WERD_RES *word_res) { WERD_CHOICE *best_choice = word_res->best_choice; int i; int prev_right = -9999; int next_left; TBOX out_box; float aspect_ratio; if (tessedit_lower_flip_hyphen <= 1) return; int num_blobs = word_res->rebuild_word->NumBlobs(); UNICHAR_ID unichar_dash = word_res->uch_set->unichar_to_id("-"); for (i = 0; i < best_choice->length() && i < num_blobs; ++i) { TBLOB* blob = word_res->rebuild_word->blobs[i]; out_box = blob->bounding_box(); if (i + 1 == num_blobs) next_left = 9999; else next_left = word_res->rebuild_word->blobs[i + 1]->bounding_box().left(); // Dont touch small or touching blobs - it is too dangerous. if ((out_box.width() > 8 * word_res->denorm.x_scale()) && (out_box.left() > prev_right) && (out_box.right() < next_left)) { aspect_ratio = out_box.width() / (float) out_box.height(); if (word_res->uch_set->eq(best_choice->unichar_id(i), ".")) { if (aspect_ratio >= tessedit_upper_flip_hyphen && word_res->uch_set->contains_unichar_id(unichar_dash) && word_res->uch_set->get_enabled(unichar_dash)) { /* Certain HYPHEN */ best_choice->set_unichar_id(unichar_dash, i); if (word_res->reject_map[i].rejected()) word_res->reject_map[i].setrej_hyphen_accept(); } if ((aspect_ratio > tessedit_lower_flip_hyphen) && word_res->reject_map[i].accepted()) //Suspected HYPHEN word_res->reject_map[i].setrej_hyphen (); } else if (best_choice->unichar_id(i) == unichar_dash) { if ((aspect_ratio >= tessedit_upper_flip_hyphen) && (word_res->reject_map[i].rejected())) word_res->reject_map[i].setrej_hyphen_accept(); //Certain HYPHEN if ((aspect_ratio <= tessedit_lower_flip_hyphen) && (word_res->reject_map[i].accepted())) //Suspected HYPHEN word_res->reject_map[i].setrej_hyphen(); } } prev_right = out_box.right(); } } // Note: After running this function word_res->ratings // might not contain the right BLOB_CHOICE corresponding to each character // in word_res->best_choice. void Tesseract::flip_0O(WERD_RES *word_res) { WERD_CHOICE *best_choice = word_res->best_choice; int i; TBOX out_box; if (!tessedit_flip_0O) return; int num_blobs = word_res->rebuild_word->NumBlobs(); for (i = 0; i < best_choice->length() && i < num_blobs; ++i) { TBLOB* blob = word_res->rebuild_word->blobs[i]; if (word_res->uch_set->get_isupper(best_choice->unichar_id(i)) || word_res->uch_set->get_isdigit(best_choice->unichar_id(i))) { out_box = blob->bounding_box(); if ((out_box.top() < kBlnBaselineOffset + kBlnXHeight) || (out_box.bottom() > kBlnBaselineOffset + kBlnXHeight / 4)) return; //Beware words with sub/superscripts } } UNICHAR_ID unichar_0 = word_res->uch_set->unichar_to_id("0"); UNICHAR_ID unichar_O = word_res->uch_set->unichar_to_id("O"); if (unichar_0 == INVALID_UNICHAR_ID || !word_res->uch_set->get_enabled(unichar_0) || unichar_O == INVALID_UNICHAR_ID || !word_res->uch_set->get_enabled(unichar_O)) { return; // 0 or O are not present/enabled in unicharset } for (i = 1; i < best_choice->length(); ++i) { if (best_choice->unichar_id(i) == unichar_0 || best_choice->unichar_id(i) == unichar_O) { /* A0A */ if ((i+1) < best_choice->length() && non_O_upper(*word_res->uch_set, best_choice->unichar_id(i-1)) && non_O_upper(*word_res->uch_set, best_choice->unichar_id(i+1))) { best_choice->set_unichar_id(unichar_O, i); } /* A00A */ if (non_O_upper(*word_res->uch_set, best_choice->unichar_id(i-1)) && (i+1) < best_choice->length() && (best_choice->unichar_id(i+1) == unichar_0 || best_choice->unichar_id(i+1) == unichar_O) && (i+2) < best_choice->length() && non_O_upper(*word_res->uch_set, best_choice->unichar_id(i+2))) { best_choice->set_unichar_id(unichar_O, i); i++; } /* AA0<non digit or end of word> */ if ((i > 1) && non_O_upper(*word_res->uch_set, best_choice->unichar_id(i-2)) && non_O_upper(*word_res->uch_set, best_choice->unichar_id(i-1)) && (((i+1) < best_choice->length() && !word_res->uch_set->get_isdigit(best_choice->unichar_id(i+1)) && !word_res->uch_set->eq(best_choice->unichar_id(i+1), "l") && !word_res->uch_set->eq(best_choice->unichar_id(i+1), "I")) || (i == best_choice->length() - 1))) { best_choice->set_unichar_id(unichar_O, i); } /* 9O9 */ if (non_0_digit(*word_res->uch_set, best_choice->unichar_id(i-1)) && (i+1) < best_choice->length() && non_0_digit(*word_res->uch_set, best_choice->unichar_id(i+1))) { best_choice->set_unichar_id(unichar_0, i); } /* 9OOO */ if (non_0_digit(*word_res->uch_set, best_choice->unichar_id(i-1)) && (i+2) < best_choice->length() && (best_choice->unichar_id(i+1) == unichar_0 || best_choice->unichar_id(i+1) == unichar_O) && (best_choice->unichar_id(i+2) == unichar_0 || best_choice->unichar_id(i+2) == unichar_O)) { best_choice->set_unichar_id(unichar_0, i); best_choice->set_unichar_id(unichar_0, i+1); best_choice->set_unichar_id(unichar_0, i+2); i += 2; } /* 9OO<non upper> */ if (non_0_digit(*word_res->uch_set, best_choice->unichar_id(i-1)) && (i+2) < best_choice->length() && (best_choice->unichar_id(i+1) == unichar_0 || best_choice->unichar_id(i+1) == unichar_O) && !word_res->uch_set->get_isupper(best_choice->unichar_id(i+2))) { best_choice->set_unichar_id(unichar_0, i); best_choice->set_unichar_id(unichar_0, i+1); i++; } /* 9O<non upper> */ if (non_0_digit(*word_res->uch_set, best_choice->unichar_id(i-1)) && (i+1) < best_choice->length() && !word_res->uch_set->get_isupper(best_choice->unichar_id(i+1))) { best_choice->set_unichar_id(unichar_0, i); } /* 9[.,]OOO.. */ if ((i > 1) && (word_res->uch_set->eq(best_choice->unichar_id(i-1), ".") || word_res->uch_set->eq(best_choice->unichar_id(i-1), ",")) && (word_res->uch_set->get_isdigit(best_choice->unichar_id(i-2)) || best_choice->unichar_id(i-2) == unichar_O)) { if (best_choice->unichar_id(i-2) == unichar_O) { best_choice->set_unichar_id(unichar_0, i-2); } while (i < best_choice->length() && (best_choice->unichar_id(i) == unichar_O || best_choice->unichar_id(i) == unichar_0)) { best_choice->set_unichar_id(unichar_0, i); i++; } i--; } } } } BOOL8 Tesseract::non_O_upper(const UNICHARSET& ch_set, UNICHAR_ID unichar_id) { return ch_set.get_isupper(unichar_id) && !ch_set.eq(unichar_id, "O"); } BOOL8 Tesseract::non_0_digit(const UNICHARSET& ch_set, UNICHAR_ID unichar_id) { return ch_set.get_isdigit(unichar_id) && !ch_set.eq(unichar_id, "0"); } } // namespace tesseract
1080228-arabicocr11
ccmain/reject.cpp
C++
asf20
28,968
/********************************************************************** * File: cube_reco_context.cpp * Description: Implementation of the Cube Recognition Context Class * Author: Ahmad Abdulkader * Created: 2007 * * (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. * **********************************************************************/ #include <string> #include <limits.h> #include "cube_reco_context.h" #include "classifier_factory.h" #include "cube_tuning_params.h" #include "dict.h" #include "feature_bmp.h" #include "tessdatamanager.h" #include "tesseractclass.h" #include "tess_lang_model.h" namespace tesseract { // Instantiate a CubeRecoContext object using a Tesseract object. // CubeRecoContext will not take ownership of tess_obj, but will // record the pointer to it and will make use of various Tesseract // components (language model, flags, etc). Thus the caller should // keep tess_obj alive so long as the instantiated CubeRecoContext is used. CubeRecoContext::CubeRecoContext(Tesseract *tess_obj) { tess_obj_ = tess_obj; lang_ = ""; loaded_ = false; lang_mod_ = NULL; params_ = NULL; char_classifier_ = NULL; char_set_ = NULL; word_size_model_ = NULL; char_bigrams_ = NULL; word_unigrams_ = NULL; noisy_input_ = false; size_normalization_ = false; } CubeRecoContext::~CubeRecoContext() { if (char_classifier_ != NULL) { delete char_classifier_; char_classifier_ = NULL; } if (word_size_model_ != NULL) { delete word_size_model_; word_size_model_ = NULL; } if (char_set_ != NULL) { delete char_set_; char_set_ = NULL; } if (char_bigrams_ != NULL) { delete char_bigrams_; char_bigrams_ = NULL; } if (word_unigrams_ != NULL) { delete word_unigrams_; word_unigrams_ = NULL; } if (lang_mod_ != NULL) { delete lang_mod_; lang_mod_ = NULL; } if (params_ != NULL) { delete params_; params_ = NULL; } } // Returns the path of the data files by looking up the TESSDATA_PREFIX // environment variable and appending a "tessdata" directory to it bool CubeRecoContext::GetDataFilePath(string *path) const { *path = tess_obj_->datadir.string(); return true; } // The object initialization function that loads all the necessary // components of a RecoContext. TessdataManager is used to load the // data from [lang].traineddata file. If TESSDATA_CUBE_UNICHARSET // component is present, Cube will be instantiated with the unicharset // specified in this component and the corresponding dictionary // (TESSDATA_CUBE_SYSTEM_DAWG), and will map Cube's unicharset to // Tesseract's. Otherwise, TessdataManager will assume that Cube will // be using Tesseract's unicharset and dawgs, and will load the // unicharset from the TESSDATA_UNICHARSET component and will load the // dawgs from TESSDATA_*_DAWG components. bool CubeRecoContext::Load(TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset) { ASSERT_HOST(tess_obj_ != NULL); tess_unicharset_ = tess_unicharset; string data_file_path; // Get the data file path. if (GetDataFilePath(&data_file_path) == false) { fprintf(stderr, "Unable to get data file path\n"); return false; } // Get the language from the Tesseract object. lang_ = tess_obj_->lang.string(); // Create the char set. if ((char_set_ = CharSet::Create(tessdata_manager, tess_unicharset)) == NULL) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Load): unable to load " "CharSet\n"); return false; } // Create the language model. string lm_file_name = data_file_path + lang_ + ".cube.lm"; string lm_params; if (!CubeUtils::ReadFileToString(lm_file_name, &lm_params)) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Load): unable to read cube " "language model params from %s\n", lm_file_name.c_str()); return false; } lang_mod_ = new TessLangModel(lm_params, data_file_path, tess_obj_->getDict().load_system_dawg, tessdata_manager, this); if (lang_mod_ == NULL) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Load): unable to create " "TessLangModel\n"); return false; } // Create the optional char bigrams object. char_bigrams_ = CharBigrams::Create(data_file_path, lang_); // Create the optional word unigrams object. word_unigrams_ = WordUnigrams::Create(data_file_path, lang_); // Create the optional size model. word_size_model_ = WordSizeModel::Create(data_file_path, lang_, char_set_, Contextual()); // Load tuning params. params_ = CubeTuningParams::Create(data_file_path, lang_); if (params_ == NULL) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Load): unable to read " "CubeTuningParams from %s\n", data_file_path.c_str()); return false; } // Create the char classifier. char_classifier_ = CharClassifierFactory::Create(data_file_path, lang_, lang_mod_, char_set_, params_); if (char_classifier_ == NULL) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Load): unable to load " "CharClassifierFactory object from %s\n", data_file_path.c_str()); return false; } loaded_ = true; return true; } // Creates a CubeRecoContext object using a tesseract object CubeRecoContext * CubeRecoContext::Create(Tesseract *tess_obj, TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset) { // create the object CubeRecoContext *cntxt = new CubeRecoContext(tess_obj); if (cntxt == NULL) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Create): unable to create " "CubeRecoContext object\n"); return NULL; } // load the necessary components if (cntxt->Load(tessdata_manager, tess_unicharset) == false) { fprintf(stderr, "Cube ERROR (CubeRecoContext::Create): unable to init " "CubeRecoContext object\n"); delete cntxt; return NULL; } // success return cntxt; } } // tesseract}
1080228-arabicocr11
ccmain/cube_reco_context.cpp
C++
asf20
6,733
/********************************************************************** * File: tessedit.h (Formerly tessedit.h) * Description: Main program for merge of tess and editor. * Author: Ray Smith * Created: Tue Jan 07 15:21:46 GMT 1992 * * (C) Copyright 1992, 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 TESSEDIT_H #define TESSEDIT_H #include "blobs.h" #include "pgedit.h" //progress monitor extern ETEXT_DESC *global_monitor; #endif
1080228-arabicocr11
ccmain/tessedit.h
C
asf20
1,135
/****************************************************************** * File: output.h (Formerly output.h) * Description: Output pass * Author: Phil Cheatle * Created: Thu Aug 4 10:56:08 BST 1994 * * (C) Copyright 1994, 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 OUTPUT_H #define OUTPUT_H #include "params.h" //#include "epapconv.h" #include "pageres.h" /** test line ends */ char determine_newline_type(WERD *word, ///< word to do BLOCK *block, ///< current block WERD *next_word, ///< next word BLOCK *next_block ///< block of next word ); #endif
1080228-arabicocr11
ccmain/output.h
C
asf20
1,384
/////////////////////////////////////////////////////////////////////// // File: tesseractclass.cpp // Description: The Tesseract class. It holds/owns everything needed // to run Tesseract on a single language, and also a set of // sub-Tesseracts to run sub-languages. For thread safety, *every* // variable that was previously global or static (except for // constant data, and some visual debugging flags) has been moved // in here, directly, or indirectly. // This makes it safe to run multiple Tesseracts in different // threads in parallel, and keeps the different language // instances separate. // Some global functions remain, but they are isolated re-entrant // functions that operate on their arguments. Functions that work // on variable data have been moved to an appropriate class based // mostly on the directory hierarchy. For more information see // slide 6 of "2ArchitectureAndDataStructures" in // https://drive.google.com/file/d/0B7l10Bj_LprhbUlIUFlCdGtDYkE/edit?usp=sharing // Some global data and related functions still exist in the // training-related code, but they don't interfere with normal // recognition operation. // Author: Ray Smith // Created: Fri Mar 07 08:17:01 PST 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. // /////////////////////////////////////////////////////////////////////// #include "tesseractclass.h" #include "allheaders.h" #include "cube_reco_context.h" #include "edgblob.h" #include "equationdetect.h" #include "globals.h" #include "tesseract_cube_combiner.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif namespace tesseract { Tesseract::Tesseract() : BOOL_MEMBER(tessedit_resegment_from_boxes, false, "Take segmentation and labeling from box file", this->params()), BOOL_MEMBER(tessedit_resegment_from_line_boxes, false, "Conversion of word/line box file to char box file", this->params()), BOOL_MEMBER(tessedit_train_from_boxes, false, "Generate training data from boxed chars", this->params()), BOOL_MEMBER(tessedit_make_boxes_from_boxes, false, "Generate more boxes from boxed chars", this->params()), BOOL_MEMBER(tessedit_dump_pageseg_images, false, "Dump intermediate images made during page segmentation", this->params()), // The default for pageseg_mode is the old behaviour, so as not to // upset anything that relies on that. INT_MEMBER(tessedit_pageseg_mode, PSM_SINGLE_BLOCK, "Page seg mode: 0=osd only, 1=auto+osd, 2=auto, 3=col, 4=block," " 5=line, 6=word, 7=char" " (Values from PageSegMode enum in publictypes.h)", this->params()), INT_INIT_MEMBER(tessedit_ocr_engine_mode, tesseract::OEM_TESSERACT_ONLY, "Which OCR engine(s) to run (Tesseract, Cube, both)." " Defaults to loading and running only Tesseract" " (no Cube,no combiner)." " Values from OcrEngineMode enum in tesseractclass.h)", this->params()), STRING_MEMBER(tessedit_char_blacklist, "", "Blacklist of chars not to recognize", this->params()), STRING_MEMBER(tessedit_char_whitelist, "", "Whitelist of chars to recognize", this->params()), STRING_MEMBER(tessedit_char_unblacklist, "", "List of chars to override tessedit_char_blacklist", this->params()), BOOL_MEMBER(tessedit_ambigs_training, false, "Perform training for ambiguities", this->params()), INT_MEMBER(pageseg_devanagari_split_strategy, tesseract::ShiroRekhaSplitter::NO_SPLIT, "Whether to use the top-line splitting process for Devanagari " "documents while performing page-segmentation.", this->params()), INT_MEMBER(ocr_devanagari_split_strategy, tesseract::ShiroRekhaSplitter::NO_SPLIT, "Whether to use the top-line splitting process for Devanagari " "documents while performing ocr.", this->params()), STRING_MEMBER(tessedit_write_params_to_file, "", "Write all parameters to the given file.", this->params()), BOOL_MEMBER(tessedit_adaption_debug, false, "Generate and print debug" " information for adaption", this->params()), INT_MEMBER(bidi_debug, 0, "Debug level for BiDi", this->params()), INT_MEMBER(applybox_debug, 1, "Debug level", this->params()), INT_MEMBER(applybox_page, 0, "Page number to apply boxes from", this->params()), STRING_MEMBER(applybox_exposure_pattern, ".exp", "Exposure value follows" " this pattern in the image filename. The name of the image" " files are expected to be in the form" " [lang].[fontname].exp[num].tif", this->params()), BOOL_MEMBER(applybox_learn_chars_and_char_frags_mode, false, "Learn both character fragments (as is done in the" " special low exposure mode) as well as unfragmented" " characters.", this->params()), BOOL_MEMBER(applybox_learn_ngrams_mode, false, "Each bounding box" " is assumed to contain ngrams. Only learn the ngrams" " whose outlines overlap horizontally.", this->params()), BOOL_MEMBER(tessedit_display_outwords, false, "Draw output words", this->params()), BOOL_MEMBER(tessedit_dump_choices, false, "Dump char choices", this->params()), BOOL_MEMBER(tessedit_timing_debug, false, "Print timing stats", this->params()), BOOL_MEMBER(tessedit_fix_fuzzy_spaces, true, "Try to improve fuzzy spaces", this->params()), BOOL_MEMBER(tessedit_unrej_any_wd, false, "Dont bother with word plausibility", this->params()), BOOL_MEMBER(tessedit_fix_hyphens, true, "Crunch double hyphens?", this->params()), BOOL_MEMBER(tessedit_redo_xheight, true, "Check/Correct x-height", this->params()), BOOL_MEMBER(tessedit_enable_doc_dict, true, "Add words to the document dictionary", this->params()), BOOL_MEMBER(tessedit_debug_fonts, false, "Output font info per char", this->params()), BOOL_MEMBER(tessedit_debug_block_rejection, false, "Block and Row stats", this->params()), BOOL_MEMBER(tessedit_enable_bigram_correction, true, "Enable correction based on the word bigram dictionary.", this->params()), BOOL_MEMBER(tessedit_enable_dict_correction, false, "Enable single word correction based on the dictionary.", this->params()), INT_MEMBER(tessedit_bigram_debug, 0, "Amount of debug output for bigram correction.", this->params()), INT_MEMBER(debug_x_ht_level, 0, "Reestimate debug", this->params()), BOOL_MEMBER(debug_acceptable_wds, false, "Dump word pass/fail chk", this->params()), STRING_MEMBER(chs_leading_punct, "('`\"", "Leading punctuation", this->params()), STRING_MEMBER(chs_trailing_punct1, ").,;:?!", "1st Trailing punctuation", this->params()), STRING_MEMBER(chs_trailing_punct2, ")'`\"", "2nd Trailing punctuation", this->params()), double_MEMBER(quality_rej_pc, 0.08, "good_quality_doc lte rejection limit", this->params()), double_MEMBER(quality_blob_pc, 0.0, "good_quality_doc gte good blobs limit", this->params()), double_MEMBER(quality_outline_pc, 1.0, "good_quality_doc lte outline error limit", this->params()), double_MEMBER(quality_char_pc, 0.95, "good_quality_doc gte good char limit", this->params()), INT_MEMBER(quality_min_initial_alphas_reqd, 2, "alphas in a good word", this->params()), INT_MEMBER(tessedit_tess_adaption_mode, 0x27, "Adaptation decision algorithm for tess", this->params()), BOOL_MEMBER(tessedit_minimal_rej_pass1, false, "Do minimal rejection on pass 1 output", this->params()), BOOL_MEMBER(tessedit_test_adaption, false, "Test adaption criteria", this->params()), BOOL_MEMBER(tessedit_matcher_log, false, "Log matcher activity", this->params()), INT_MEMBER(tessedit_test_adaption_mode, 3, "Adaptation decision algorithm for tess", this->params()), BOOL_MEMBER(test_pt, false, "Test for point", this->params()), double_MEMBER(test_pt_x, 99999.99, "xcoord", this->params()), double_MEMBER(test_pt_y, 99999.99, "ycoord", this->params()), INT_MEMBER(paragraph_debug_level, 0, "Print paragraph debug info.", this->params()), BOOL_MEMBER(paragraph_text_based, true, "Run paragraph detection on the post-text-recognition " "(more accurate)", this->params()), INT_MEMBER(cube_debug_level, 0, "Print cube debug info.", this->params()), STRING_MEMBER(outlines_odd, "%| ", "Non standard number of outlines", this->params()), STRING_MEMBER(outlines_2, "ij!?%\":;", "Non standard number of outlines", this->params()), BOOL_MEMBER(docqual_excuse_outline_errs, false, "Allow outline errs in unrejection?", this->params()), BOOL_MEMBER(tessedit_good_quality_unrej, true, "Reduce rejection on good docs", this->params()), BOOL_MEMBER(tessedit_use_reject_spaces, true, "Reject spaces?", this->params()), double_MEMBER(tessedit_reject_doc_percent, 65.00, "%rej allowed before rej whole doc", this->params()), double_MEMBER(tessedit_reject_block_percent, 45.00, "%rej allowed before rej whole block", this->params()), double_MEMBER(tessedit_reject_row_percent, 40.00, "%rej allowed before rej whole row", this->params()), double_MEMBER(tessedit_whole_wd_rej_row_percent, 70.00, "Number of row rejects in whole word rejects" "which prevents whole row rejection", this->params()), BOOL_MEMBER(tessedit_preserve_blk_rej_perfect_wds, true, "Only rej partially rejected words in block rejection", this->params()), BOOL_MEMBER(tessedit_preserve_row_rej_perfect_wds, true, "Only rej partially rejected words in row rejection", this->params()), BOOL_MEMBER(tessedit_dont_blkrej_good_wds, false, "Use word segmentation quality metric", this->params()), BOOL_MEMBER(tessedit_dont_rowrej_good_wds, false, "Use word segmentation quality metric", this->params()), INT_MEMBER(tessedit_preserve_min_wd_len, 2, "Only preserve wds longer than this", this->params()), BOOL_MEMBER(tessedit_row_rej_good_docs, true, "Apply row rejection to good docs", this->params()), double_MEMBER(tessedit_good_doc_still_rowrej_wd, 1.1, "rej good doc wd if more than this fraction rejected", this->params()), BOOL_MEMBER(tessedit_reject_bad_qual_wds, true, "Reject all bad quality wds", this->params()), BOOL_MEMBER(tessedit_debug_doc_rejection, false, "Page stats", this->params()), BOOL_MEMBER(tessedit_debug_quality_metrics, false, "Output data to debug file", this->params()), BOOL_MEMBER(bland_unrej, false, "unrej potential with no chekcs", this->params()), double_MEMBER(quality_rowrej_pc, 1.1, "good_quality_doc gte good char limit", this->params()), BOOL_MEMBER(unlv_tilde_crunching, true, "Mark v.bad words for tilde crunch", this->params()), BOOL_MEMBER(hocr_font_info, false, "Add font info to hocr output", this->params()), BOOL_MEMBER(crunch_early_merge_tess_fails, true, "Before word crunch?", this->params()), BOOL_MEMBER(crunch_early_convert_bad_unlv_chs, false, "Take out ~^ early?", this->params()), double_MEMBER(crunch_terrible_rating, 80.0, "crunch rating lt this", this->params()), BOOL_MEMBER(crunch_terrible_garbage, true, "As it says", this->params()), double_MEMBER(crunch_poor_garbage_cert, -9.0, "crunch garbage cert lt this", this->params()), double_MEMBER(crunch_poor_garbage_rate, 60, "crunch garbage rating lt this", this->params()), double_MEMBER(crunch_pot_poor_rate, 40, "POTENTIAL crunch rating lt this", this->params()), double_MEMBER(crunch_pot_poor_cert, -8.0, "POTENTIAL crunch cert lt this", this->params()), BOOL_MEMBER(crunch_pot_garbage, true, "POTENTIAL crunch garbage", this->params()), double_MEMBER(crunch_del_rating, 60, "POTENTIAL crunch rating lt this", this->params()), double_MEMBER(crunch_del_cert, -10.0, "POTENTIAL crunch cert lt this", this->params()), double_MEMBER(crunch_del_min_ht, 0.7, "Del if word ht lt xht x this", this->params()), double_MEMBER(crunch_del_max_ht, 3.0, "Del if word ht gt xht x this", this->params()), double_MEMBER(crunch_del_min_width, 3.0, "Del if word width lt xht x this", this->params()), double_MEMBER(crunch_del_high_word, 1.5, "Del if word gt xht x this above bl", this->params()), double_MEMBER(crunch_del_low_word, 0.5, "Del if word gt xht x this below bl", this->params()), double_MEMBER(crunch_small_outlines_size, 0.6, "Small if lt xht x this", this->params()), INT_MEMBER(crunch_rating_max, 10, "For adj length in rating per ch", this->params()), INT_MEMBER(crunch_pot_indicators, 1, "How many potential indicators needed", this->params()), BOOL_MEMBER(crunch_leave_ok_strings, true, "Dont touch sensible strings", this->params()), BOOL_MEMBER(crunch_accept_ok, true, "Use acceptability in okstring", this->params()), BOOL_MEMBER(crunch_leave_accept_strings, false, "Dont pot crunch sensible strings", this->params()), BOOL_MEMBER(crunch_include_numerals, false, "Fiddle alpha figures", this->params()), INT_MEMBER(crunch_leave_lc_strings, 4, "Dont crunch words with long lower case strings", this->params()), INT_MEMBER(crunch_leave_uc_strings, 4, "Dont crunch words with long lower case strings", this->params()), INT_MEMBER(crunch_long_repetitions, 3, "Crunch words with long repetitions", this->params()), INT_MEMBER(crunch_debug, 0, "As it says", this->params()), INT_MEMBER(fixsp_non_noise_limit, 1, "How many non-noise blbs either side?", this->params()), double_MEMBER(fixsp_small_outlines_size, 0.28, "Small if lt xht x this", this->params()), BOOL_MEMBER(tessedit_prefer_joined_punct, false, "Reward punctation joins", this->params()), INT_MEMBER(fixsp_done_mode, 1, "What constitues done for spacing", this->params()), INT_MEMBER(debug_fix_space_level, 0, "Contextual fixspace debug", this->params()), STRING_MEMBER(numeric_punctuation, ".,", "Punct. chs expected WITHIN numbers", this->params()), INT_MEMBER(x_ht_acceptance_tolerance, 8, "Max allowed deviation of blob top outside of font data", this->params()), INT_MEMBER(x_ht_min_change, 8, "Min change in xht before actually trying it", this->params()), INT_MEMBER(superscript_debug, 0, "Debug level for sub & superscript fixer", this->params()), double_MEMBER(superscript_worse_certainty, 2.0, "How many times worse " "certainty does a superscript position glyph need to be for " "us to try classifying it as a char with a different " "baseline?", this->params()), double_MEMBER(superscript_bettered_certainty, 0.97, "What reduction in " "badness do we think sufficient to choose a superscript " "over what we'd thought. For example, a value of 0.6 means " "we want to reduce badness of certainty by at least 40%", this->params()), double_MEMBER(superscript_scaledown_ratio, 0.4, "A superscript scaled down more than this is unbelievably " "small. For example, 0.3 means we expect the font size to " "be no smaller than 30% of the text line font size.", this->params()), double_MEMBER(subscript_max_y_top, 0.5, "Maximum top of a character measured as a multiple of " "x-height above the baseline for us to reconsider whether " "it's a subscript.", this->params()), double_MEMBER(superscript_min_y_bottom, 0.3, "Minimum bottom of a character measured as a multiple of " "x-height above the baseline for us to reconsider whether " "it's a superscript.", this->params()), BOOL_MEMBER(tessedit_write_block_separators, false, "Write block separators in output", this->params()), BOOL_MEMBER(tessedit_write_rep_codes, false, "Write repetition char code", this->params()), BOOL_MEMBER(tessedit_write_unlv, false, "Write .unlv output file", this->params()), BOOL_MEMBER(tessedit_create_txt, true, "Write .txt output file", this->params()), BOOL_MEMBER(tessedit_create_hocr, false, "Write .html hOCR output file", this->params()), BOOL_MEMBER(tessedit_create_pdf, false, "Write .pdf output file", this->params()), STRING_MEMBER(unrecognised_char, "|", "Output char for unidentified blobs", this->params()), INT_MEMBER(suspect_level, 99, "Suspect marker level", this->params()), INT_MEMBER(suspect_space_level, 100, "Min suspect level for rejecting spaces", this->params()), INT_MEMBER(suspect_short_words, 2, "Dont Suspect dict wds longer than this", this->params()), BOOL_MEMBER(suspect_constrain_1Il, false, "UNLV keep 1Il chars rejected", this->params()), double_MEMBER(suspect_rating_per_ch, 999.9, "Dont touch bad rating limit", this->params()), double_MEMBER(suspect_accept_rating, -999.9, "Accept good rating limit", this->params()), BOOL_MEMBER(tessedit_minimal_rejection, false, "Only reject tess failures", this->params()), BOOL_MEMBER(tessedit_zero_rejection, false, "Dont reject ANYTHING", this->params()), BOOL_MEMBER(tessedit_word_for_word, false, "Make output have exactly one word per WERD", this->params()), BOOL_MEMBER(tessedit_zero_kelvin_rejection, false, "Dont reject ANYTHING AT ALL", this->params()), BOOL_MEMBER(tessedit_consistent_reps, true, "Force all rep chars the same", this->params()), INT_MEMBER(tessedit_reject_mode, 0, "Rejection algorithm", this->params()), BOOL_MEMBER(tessedit_rejection_debug, false, "Adaption debug", this->params()), BOOL_MEMBER(tessedit_flip_0O, true, "Contextual 0O O0 flips", this->params()), double_MEMBER(tessedit_lower_flip_hyphen, 1.5, "Aspect ratio dot/hyphen test", this->params()), double_MEMBER(tessedit_upper_flip_hyphen, 1.8, "Aspect ratio dot/hyphen test", this->params()), BOOL_MEMBER(rej_trust_doc_dawg, false, "Use DOC dawg in 11l conf. detector", this->params()), BOOL_MEMBER(rej_1Il_use_dict_word, false, "Use dictword test", this->params()), BOOL_MEMBER(rej_1Il_trust_permuter_type, true, "Dont double check", this->params()), BOOL_MEMBER(rej_use_tess_accepted, true, "Individual rejection control", this->params()), BOOL_MEMBER(rej_use_tess_blanks, true, "Individual rejection control", this->params()), BOOL_MEMBER(rej_use_good_perm, true, "Individual rejection control", this->params()), BOOL_MEMBER(rej_use_sensible_wd, false, "Extend permuter check", this->params()), BOOL_MEMBER(rej_alphas_in_number_perm, false, "Extend permuter check", this->params()), double_MEMBER(rej_whole_of_mostly_reject_word_fract, 0.85, "if >this fract", this->params()), INT_MEMBER(tessedit_image_border, 2, "Rej blbs near image edge limit", this->params()), STRING_MEMBER(ok_repeated_ch_non_alphanum_wds, "-?*\075", "Allow NN to unrej", this->params()), STRING_MEMBER(conflict_set_I_l_1, "Il1[]", "Il1 conflict set", this->params()), INT_MEMBER(min_sane_x_ht_pixels, 8, "Reject any x-ht lt or eq than this", this->params()), BOOL_MEMBER(tessedit_create_boxfile, false, "Output text with boxes", this->params()), INT_MEMBER(tessedit_page_number, -1, "-1 -> All pages" " , else specifc page to process", this->params()), BOOL_MEMBER(tessedit_write_images, false, "Capture the image from the IPE", this->params()), BOOL_MEMBER(interactive_display_mode, false, "Run interactively?", this->params()), STRING_MEMBER(file_type, ".tif", "Filename extension", this->params()), BOOL_MEMBER(tessedit_override_permuter, true, "According to dict_word", this->params()), INT_MEMBER(tessdata_manager_debug_level, 0, "Debug level for" " TessdataManager functions.", this->params()), STRING_MEMBER(tessedit_load_sublangs, "", "List of languages to load with this one", this->params()), BOOL_MEMBER(tessedit_use_primary_params_model, false, "In multilingual mode use params model of the" " primary language", this->params()), double_MEMBER(min_orientation_margin, 7.0, "Min acceptable orientation margin", this->params()), BOOL_MEMBER(textord_tabfind_show_vlines, false, "Debug line finding", this->params()), BOOL_MEMBER(textord_use_cjk_fp_model, FALSE, "Use CJK fixed pitch model", this->params()), BOOL_MEMBER(poly_allow_detailed_fx, false, "Allow feature extractors to see the original outline", this->params()), BOOL_INIT_MEMBER(tessedit_init_config_only, false, "Only initialize with the config file. Useful if the " "instance is not going to be used for OCR but say only " "for layout analysis.", this->params()), BOOL_MEMBER(textord_equation_detect, false, "Turn on equation detector", this->params()), BOOL_MEMBER(textord_tabfind_vertical_text, true, "Enable vertical detection", this->params()), BOOL_MEMBER(textord_tabfind_force_vertical_text, false, "Force using vertical text page mode", this->params()), double_MEMBER(textord_tabfind_vertical_text_ratio, 0.5, "Fraction of textlines deemed vertical to use vertical page " "mode", this->params()), double_MEMBER(textord_tabfind_aligned_gap_fraction, 0.75, "Fraction of height used as a minimum gap for aligned blobs.", this->params()), INT_MEMBER(tessedit_parallelize, 0, "Run in parallel where possible", this->params()), // The following parameters were deprecated and removed from their original // locations. The parameters are temporarily kept here to give Tesseract // users a chance to updated their [lang].traineddata and config files // without introducing failures during Tesseract initialization. // TODO(ocr-team): remove these parameters from the code once we are // reasonably sure that Tesseract users have updated their data files. // // BEGIN DEPRECATED PARAMETERS BOOL_MEMBER(textord_tabfind_vertical_horizontal_mix, true, "find horizontal lines such as headers in vertical page mode", this->params()), INT_MEMBER(tessedit_ok_mode, 5, "Acceptance decision algorithm", this->params()), BOOL_INIT_MEMBER(load_fixed_length_dawgs, true, "Load fixed length dawgs" " (e.g. for non-space delimited languages)", this->params()), INT_MEMBER(segment_debug, 0, "Debug the whole segmentation process", this->params()), BOOL_MEMBER(permute_debug, 0, "Debug char permutation process", this->params()), double_MEMBER(bestrate_pruning_factor, 2.0, "Multiplying factor of" " current best rate to prune other hypotheses", this->params()), BOOL_MEMBER(permute_script_word, 0, "Turn on word script consistency permuter", this->params()), BOOL_MEMBER(segment_segcost_rating, 0, "incorporate segmentation cost in word rating?", this->params()), double_MEMBER(segment_reward_script, 0.95, "Score multipler for script consistency within a word. " "Being a 'reward' factor, it should be <= 1. " "Smaller value implies bigger reward.", this->params()), BOOL_MEMBER(permute_fixed_length_dawg, 0, "Turn on fixed-length phrasebook search permuter", this->params()), BOOL_MEMBER(permute_chartype_word, 0, "Turn on character type (property) consistency permuter", this->params()), double_MEMBER(segment_reward_chartype, 0.97, "Score multipler for char type consistency within a word. ", this->params()), double_MEMBER(segment_reward_ngram_best_choice, 0.99, "Score multipler for ngram permuter's best choice" " (only used in the Han script path).", this->params()), BOOL_MEMBER(ngram_permuter_activated, false, "Activate character-level n-gram-based permuter", this->params()), BOOL_MEMBER(permute_only_top, false, "Run only the top choice permuter", this->params()), INT_MEMBER(language_model_fixed_length_choices_depth, 3, "Depth of blob choice lists to explore" " when fixed length dawgs are on", this->params()), BOOL_MEMBER(use_new_state_cost, FALSE, "use new state cost heuristics for segmentation state" " evaluation", this->params()), double_MEMBER(heuristic_segcost_rating_base, 1.25, "base factor for adding segmentation cost into word rating." "It's a multiplying factor, the larger the value above 1, " "the bigger the effect of segmentation cost.", this->params()), double_MEMBER(heuristic_weight_rating, 1.0, "weight associated with char rating in combined cost of" "state", this->params()), double_MEMBER(heuristic_weight_width, 1000.0, "weight associated with width evidence in combined cost of" " state", this->params()), double_MEMBER(heuristic_weight_seamcut, 0.0, "weight associated with seam cut in combined cost of state", this->params()), double_MEMBER(heuristic_max_char_wh_ratio, 2.0, "max char width-to-height ratio allowed in segmentation", this->params()), BOOL_MEMBER(enable_new_segsearch, true, "Enable new segmentation search path.", this->params()), double_MEMBER(segsearch_max_fixed_pitch_char_wh_ratio, 2.0, "Maximum character width-to-height ratio for" " fixed-pitch fonts", this->params()), // END DEPRECATED PARAMETERS backup_config_file_(NULL), pix_binary_(NULL), cube_binary_(NULL), pix_grey_(NULL), pix_thresholds_(NULL), source_resolution_(0), textord_(this), right_to_left_(false), scaled_color_(NULL), scaled_factor_(-1), deskew_(1.0f, 0.0f), reskew_(1.0f, 0.0f), most_recently_used_(this), font_table_size_(0), cube_cntxt_(NULL), tess_cube_combiner_(NULL), equ_detect_(NULL) { } Tesseract::~Tesseract() { Clear(); end_tesseract(); sub_langs_.delete_data_pointers(); // Delete cube objects. if (cube_cntxt_ != NULL) { delete cube_cntxt_; cube_cntxt_ = NULL; } if (tess_cube_combiner_ != NULL) { delete tess_cube_combiner_; tess_cube_combiner_ = NULL; } } void Tesseract::Clear() { pixDestroy(&pix_binary_); pixDestroy(&cube_binary_); pixDestroy(&pix_grey_); pixDestroy(&pix_thresholds_); pixDestroy(&scaled_color_); deskew_ = FCOORD(1.0f, 0.0f); reskew_ = FCOORD(1.0f, 0.0f); splitter_.Clear(); scaled_factor_ = -1; for (int i = 0; i < sub_langs_.size(); ++i) sub_langs_[i]->Clear(); } void Tesseract::SetEquationDetect(EquationDetect* detector) { equ_detect_ = detector; equ_detect_->SetLangTesseract(this); } // Clear all memory of adaption for this and all subclassifiers. void Tesseract::ResetAdaptiveClassifier() { ResetAdaptiveClassifierInternal(); for (int i = 0; i < sub_langs_.size(); ++i) { sub_langs_[i]->ResetAdaptiveClassifierInternal(); } } // Clear the document dictionary for this and all subclassifiers. void Tesseract::ResetDocumentDictionary() { getDict().ResetDocumentDictionary(); for (int i = 0; i < sub_langs_.size(); ++i) { sub_langs_[i]->getDict().ResetDocumentDictionary(); } } void Tesseract::SetBlackAndWhitelist() { // Set the white and blacklists (if any) unicharset.set_black_and_whitelist(tessedit_char_blacklist.string(), tessedit_char_whitelist.string(), tessedit_char_unblacklist.string()); // Black and white lists should apply to all loaded classifiers. for (int i = 0; i < sub_langs_.size(); ++i) { sub_langs_[i]->unicharset.set_black_and_whitelist( tessedit_char_blacklist.string(), tessedit_char_whitelist.string(), tessedit_char_unblacklist.string()); } } // Perform steps to prepare underlying binary image/other data structures for // page segmentation. void Tesseract::PrepareForPageseg() { textord_.set_use_cjk_fp_model(textord_use_cjk_fp_model); pixDestroy(&cube_binary_); cube_binary_ = pixClone(pix_binary()); // Find the max splitter strategy over all langs. ShiroRekhaSplitter::SplitStrategy max_pageseg_strategy = static_cast<ShiroRekhaSplitter::SplitStrategy>( static_cast<inT32>(pageseg_devanagari_split_strategy)); for (int i = 0; i < sub_langs_.size(); ++i) { ShiroRekhaSplitter::SplitStrategy pageseg_strategy = static_cast<ShiroRekhaSplitter::SplitStrategy>( static_cast<inT32>(sub_langs_[i]->pageseg_devanagari_split_strategy)); if (pageseg_strategy > max_pageseg_strategy) max_pageseg_strategy = pageseg_strategy; // Clone the cube image to all the sub langs too. pixDestroy(&sub_langs_[i]->cube_binary_); sub_langs_[i]->cube_binary_ = pixClone(pix_binary()); pixDestroy(&sub_langs_[i]->pix_binary_); sub_langs_[i]->pix_binary_ = pixClone(pix_binary()); } // Perform shiro-rekha (top-line) splitting and replace the current image by // the newly splitted image. splitter_.set_orig_pix(pix_binary()); splitter_.set_pageseg_split_strategy(max_pageseg_strategy); if (splitter_.Split(true)) { ASSERT_HOST(splitter_.splitted_image()); pixDestroy(&pix_binary_); pix_binary_ = pixClone(splitter_.splitted_image()); } } // Perform steps to prepare underlying binary image/other data structures for // OCR. The current segmentation is required by this method. // Note that this method resets pix_binary_ to the original binarized image, // which may be different from the image actually used for OCR depending on the // value of devanagari_ocr_split_strategy. void Tesseract::PrepareForTessOCR(BLOCK_LIST* block_list, Tesseract* osd_tess, OSResults* osr) { // Find the max splitter strategy over all langs. ShiroRekhaSplitter::SplitStrategy max_ocr_strategy = static_cast<ShiroRekhaSplitter::SplitStrategy>( static_cast<inT32>(ocr_devanagari_split_strategy)); for (int i = 0; i < sub_langs_.size(); ++i) { ShiroRekhaSplitter::SplitStrategy ocr_strategy = static_cast<ShiroRekhaSplitter::SplitStrategy>( static_cast<inT32>(sub_langs_[i]->ocr_devanagari_split_strategy)); if (ocr_strategy > max_ocr_strategy) max_ocr_strategy = ocr_strategy; } // Utilize the segmentation information available. splitter_.set_segmentation_block_list(block_list); splitter_.set_ocr_split_strategy(max_ocr_strategy); // Run the splitter for OCR bool split_for_ocr = splitter_.Split(false); // Restore pix_binary to the binarized original pix for future reference. ASSERT_HOST(splitter_.orig_pix()); pixDestroy(&pix_binary_); pix_binary_ = pixClone(splitter_.orig_pix()); // If the pageseg and ocr strategies are different, refresh the block list // (from the last SegmentImage call) with blobs from the real image to be used // for OCR. if (splitter_.HasDifferentSplitStrategies()) { BLOCK block("", TRUE, 0, 0, 0, 0, pixGetWidth(pix_binary_), pixGetHeight(pix_binary_)); Pix* pix_for_ocr = split_for_ocr ? splitter_.splitted_image() : splitter_.orig_pix(); extract_edges(pix_for_ocr, &block); splitter_.RefreshSegmentationWithNewBlobs(block.blob_list()); } // The splitter isn't needed any more after this, so save memory by clearing. splitter_.Clear(); } } // namespace tesseract
1080228-arabicocr11
ccmain/tesseractclass.cpp
C++
asf20
35,332
/////////////////////////////////////////////////////////////////////// // File: paramsd.cpp // Description: Tesseract parameter Editor // Author: Joern Wanke // Created: Wed Jul 18 10:05:01 PDT 2007 // // (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. // /////////////////////////////////////////////////////////////////////// // // The parameters editor is used to edit all the parameters used within // tesseract from the ui. #ifdef _WIN32 #else #include <stdlib.h> #include <stdio.h> #endif #include <map> // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #ifndef GRAPHICS_DISABLED #include "paramsd.h" #include "params.h" #include "scrollview.h" #include "svmnode.h" #define VARDIR "configs/" /*parameters files */ #define MAX_ITEMS_IN_SUBMENU 30 // The following variables should remain static globals, since they // are used by debug editor, which uses a single Tesseract instance. // // Contains the mappings from unique VC ids to their actual pointers. static std::map<int, ParamContent*> vcMap; static int nrParams = 0; static int writeCommands[2]; ELISTIZE(ParamContent) // Constructors for the various ParamTypes. ParamContent::ParamContent(tesseract::StringParam* it) { my_id_ = nrParams; nrParams++; param_type_ = VT_STRING; sIt = it; vcMap[my_id_] = this; } // Constructors for the various ParamTypes. ParamContent::ParamContent(tesseract::IntParam* it) { my_id_ = nrParams; nrParams++; param_type_ = VT_INTEGER; iIt = it; vcMap[my_id_] = this; } // Constructors for the various ParamTypes. ParamContent::ParamContent(tesseract::BoolParam* it) { my_id_ = nrParams; nrParams++; param_type_ = VT_BOOLEAN; bIt = it; vcMap[my_id_] = this; } // Constructors for the various ParamTypes. ParamContent::ParamContent(tesseract::DoubleParam* it) { my_id_ = nrParams; nrParams++; param_type_ = VT_DOUBLE; dIt = it; vcMap[my_id_] = this; } // Gets a VC object identified by its ID. ParamContent* ParamContent::GetParamContentById(int id) { return vcMap[id]; } // Copy the first N words from the source string to the target string. // Words are delimited by "_". void ParamsEditor::GetFirstWords( const char *s, // source string int n, // number of words char *t // target string ) { int full_length = strlen(s); int reqd_len = 0; // No. of chars requird const char *next_word = s; while ((n > 0) && reqd_len < full_length) { reqd_len += strcspn(next_word, "_") + 1; next_word += reqd_len; n--; } strncpy(t, s, reqd_len); t[reqd_len] = '\0'; // ensure null terminal } // Getter for the name. const char* ParamContent::GetName() const { if (param_type_ == VT_INTEGER) { return iIt->name_str(); } else if (param_type_ == VT_BOOLEAN) { return bIt->name_str(); } else if (param_type_ == VT_DOUBLE) { return dIt->name_str(); } else if (param_type_ == VT_STRING) { return sIt->name_str(); } else return "ERROR: ParamContent::GetName()"; } // Getter for the description. const char* ParamContent::GetDescription() const { if (param_type_ == VT_INTEGER) { return iIt->info_str(); } else if (param_type_ == VT_BOOLEAN) { return bIt->info_str(); } else if (param_type_ == VT_DOUBLE) { return dIt->info_str(); } else if (param_type_ == VT_STRING) { return sIt->info_str(); } else return NULL; } // Getter for the value. STRING ParamContent::GetValue() const { STRING result; if (param_type_ == VT_INTEGER) { result.add_str_int("", *iIt); } else if (param_type_ == VT_BOOLEAN) { result.add_str_int("", *bIt); } else if (param_type_ == VT_DOUBLE) { result.add_str_double("", *dIt); } else if (param_type_ == VT_STRING) { if (((STRING) * (sIt)).string() != NULL) { result = sIt->string(); } else { result = "Null"; } } return result; } // Setter for the value. void ParamContent::SetValue(const char* val) { // TODO (wanke) Test if the values actually are properly converted. // (Quickly visible impacts?) changed_ = TRUE; if (param_type_ == VT_INTEGER) { iIt->set_value(atoi(val)); } else if (param_type_ == VT_BOOLEAN) { bIt->set_value(atoi(val)); } else if (param_type_ == VT_DOUBLE) { dIt->set_value(strtod(val, NULL)); } else if (param_type_ == VT_STRING) { sIt->set_value(val); } } // Gets the up to the first 3 prefixes from s (split by _). // For example, tesseract_foo_bar will be split into tesseract,foo and bar. void ParamsEditor::GetPrefixes(const char* s, STRING* level_one, STRING* level_two, STRING* level_three) { char* p = new char[1024]; GetFirstWords(s, 1, p); *level_one = p; GetFirstWords(s, 2, p); *level_two = p; GetFirstWords(s, 3, p); *level_three = p; delete[] p; } // Compare two VC objects by their name. int ParamContent::Compare(const void* v1, const void* v2) { const ParamContent* one = *reinterpret_cast<const ParamContent* const *>(v1); const ParamContent* two = *reinterpret_cast<const ParamContent* const *>(v2); return strcmp(one->GetName(), two->GetName()); } // Find all editable parameters used within tesseract and create a // SVMenuNode tree from it. // TODO (wanke): This is actually sort of hackish. SVMenuNode* ParamsEditor::BuildListOfAllLeaves(tesseract::Tesseract *tess) { SVMenuNode* mr = new SVMenuNode(); ParamContent_LIST vclist; ParamContent_IT vc_it(&vclist); // Amount counts the number of entries for a specific char*. // TODO(rays) get rid of the use of std::map. std::map<const char*, int> amount; // Add all parameters to a list. int v, i; int num_iterations = (tess->params() == NULL) ? 1 : 2; for (v = 0; v < num_iterations; ++v) { tesseract::ParamsVectors *vec = (v == 0) ? GlobalParams() : tess->params(); for (i = 0; i < vec->int_params.size(); ++i) { vc_it.add_after_then_move(new ParamContent(vec->int_params[i])); } for (i = 0; i < vec->bool_params.size(); ++i) { vc_it.add_after_then_move(new ParamContent(vec->bool_params[i])); } for (i = 0; i < vec->string_params.size(); ++i) { vc_it.add_after_then_move(new ParamContent(vec->string_params[i])); } for (i = 0; i < vec->double_params.size(); ++i) { vc_it.add_after_then_move(new ParamContent(vec->double_params[i])); } } // Count the # of entries starting with a specific prefix. for (vc_it.mark_cycle_pt(); !vc_it.cycled_list(); vc_it.forward()) { ParamContent* vc = vc_it.data(); STRING tag; STRING tag2; STRING tag3; GetPrefixes(vc->GetName(), &tag, &tag2, &tag3); amount[tag.string()]++; amount[tag2.string()]++; amount[tag3.string()]++; } vclist.sort(ParamContent::Compare); // Sort the list alphabetically. SVMenuNode* other = mr->AddChild("OTHER"); // go through the list again and this time create the menu structure. vc_it.move_to_first(); for (vc_it.mark_cycle_pt(); !vc_it.cycled_list(); vc_it.forward()) { ParamContent* vc = vc_it.data(); STRING tag; STRING tag2; STRING tag3; GetPrefixes(vc->GetName(), &tag, &tag2, &tag3); if (amount[tag.string()] == 1) { other->AddChild(vc->GetName(), vc->GetId(), vc->GetValue().string(), vc->GetDescription()); } else { // More than one would use this submenu -> create submenu. SVMenuNode* sv = mr->AddChild(tag.string()); if ((amount[tag.string()] <= MAX_ITEMS_IN_SUBMENU) || (amount[tag2.string()] <= 1)) { sv->AddChild(vc->GetName(), vc->GetId(), vc->GetValue().string(), vc->GetDescription()); } else { // Make subsubmenus. SVMenuNode* sv2 = sv->AddChild(tag2.string()); sv2->AddChild(vc->GetName(), vc->GetId(), vc->GetValue().string(), vc->GetDescription()); } } } return mr; } // Event listener. Waits for SVET_POPUP events and processes them. void ParamsEditor::Notify(const SVEvent* sve) { if (sve->type == SVET_POPUP) { // only catch SVET_POPUP! char* param = sve->parameter; if (sve->command_id == writeCommands[0]) { WriteParams(param, false); } else if (sve->command_id == writeCommands[1]) { WriteParams(param, true); } else { ParamContent* vc = ParamContent::GetParamContentById( sve->command_id); vc->SetValue(param); sv_window_->AddMessage("Setting %s to %s", vc->GetName(), vc->GetValue().string()); } } } // Integrate the parameters editor as popupmenu into the existing scrollview // window (usually the pg editor). If sv == null, create a new empty // empty window and attach the parameters editor to that window (ugly). ParamsEditor::ParamsEditor(tesseract::Tesseract* tess, ScrollView* sv) { if (sv == NULL) { const char* name = "ParamEditorMAIN"; sv = new ScrollView(name, 1, 1, 200, 200, 300, 200); } sv_window_ = sv; //Only one event handler per window. //sv->AddEventHandler((SVEventHandler*) this); SVMenuNode* svMenuRoot = BuildListOfAllLeaves(tess); STRING paramfile; paramfile = tess->datadir; paramfile += VARDIR; // parameters dir paramfile += "edited"; // actual name SVMenuNode* std_menu = svMenuRoot->AddChild ("Build Config File"); writeCommands[0] = nrParams+1; std_menu->AddChild("All Parameters", writeCommands[0], paramfile.string(), "Config file name?"); writeCommands[1] = nrParams+2; std_menu->AddChild ("changed_ Parameters Only", writeCommands[1], paramfile.string(), "Config file name?"); svMenuRoot->BuildMenu(sv, false); } // Write all (changed_) parameters to a config file. void ParamsEditor::WriteParams(char *filename, bool changes_only) { FILE *fp; // input file char msg_str[255]; // if file exists if ((fp = fopen (filename, "rb")) != NULL) { fclose(fp); sprintf (msg_str, "Overwrite file " "%s" "? (Y/N)", filename); int a = sv_window_->ShowYesNoDialog(msg_str); if (a == 'n') { return; } // dont write } fp = fopen (filename, "wb"); // can we write to it? if (fp == NULL) { sv_window_->AddMessage("Cant write to file " "%s" "", filename); return; } for (std::map<int, ParamContent*>::iterator iter = vcMap.begin(); iter != vcMap.end(); ++iter) { ParamContent* cur = iter->second; if (!changes_only || cur->HasChanged()) { fprintf(fp, "%-25s %-12s # %s\n", cur->GetName(), cur->GetValue().string(), cur->GetDescription()); } } fclose(fp); } #endif
1080228-arabicocr11
ccmain/paramsd.cpp
C++
asf20
11,507