code
stringlengths
1
2.06M
language
stringclasses
1 value
/********************************************************************** * File: char_samp_enum.cpp * Description: Implementation of a Character Sample Set 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 <stdlib.h> #include <string> #include "char_samp_set.h" #include "cached_file.h" namespace tesseract { CharSampSet::CharSampSet() { cnt_ = 0; samp_buff_ = NULL; own_samples_ = false; } CharSampSet::~CharSampSet() { Cleanup(); } // free buffers and init vars void CharSampSet::Cleanup() { if (samp_buff_ != NULL) { // only free samples if owned by class if (own_samples_ == true) { for (int samp_idx = 0; samp_idx < cnt_; samp_idx++) { if (samp_buff_[samp_idx] != NULL) { delete samp_buff_[samp_idx]; } } } delete []samp_buff_; } cnt_ = 0; samp_buff_ = NULL; } // add a new sample bool CharSampSet::Add(CharSamp *char_samp) { if ((cnt_ % SAMP_ALLOC_BLOCK) == 0) { // create an extended buffer CharSamp **new_samp_buff = reinterpret_cast<CharSamp **>(new CharSamp *[cnt_ + SAMP_ALLOC_BLOCK]); if (new_samp_buff == NULL) { return false; } // copy old contents if (cnt_ > 0) { memcpy(new_samp_buff, samp_buff_, cnt_ * sizeof(*samp_buff_)); delete []samp_buff_; } samp_buff_ = new_samp_buff; } samp_buff_[cnt_++] = char_samp; return true; } // load char samples from file bool CharSampSet::LoadCharSamples(FILE *fp) { // free existing Cleanup(); // samples are created here and owned by the class own_samples_ = true; // start loading char samples while (feof(fp) == 0) { CharSamp *new_samp = CharSamp::FromCharDumpFile(fp); if (new_samp != NULL) { if (Add(new_samp) == false) { return false; } } } return true; } // creates a CharSampSet object from file CharSampSet * CharSampSet::FromCharDumpFile(string file_name) { FILE *fp; unsigned int val32; // open the file fp = fopen(file_name.c_str(), "rb"); if (fp == NULL) { return NULL; } // read and verify marker if (fread(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { fclose(fp); return NULL; } if (val32 != 0xfefeabd0) { fclose(fp); return NULL; } // create an object CharSampSet *samp_set = new CharSampSet(); if (samp_set == NULL) { fclose(fp); return NULL; } if (samp_set->LoadCharSamples(fp) == false) { delete samp_set; samp_set = NULL; } fclose(fp); return samp_set; } // Create a new Char Dump file FILE *CharSampSet::CreateCharDumpFile(string file_name) { FILE *fp; unsigned int val32; // create the file fp = fopen(file_name.c_str(), "wb"); if (!fp) { return NULL; } // read and verify marker val32 = 0xfefeabd0; if (fwrite(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { fclose(fp); return NULL; } return fp; } // Enumerate the Samples in the set one-by-one calling the enumertor's // EnumCharSamp method for each sample bool CharSampSet::EnumSamples(string file_name, CharSampEnum *enum_obj) { CachedFile *fp_in; unsigned int val32; long i64_size, i64_pos; // open the file fp_in = new CachedFile(file_name); if (fp_in == NULL) { return false; } i64_size = fp_in->Size(); if (i64_size < 1) { return false; } // read and verify marker if (fp_in->Read(&val32, sizeof(val32)) != sizeof(val32)) { return false; } if (val32 != 0xfefeabd0) { return false; } // start loading char samples while (fp_in->eof() == false) { CharSamp *new_samp = CharSamp::FromCharDumpFile(fp_in); i64_pos = fp_in->Tell(); if (new_samp != NULL) { bool ret_flag = (enum_obj)->EnumCharSamp(new_samp, (100.0f * i64_pos / i64_size)); delete new_samp; if (ret_flag == false) { break; } } } delete fp_in; return true; } } // namespace ocrlib
C++
/********************************************************************** * File: search_column.h * Description: Declaration of the Beam Search Column 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 SearchColumn class abstracts a column in the lattice that is created // by the BeamSearch during the recognition process // The class holds the lattice nodes. New nodes are added by calls to AddNode // made from the BeamSearch // The class maintains a hash table of the nodes to be able to lookup nodes // quickly using their lang_mod_edge. This is needed to merge similar paths // in the lattice #ifndef SEARCH_COLUMN_H #define SEARCH_COLUMN_H #include "search_node.h" #include "lang_mod_edge.h" #include "cube_reco_context.h" namespace tesseract { class SearchColumn { public: SearchColumn(int col_idx, int max_node_cnt); ~SearchColumn(); // Accessor functions inline int ColIdx() const { return col_idx_; } inline int NodeCount() const { return node_cnt_; } inline SearchNode **Nodes() const { return node_array_; } // Prune the nodes if necessary. Pruning is done such that a max // number of nodes is kept, i.e., the beam width void Prune(); SearchNode *AddNode(LangModEdge *edge, int score, SearchNode *parent, CubeRecoContext *cntxt); // Returns the node with the least cost SearchNode *BestNode(); // Sort the lattice nodes. Needed for visualization void Sort(); // Free up the Hash Table. Added to be called by the Beam Search after // a column is pruned to reduce memory foot print void FreeHashTable() { if (node_hash_table_ != NULL) { delete node_hash_table_; node_hash_table_ = NULL; } } private: static const int kNodeAllocChunk = 1024; static const int kScoreBins = 1024; bool init_; int min_cost_; int max_cost_; int max_node_cnt_; int node_cnt_; int col_idx_; int score_bins_[kScoreBins]; SearchNode **node_array_; SearchNodeHashTable *node_hash_table_; // Free node array and hash table void Cleanup(); // Create hash table bool Init(); }; } #endif // SEARCH_COLUMN_H
C++
/********************************************************************** * File: feature_chebyshev.cpp * Description: Implementation of the Chebyshev coefficients Feature 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. * **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string> #include <vector> #include <algorithm> #include "feature_base.h" #include "feature_hybrid.h" #include "cube_utils.h" #include "const.h" #include "char_samp.h" namespace tesseract { FeatureHybrid::FeatureHybrid(TuningParams *params) :FeatureBase(params) { feature_bmp_ = new FeatureBmp(params); feature_chebyshev_ = new FeatureChebyshev(params); } FeatureHybrid::~FeatureHybrid() { delete feature_bmp_; delete feature_chebyshev_; } // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers CharSamp *FeatureHybrid::ComputeFeatureBitmap(CharSamp *char_samp) { return char_samp; } // Compute the features of a given CharSamp bool FeatureHybrid::ComputeFeatures(CharSamp *char_samp, float *features) { if (feature_bmp_ == NULL || feature_chebyshev_ == NULL) { return false; } if (!feature_bmp_->ComputeFeatures(char_samp, features)) { return false; } return feature_chebyshev_->ComputeFeatures(char_samp, features + feature_bmp_->FeatureCnt()); } } // namespace tesseract
C++
/********************************************************************** * File: char_samp_enum.cpp * Description: Implementation of a Character Sample Enumerator 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 "char_samp_enum.h" namespace tesseract { CharSampEnum::CharSampEnum() { } CharSampEnum::~CharSampEnum() { } } // namespace ocrlib
C++
/********************************************************************** * File: bmp_8.h * Description: Declaration of an 8-bit Bitmap 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. * **********************************************************************/ #ifndef BMP8_H #define BMP8_H // The Bmp8 class is an 8-bit bitmap that represents images of // words, characters and segments throughout Cube // It is meant to provide fast access to the bitmap bits and provide // fast scaling, cropping, deslanting, connected components detection, // loading and saving functionality #include <stdlib.h> #include <stdio.h> #include "con_comp.h" #include "cached_file.h" namespace tesseract { // Non-integral deslanting parameters. static const float kMinDeslantAngle = -30.0f; static const float kMaxDeslantAngle = 30.0f; static const float kDeslantAngleDelta = 0.5f; class Bmp8 { public: Bmp8(unsigned short wid, unsigned short hgt); ~Bmp8(); // Clears the bitmap bool Clear(); // accessors to bitmap dimensions inline unsigned short Width() const { return wid_; } inline unsigned short Stride() const { return stride_; } inline unsigned short Height() const { return hgt_; } inline unsigned char *RawData() const { return (line_buff_ == NULL ? NULL : line_buff_[0]); } // creates a scaled version of the specified bitmap // Optionally, scaling can be isotropic (preserving aspect ratio) or not bool ScaleFrom(Bmp8 *bmp, bool isotropic = true); // Deslant the bitmap vertically bool Deslant(); // Deslant the bitmap horizontally bool HorizontalDeslant(double *deslant_angle); // Create a bitmap object from a file static Bmp8 *FromCharDumpFile(CachedFile *fp); static Bmp8 *FromCharDumpFile(FILE *fp); // are two bitmaps identical bool IsIdentical(Bmp8 *pBmp) const; // Detect connected components ConComp ** FindConComps(int *concomp_cnt, int min_size) const; // compute the foreground ratio float ForegroundRatio() const; // returns the mean horizontal histogram entropy of the bitmap float MeanHorizontalHistogramEntropy() const; // returns the horizontal histogram of the bitmap int *HorizontalHistogram() const; private: // Compute a look up tan table that will be used for fast slant computation static bool ComputeTanTable(); // create a bitmap buffer (two flavors char & int) and init contents unsigned char ** CreateBmpBuffer(unsigned char init_val = 0xff); static unsigned int ** CreateBmpBuffer(int wid, int hgt, unsigned char init_val = 0xff); // Free a bitmap buffer static void FreeBmpBuffer(unsigned char **buff); static void FreeBmpBuffer(unsigned int **buff); // a static array that holds the tan lookup table static float *tan_table_; // bitmap 32-bit-aligned stride unsigned short stride_; // Bmp8 magic number used to validate saved bitmaps static const unsigned int kMagicNumber = 0xdeadbeef; protected: // bitmap dimensions unsigned short wid_; unsigned short hgt_; // bitmap contents unsigned char **line_buff_; // deslanting parameters static const int kConCompAllocChunk = 16; static const int kDeslantAngleCount; // Load dimensions & contents of bitmap from file bool LoadFromCharDumpFile(CachedFile *fp); bool LoadFromCharDumpFile(FILE *fp); // Load dimensions & contents of bitmap from raw data bool LoadFromCharDumpFile(unsigned char **raw_data); // Load contents of bitmap from raw data bool LoadFromRawData(unsigned char *data); // save bitmap to a file bool SaveBmp2CharDumpFile(FILE *fp) const; // checks if a row or a column are entirely blank bool IsBlankColumn(int x) const; bool IsBlankRow(int y) const; // crop the bitmap returning new dimensions void Crop(int *xst_src, int *yst_src, int *wid, int *hgt); // copy part of the specified bitmap void Copy(int x, int y, int wid, int hgt, Bmp8 *bmp_dest) const; }; } #endif // BMP8_H
C++
/********************************************************************** * File: bmp_8.cpp * Description: Implementation of an 8-bit Bitmap 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 <stdlib.h> #include <math.h> #include <cstring> #include <algorithm> #include "bmp_8.h" #include "con_comp.h" #include "platform.h" #ifdef USE_STD_NAMESPACE using std::min; using std::max; #endif namespace tesseract { const int Bmp8::kDeslantAngleCount = (1 + static_cast<int>(0.5f + (kMaxDeslantAngle - kMinDeslantAngle) / kDeslantAngleDelta)); float *Bmp8::tan_table_ = NULL; Bmp8::Bmp8(unsigned short wid, unsigned short hgt) : wid_(wid) , hgt_(hgt) { line_buff_ = CreateBmpBuffer(); } Bmp8::~Bmp8() { FreeBmpBuffer(line_buff_); } // free buffer void Bmp8::FreeBmpBuffer(unsigned char **buff) { if (buff != NULL) { if (buff[0] != NULL) { delete []buff[0]; } delete []buff; } } void Bmp8::FreeBmpBuffer(unsigned int **buff) { if (buff != NULL) { if (buff[0] != NULL) { delete []buff[0]; } delete []buff; } } // init bmp buffers unsigned char **Bmp8::CreateBmpBuffer(unsigned char init_val) { unsigned char **buff; // Check valid sizes if (!hgt_ || !wid_) return NULL; // compute stride (align on 4 byte boundries) stride_ = ((wid_ % 4) == 0) ? wid_ : (4 * (1 + (wid_ / 4))); buff = (unsigned char **) new unsigned char *[hgt_ * sizeof(*buff)]; if (!buff) { delete []buff; return NULL; } // alloc and init memory for buffer and line buffer buff[0] = (unsigned char *) new unsigned char[stride_ * hgt_ * sizeof(*buff[0])]; if (!buff[0]) { return NULL; } memset(buff[0], init_val, stride_ * hgt_ * sizeof(*buff[0])); for (int y = 1; y < hgt_; y++) { buff[y] = buff[y -1] + stride_; } return buff; } // init bmp buffers unsigned int ** Bmp8::CreateBmpBuffer(int wid, int hgt, unsigned char init_val) { unsigned int **buff; // compute stride (align on 4 byte boundries) buff = (unsigned int **) new unsigned int *[hgt * sizeof(*buff)]; if (!buff) { delete []buff; return NULL; } // alloc and init memory for buffer and line buffer buff[0] = (unsigned int *) new unsigned int[wid * hgt * sizeof(*buff[0])]; if (!buff[0]) { return NULL; } memset(buff[0], init_val, wid * hgt * sizeof(*buff[0])); for (int y = 1; y < hgt; y++) { buff[y] = buff[y -1] + wid; } return buff; } // clears the contents of the bmp bool Bmp8::Clear() { if (line_buff_ == NULL) { return false; } memset(line_buff_[0], 0xff, stride_ * hgt_ * sizeof(*line_buff_[0])); return true; } bool Bmp8::LoadFromCharDumpFile(CachedFile *fp) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // read and check 32 bit marker if (fp->Read(&val32, sizeof(val32)) != sizeof(val32)) { return false; } if (val32 != kMagicNumber) { return false; } // read wid and hgt if (fp->Read(&wid, sizeof(wid)) != sizeof(wid)) { return false; } if (fp->Read(&hgt, sizeof(hgt)) != sizeof(hgt)) { return false; } // read buf size if (fp->Read(&buf_size, sizeof(buf_size)) != sizeof(buf_size)) { return false; } // validate buf size: for now, only 3 channel (RBG) is supported pix_cnt = wid * hgt; if (buf_size != (3 * pix_cnt)) { return false; } // alloc memory & read the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } if (fp->Read(buff, buf_size) != buf_size) { delete []buff; return false; } // create internal buffers wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { delete []buff; return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (buff[pix] != buff[pix + 1] || buff[pix] != buff[pix + 2]) { delete []buff; return false; } line_buff_[y][x] = buff[pix]; } } // delete temp buffer delete[]buff; return true; } Bmp8 * Bmp8::FromCharDumpFile(CachedFile *fp) { // create a Bmp8 object Bmp8 *bmp_obj = new Bmp8(0, 0); if (bmp_obj == NULL) { return NULL; } if (bmp_obj->LoadFromCharDumpFile(fp) == false) { delete bmp_obj; return NULL; } return bmp_obj; } bool Bmp8::LoadFromCharDumpFile(FILE *fp) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // read and check 32 bit marker if (fread(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } if (val32 != kMagicNumber) { return false; } // read wid and hgt if (fread(&wid, 1, sizeof(wid), fp) != sizeof(wid)) { return false; } if (fread(&hgt, 1, sizeof(hgt), fp) != sizeof(hgt)) { return false; } // read buf size if (fread(&buf_size, 1, sizeof(buf_size), fp) != sizeof(buf_size)) { return false; } // validate buf size: for now, only 3 channel (RBG) is supported pix_cnt = wid * hgt; if (buf_size != (3 * pix_cnt)) { return false; } // alloc memory & read the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } if (fread(buff, 1, buf_size, fp) != buf_size) { delete []buff; return false; } // create internal buffers wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { delete []buff; return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (buff[pix] != buff[pix + 1] || buff[pix] != buff[pix + 2]) { delete []buff; return false; } line_buff_[y][x] = buff[pix]; } } // delete temp buffer delete[]buff; return true; } Bmp8 * Bmp8::FromCharDumpFile(FILE *fp) { // create a Bmp8 object Bmp8 *bmp_obj = new Bmp8(0, 0); if (bmp_obj == NULL) { return NULL; } if (bmp_obj->LoadFromCharDumpFile(fp) == false) { delete bmp_obj; return NULL; } return bmp_obj; } bool Bmp8::IsBlankColumn(int x) const { for (int y = 0; y < hgt_; y++) { if (line_buff_[y][x] != 0xff) { return false; } } return true; } bool Bmp8::IsBlankRow(int y) const { for (int x = 0; x < wid_; x++) { if (line_buff_[y][x] != 0xff) { return false; } } return true; } // crop the bitmap returning new dimensions void Bmp8::Crop(int *xst, int *yst, int *wid, int *hgt) { (*xst) = 0; (*yst) = 0; int xend = wid_ - 1; int yend = hgt_ - 1; while ((*xst) < (wid_ - 1) && (*xst) <= xend) { // column is not empty if (!IsBlankColumn((*xst))) { break; } (*xst)++; } while (xend > 0 && xend >= (*xst)) { // column is not empty if (!IsBlankColumn(xend)) { break; } xend--; } while ((*yst) < (hgt_ - 1) && (*yst) <= yend) { // column is not empty if (!IsBlankRow((*yst))) { break; } (*yst)++; } while (yend > 0 && yend >= (*yst)) { // column is not empty if (!IsBlankRow(yend)) { break; } yend--; } (*wid) = xend - (*xst) + 1; (*hgt) = yend - (*yst) + 1; } // generates a scaled bitmap with dimensions the new bmp will have the // same aspect ratio and will be centered in the box bool Bmp8::ScaleFrom(Bmp8 *bmp, bool isotropic) { int x_num; int x_denom; int y_num; int y_denom; int xoff; int yoff; int xsrc; int ysrc; int xdest; int ydest; int xst_src = 0; int yst_src = 0; int xend_src = bmp->wid_ - 1; int yend_src = bmp->hgt_ - 1; int wid_src; int hgt_src; // src dimensions wid_src = xend_src - xst_src + 1, hgt_src = yend_src - yst_src + 1; // scale to maintain aspect ratio if required if (isotropic) { if ((wid_ * hgt_src) > (hgt_ * wid_src)) { x_num = y_num = hgt_; x_denom = y_denom = hgt_src; } else { x_num = y_num = wid_; x_denom = y_denom = wid_src; } } else { x_num = wid_; y_num = hgt_; x_denom = wid_src; y_denom = hgt_src; } // compute offsets needed to center new bmp xoff = (wid_ - ((x_num * wid_src) / x_denom)) / 2; yoff = (hgt_ - ((y_num * hgt_src) / y_denom)) / 2; // scale up if (y_num > y_denom) { for (ydest = yoff; ydest < (hgt_ - yoff); ydest++) { // compute un-scaled y ysrc = static_cast<int>(0.5 + (1.0 * (ydest - yoff) * y_denom / y_num)); if (ysrc < 0 || ysrc >= hgt_src) { continue; } for (xdest = xoff; xdest < (wid_ - xoff); xdest++) { // compute un-scaled y xsrc = static_cast<int>(0.5 + (1.0 * (xdest - xoff) * x_denom / x_num)); if (xsrc < 0 || xsrc >= wid_src) { continue; } line_buff_[ydest][xdest] = bmp->line_buff_[ysrc + yst_src][xsrc + xst_src]; } } } else { // or scale down // scaling down is a bit tricky: we'll accumulate pixels // and then compute the means unsigned int **dest_line_buff = CreateBmpBuffer(wid_, hgt_, 0), **dest_pix_cnt = CreateBmpBuffer(wid_, hgt_, 0); for (ysrc = 0; ysrc < hgt_src; ysrc++) { // compute scaled y ydest = yoff + static_cast<int>(0.5 + (1.0 * ysrc * y_num / y_denom)); if (ydest < 0 || ydest >= hgt_) { continue; } for (xsrc = 0; xsrc < wid_src; xsrc++) { // compute scaled y xdest = xoff + static_cast<int>(0.5 + (1.0 * xsrc * x_num / x_denom)); if (xdest < 0 || xdest >= wid_) { continue; } dest_line_buff[ydest][xdest] += bmp->line_buff_[ysrc + yst_src][xsrc + xst_src]; dest_pix_cnt[ydest][xdest]++; } } for (ydest = 0; ydest < hgt_; ydest++) { for (xdest = 0; xdest < wid_; xdest++) { if (dest_pix_cnt[ydest][xdest] > 0) { unsigned int pixval = dest_line_buff[ydest][xdest] / dest_pix_cnt[ydest][xdest]; line_buff_[ydest][xdest] = (unsigned char) min((unsigned int)255, pixval); } } } // we no longer need these temp buffers FreeBmpBuffer(dest_line_buff); FreeBmpBuffer(dest_pix_cnt); } return true; } bool Bmp8::LoadFromRawData(unsigned char *data) { unsigned char *pline_data = data; // copy the data for (int y = 0; y < hgt_; y++, pline_data += wid_) { memcpy(line_buff_[y], pline_data, wid_ * sizeof(*pline_data)); } return true; } bool Bmp8::SaveBmp2CharDumpFile(FILE *fp) const { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; int buf_size; int pix; int pix_cnt; unsigned int val32; unsigned char *buff; // write and check 32 bit marker val32 = kMagicNumber; if (fwrite(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } // write wid and hgt wid = wid_; if (fwrite(&wid, 1, sizeof(wid), fp) != sizeof(wid)) { return false; } hgt = hgt_; if (fwrite(&hgt, 1, sizeof(hgt), fp) != sizeof(hgt)) { return false; } // write buf size pix_cnt = wid * hgt; buf_size = 3 * pix_cnt; if (fwrite(&buf_size, 1, sizeof(buf_size), fp) != sizeof(buf_size)) { return false; } // alloc memory & write the 3 channel buffer buff = new unsigned char[buf_size]; if (buff == NULL) { return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { buff[pix] = buff[pix + 1] = buff[pix + 2] = line_buff_[y][x]; } } if (fwrite(buff, 1, buf_size, fp) != buf_size) { delete []buff; return false; } // delete temp buffer delete[]buff; return true; } // copy part of the specified bitmap to the top of the bitmap // does any necessary clipping void Bmp8::Copy(int x_st, int y_st, int wid, int hgt, Bmp8 *bmp_dest) const { int x_end = min(x_st + wid, static_cast<int>(wid_)), y_end = min(y_st + hgt, static_cast<int>(hgt_)); for (int y = y_st; y < y_end; y++) { for (int x = x_st; x < x_end; x++) { bmp_dest->line_buff_[y - y_st][x - x_st] = line_buff_[y][x]; } } } bool Bmp8::IsIdentical(Bmp8 *pBmp) const { if (wid_ != pBmp->wid_ || hgt_ != pBmp->hgt_) { return false; } for (int y = 0; y < hgt_; y++) { if (memcmp(line_buff_[y], pBmp->line_buff_[y], wid_) != 0) { return false; } } return true; } // Detect connected components in the bitmap ConComp ** Bmp8::FindConComps(int *concomp_cnt, int min_size) const { (*concomp_cnt) = 0; unsigned int **out_bmp_array = CreateBmpBuffer(wid_, hgt_, 0); if (out_bmp_array == NULL) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not allocate " "bitmap array\n"); return NULL; } // listed of connected components ConComp **concomp_array = NULL; int x; int y; int x_nbr; int y_nbr; int concomp_id; int alloc_concomp_cnt = 0; // neighbors to check const int nbr_cnt = 4; // relative coordinates of nbrs int x_del[nbr_cnt] = {-1, 0, 1, -1}, y_del[nbr_cnt] = {-1, -1, -1, 0}; for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // is this a foreground pix if (line_buff_[y][x] != 0xff) { int master_concomp_id = 0; ConComp *master_concomp = NULL; // checkout the nbrs for (int nbr = 0; nbr < nbr_cnt; nbr++) { x_nbr = x + x_del[nbr]; y_nbr = y + y_del[nbr]; if (x_nbr < 0 || y_nbr < 0 || x_nbr >= wid_ || y_nbr >= hgt_) { continue; } // is this nbr a foreground pix if (line_buff_[y_nbr][x_nbr] != 0xff) { // get its concomp ID concomp_id = out_bmp_array[y_nbr][x_nbr]; // this should not happen if (concomp_id < 1 || concomp_id > alloc_concomp_cnt) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): illegal " "connected component id: %d\n", concomp_id); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // if we has previously found a component then merge the two // and delete the latest one if (master_concomp != NULL && concomp_id != master_concomp_id) { // relabel all the pts ConCompPt *pt_ptr = concomp_array[concomp_id - 1]->Head(); while (pt_ptr != NULL) { out_bmp_array[pt_ptr->y()][pt_ptr->x()] = master_concomp_id; pt_ptr = pt_ptr->Next(); } // merge the two concomp if (!master_concomp->Merge(concomp_array[concomp_id - 1])) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "merge connected component: %d\n", concomp_id); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // delete the merged concomp delete concomp_array[concomp_id - 1]; concomp_array[concomp_id - 1] = NULL; } else { // this is the first concomp we encounter master_concomp_id = concomp_id; master_concomp = concomp_array[master_concomp_id - 1]; out_bmp_array[y][x] = master_concomp_id; if (!master_concomp->Add(x, y)) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "add connected component (%d,%d)\n", x, y); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } } } // foreground nbr } // nbrs // if there was no foreground pix, then create a new concomp if (master_concomp == NULL) { master_concomp = new ConComp(); if (master_concomp == NULL || master_concomp->Add(x, y) == false) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "allocate or add a connected component\n"); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } // extend the list of concomps if needed if ((alloc_concomp_cnt % kConCompAllocChunk) == 0) { ConComp **temp_con_comp = new ConComp *[alloc_concomp_cnt + kConCompAllocChunk]; if (temp_con_comp == NULL) { fprintf(stderr, "Cube ERROR (Bmp8::FindConComps): could not " "extend array of connected components\n"); FreeBmpBuffer(out_bmp_array); delete []concomp_array; return NULL; } if (alloc_concomp_cnt > 0) { memcpy(temp_con_comp, concomp_array, alloc_concomp_cnt * sizeof(*concomp_array)); delete []concomp_array; } concomp_array = temp_con_comp; } concomp_array[alloc_concomp_cnt++] = master_concomp; out_bmp_array[y][x] = alloc_concomp_cnt; } } // foreground pix } // x } // y // free the concomp bmp FreeBmpBuffer(out_bmp_array); if (alloc_concomp_cnt > 0 && concomp_array != NULL) { // scan the array of connected components and color // the o/p buffer with the corresponding concomps (*concomp_cnt) = 0; ConComp *concomp = NULL; for (int concomp_idx = 0; concomp_idx < alloc_concomp_cnt; concomp_idx++) { concomp = concomp_array[concomp_idx]; // found a concomp if (concomp != NULL) { // add the connected component if big enough if (concomp->PtCnt() > min_size) { concomp->SetLeftMost(true); concomp->SetRightMost(true); concomp->SetID((*concomp_cnt)); concomp_array[(*concomp_cnt)++] = concomp; } else { delete concomp; } } } } return concomp_array; } // precompute the tan table to speedup deslanting bool Bmp8::ComputeTanTable() { int ang_idx; float ang_val; // alloc memory for tan table delete []tan_table_; tan_table_ = new float[kDeslantAngleCount]; if (tan_table_ == NULL) { return false; } for (ang_idx = 0, ang_val = kMinDeslantAngle; ang_idx < kDeslantAngleCount; ang_idx++) { tan_table_[ang_idx] = tan(ang_val * M_PI / 180.0f); ang_val += kDeslantAngleDelta; } return true; } // generates a deslanted bitmap from the passed bitmap. bool Bmp8::Deslant() { int x; int y; int des_x; int des_y; int ang_idx; int best_ang; int min_des_x; int max_des_x; int des_wid; // only do deslanting if bitmap is wide enough // otherwise it slant estimate might not be reliable if (wid_ < (hgt_ * 2)) { return true; } // compute tan table if needed if (tan_table_ == NULL && !ComputeTanTable()) { return false; } // compute min and max values for x after deslant min_des_x = static_cast<int>(0.5f + (hgt_ - 1) * tan_table_[0]); max_des_x = (wid_ - 1) + static_cast<int>(0.5f + (hgt_ - 1) * tan_table_[kDeslantAngleCount - 1]); des_wid = max_des_x - min_des_x + 1; // alloc memory for histograms int **angle_hist = new int*[kDeslantAngleCount]; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { angle_hist[ang_idx] = new int[des_wid]; if (angle_hist[ang_idx] == NULL) { delete[] angle_hist; return false; } memset(angle_hist[ang_idx], 0, des_wid * sizeof(*angle_hist[ang_idx])); } // compute histograms for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { des_y = hgt_ - y - 1; // stamp all histograms for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { des_x = x + static_cast<int>(0.5f + (des_y * tan_table_[ang_idx])); if (des_x >= min_des_x && des_x <= max_des_x) { angle_hist[ang_idx][des_x - min_des_x]++; } } } } } // find the histogram with the lowest entropy float entropy; double best_entropy = 0.0f; double norm_val; best_ang = -1; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { entropy = 0.0f; for (x = min_des_x; x <= max_des_x; x++) { if (angle_hist[ang_idx][x - min_des_x] > 0) { norm_val = (1.0f * angle_hist[ang_idx][x - min_des_x] / hgt_); entropy += (-1.0f * norm_val * log(norm_val)); } } if (best_ang == -1 || entropy < best_entropy) { best_ang = ang_idx; best_entropy = entropy; } // free the histogram delete[] angle_hist[ang_idx]; } delete[] angle_hist; // deslant if (best_ang != -1) { unsigned char **dest_lines; int old_wid = wid_; // create a new buffer wid_ = des_wid; dest_lines = CreateBmpBuffer(); if (dest_lines == NULL) { return false; } for (y = 0; y < hgt_; y++) { for (x = 0; x < old_wid; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { des_y = hgt_ - y - 1; // compute new pos des_x = x + static_cast<int>(0.5f + (des_y * tan_table_[best_ang])); dest_lines[y][des_x - min_des_x] = 0; } } } // free old buffer FreeBmpBuffer(line_buff_); line_buff_ = dest_lines; } return true; } // Load dimensions & contents of bitmap from raw data bool Bmp8::LoadFromCharDumpFile(unsigned char **raw_data_ptr) { unsigned short wid; unsigned short hgt; unsigned short x; unsigned short y; unsigned char *raw_data = (*raw_data_ptr); int buf_size; int pix; unsigned int val32; // read and check 32 bit marker memcpy(&val32, raw_data, sizeof(val32)); raw_data += sizeof(val32); if (val32 != kMagicNumber) { return false; } // read wid and hgt memcpy(&wid, raw_data, sizeof(wid)); raw_data += sizeof(wid); memcpy(&hgt, raw_data, sizeof(hgt)); raw_data += sizeof(hgt); // read buf size memcpy(&buf_size, raw_data, sizeof(buf_size)); raw_data += sizeof(buf_size); // validate buf size: for now, only 3 channel (RBG) is supported if (buf_size != (3 * wid * hgt)) { return false; } wid_ = wid; hgt_ = hgt; line_buff_ = CreateBmpBuffer(); if (line_buff_ == NULL) { return false; } // copy the data for (y = 0, pix = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++, pix += 3) { // for now we only support gray scale, // so we expect R = G = B, it this is not the case, bail out if (raw_data[pix] != raw_data[pix + 1] || raw_data[pix] != raw_data[pix + 2]) { return false; } line_buff_[y][x] = raw_data[pix]; } } (*raw_data_ptr) = raw_data + buf_size; return true; } float Bmp8::ForegroundRatio() const { int fore_cnt = 0; if (wid_ == 0 || hgt_ == 0) { return 1.0; } for (int y = 0; y < hgt_; y++) { for (int x = 0; x < wid_; x++) { fore_cnt += (line_buff_[y][x] == 0xff ? 0 : 1); } } return (1.0 * (fore_cnt / hgt_) / wid_); } // generates a deslanted bitmap from the passed bitmap bool Bmp8::HorizontalDeslant(double *deslant_angle) { int x; int y; int des_y; int ang_idx; int best_ang; int min_des_y; int max_des_y; int des_hgt; // compute tan table if necess. if (tan_table_ == NULL && !ComputeTanTable()) { return false; } // compute min and max values for x after deslant min_des_y = min(0, static_cast<int>((wid_ - 1) * tan_table_[0])); max_des_y = (hgt_ - 1) + max(0, static_cast<int>((wid_ - 1) * tan_table_[kDeslantAngleCount - 1])); des_hgt = max_des_y - min_des_y + 1; // alloc memory for histograms int **angle_hist = new int*[kDeslantAngleCount]; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { angle_hist[ang_idx] = new int[des_hgt]; if (angle_hist[ang_idx] == NULL) { delete[] angle_hist; return false; } memset(angle_hist[ang_idx], 0, des_hgt * sizeof(*angle_hist[ang_idx])); } // compute histograms for (y = 0; y < hgt_; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { // stamp all histograms for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { des_y = y - static_cast<int>(x * tan_table_[ang_idx]); if (des_y >= min_des_y && des_y <= max_des_y) { angle_hist[ang_idx][des_y - min_des_y]++; } } } } } // find the histogram with the lowest entropy float entropy; float best_entropy = 0.0f; float norm_val; best_ang = -1; for (ang_idx = 0; ang_idx < kDeslantAngleCount; ang_idx++) { entropy = 0.0f; for (y = min_des_y; y <= max_des_y; y++) { if (angle_hist[ang_idx][y - min_des_y] > 0) { norm_val = (1.0f * angle_hist[ang_idx][y - min_des_y] / wid_); entropy += (-1.0f * norm_val * log(norm_val)); } } if (best_ang == -1 || entropy < best_entropy) { best_ang = ang_idx; best_entropy = entropy; } // free the histogram delete[] angle_hist[ang_idx]; } delete[] angle_hist; (*deslant_angle) = 0.0; // deslant if (best_ang != -1) { unsigned char **dest_lines; int old_hgt = hgt_; // create a new buffer min_des_y = min(0, static_cast<int>((wid_ - 1) * -tan_table_[best_ang])); max_des_y = (hgt_ - 1) + max(0, static_cast<int>((wid_ - 1) * -tan_table_[best_ang])); hgt_ = max_des_y - min_des_y + 1; dest_lines = CreateBmpBuffer(); if (dest_lines == NULL) { return false; } for (y = 0; y < old_hgt; y++) { for (x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { // compute new pos des_y = y - static_cast<int>((x * tan_table_[best_ang])); dest_lines[des_y - min_des_y][x] = 0; } } } // free old buffer FreeBmpBuffer(line_buff_); line_buff_ = dest_lines; (*deslant_angle) = kMinDeslantAngle + (best_ang * kDeslantAngleDelta); } return true; } float Bmp8::MeanHorizontalHistogramEntropy() const { float entropy = 0.0f; // compute histograms for (int y = 0; y < hgt_; y++) { int pix_cnt = 0; for (int x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { pix_cnt++; } } if (pix_cnt > 0) { float norm_val = (1.0f * pix_cnt / wid_); entropy += (-1.0f * norm_val * log(norm_val)); } } return entropy / hgt_; } int *Bmp8::HorizontalHistogram() const { int *hist = new int[hgt_]; if (hist == NULL) { return NULL; } // compute histograms for (int y = 0; y < hgt_; y++) { hist[y] = 0; for (int x = 0; x < wid_; x++) { // find a non-bkgrnd pixel if (line_buff_[y][x] != 0xff) { hist[y]++; } } } return hist; } } // namespace tesseract
C++
/********************************************************************** * File: string_32.h * Description: Declaration of a 32 Bit string 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 string_32 class provides the functionality needed // for a 32-bit string class #ifndef STRING_32_H #define STRING_32_H #include <string.h> #include <string> #include <algorithm> #include <vector> #ifdef USE_STD_NAMESPACE using std::basic_string; using std::string; using std::vector; #endif namespace tesseract { // basic definitions typedef signed int char_32; typedef basic_string<char_32> string_32; } #endif // STRING_32_H
C++
/********************************************************************** * File: cube_line_object.h * Description: Declaration of the Cube Line Object 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 CubeLineObject implements an objects that holds a line of text // Each line is broken into phrases. Phrases are blocks within the line that // are unambiguously separate collections of words #ifndef CUBE_LINE_OBJECT_H #define CUBE_LINE_OBJECT_H #include "cube_reco_context.h" #include "cube_object.h" #include "allheaders.h" namespace tesseract { class CubeLineObject { public: CubeLineObject(CubeRecoContext *cntxt, Pix *pix); ~CubeLineObject(); // accessors inline int PhraseCount() { if (!processed_ && !Process()) { return 0; } return phrase_cnt_; } inline CubeObject **Phrases() { if (!processed_ && !Process()) { return NULL; } return phrases_; } private: CubeRecoContext *cntxt_; bool own_pix_; bool processed_; Pix *line_pix_; CubeObject **phrases_; int phrase_cnt_; bool Process(); // Compute the least word breaking threshold that is required to produce a // valid set of phrases. Phrases are validated using the Aspect ratio // constraints specified in the language specific Params object int ComputeWordBreakThreshold(int con_comp_cnt, ConComp **con_comps, bool rtl); }; } #endif // CUBE_LINE_OBJECT_H
C++
/********************************************************************** * File: classifier_factory.h * Description: Declaration of the Base Character Classifier * 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 CharClassifierFactory provides a single static method to create an // instance of the desired classifier #ifndef CHAR_CLASSIFIER_FACTORY_H #define CHAR_CLASSIFIER_FACTORY_H #include <string> #include "classifier_base.h" #include "lang_model.h" namespace tesseract { class CharClassifierFactory { public: // Creates a CharClassifier object of the appropriate type depending on the // classifier type in the settings file static CharClassifier *Create(const string &data_file_path, const string &lang, LangModel *lang_mod, CharSet *char_set, TuningParams *params); }; } // tesseract #endif // CHAR_CLASSIFIER_FACTORY_H
C++
/********************************************************************** * File: cube_object.h * Description: Declaration of the Cube Object 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 CubeObject class is the main class used to perform recognition of // a specific char_samp as a single word. // To recognize a word, a CubeObject is constructed for this word. // A Call to RecognizeWord is then issued specifying the language model that // will be used during recognition. If none is specified, the default language // model in the CubeRecoContext is used. The CubeRecoContext is passed at // construction time // // The typical usage pattern for Cube is shown below: // // // Create and initialize Tesseract object and get its // // CubeRecoContext object (note that Tesseract object owns it, // // so it will be freed when the Tesseract object is freed). // tesseract::Tesseract *tess_obj = new tesseract::Tesseract(); // tess_obj->init_tesseract(data_path, lang, tesseract::OEM_CUBE_ONLY); // CubeRecoContext *cntxt = tess_obj->GetCubeRecoContext(); // CHECK(cntxt != NULL) << "Unable to create a Cube reco context"; // . // . // . // // Do this to recognize a word in pix whose co-ordinates are // // (left,top,width,height) // tesseract::CubeObject *cube_obj; // cube_obj = new tesseract::CubeObject(cntxt, pix, // left, top, width, height); // // // Get back Cube's list of answers // tesseract::WordAltList *alt_list = cube_obj->RecognizeWord(); // CHECK(alt_list != NULL && alt_list->AltCount() > 0); // // // Get the string and cost of every alternate // for (int alt = 0; alt < alt_list->AltCount(); alt++) { // // Return the result as a UTF-32 string // string_32 res_str32 = alt_list->Alt(alt); // // Convert to UTF8 if need-be // string res_str; // CubeUtils::UTF32ToUTF8(res_str32.c_str(), &res_str); // // Get the string cost. This should get bigger as you go deeper // // in the list // int cost = alt_list->AltCost(alt); // } // // // Call this once you are done recognizing this word // delete cube_obj; // // // Call this once you are done recognizing all words with // // for the current language // delete tess_obj; // // Note that if the language supports "Italics" (see the CubeRecoContext), the // RecognizeWord function attempts to de-slant the word. #ifndef CUBE_OBJECT_H #define CUBE_OBJECT_H #include "char_samp.h" #include "word_altlist.h" #include "beam_search.h" #include "cube_search_object.h" #include "tess_lang_model.h" #include "cube_reco_context.h" namespace tesseract { // minimum aspect ratio needed to normalize a char_samp before recognition static const float kMinNormalizationAspectRatio = 3.5; // minimum probability a top alt choice must meet before having // deslanted processing applied to it static const float kMinProbSkipDeslanted = 0.25; class CubeObject { public: // Different flavors of constructor. They just differ in the way the // word image is specified CubeObject(CubeRecoContext *cntxt, CharSamp *char_samp); CubeObject(CubeRecoContext *cntxt, Pix *pix, int left, int top, int wid, int hgt); ~CubeObject(); // Perform the word recognition using the specified language mode. If none // is specified, the default language model in the CubeRecoContext is used. // Returns the sorted list of alternate word answers WordAltList *RecognizeWord(LangModel *lang_mod = NULL); // Same as RecognizeWord but recognizes as a phrase WordAltList *RecognizePhrase(LangModel *lang_mod = NULL); // Computes the cost of a specific string. This is done by performing // recognition of a language model that allows only the specified word. // The alternate list(s) will be permanently modified. int WordCost(const char *str); // Recognizes a single character and returns the list of results. CharAltList *RecognizeChar(); // Returns the BeamSearch object that resulted from the last call to // RecognizeWord inline BeamSearch *BeamObj() const { return (deslanted_ == true ? deslanted_beam_obj_ : beam_obj_); } // Returns the WordAltList object that resulted from the last call to // RecognizeWord inline WordAltList *AlternateList() const { return (deslanted_ == true ? deslanted_alt_list_ : alt_list_); } // Returns the CubeSearchObject object that resulted from the last call to // RecognizeWord inline CubeSearchObject *SrchObj() const { return (deslanted_ == true ? deslanted_srch_obj_ : srch_obj_); } // Returns the CharSamp object that resulted from the last call to // RecognizeWord. Note that this object is not necessarily identical to the // one passed at construction time as normalization might have occurred inline CharSamp *CharSample() const { return (deslanted_ == true ? deslanted_char_samp_ : char_samp_); } // Set the ownership of the CharSamp inline void SetCharSampOwnership(bool own_char_samp) { own_char_samp_ = own_char_samp; } protected: // Normalize the CharSamp if its aspect ratio exceeds the below constant. bool Normalize(); private: // minimum segment count needed to normalize a char_samp before recognition static const int kMinNormalizationSegmentCnt = 4; // Data member initialization function void Init(); // Free alternate lists. void Cleanup(); // Perform the actual recognition using the specified language mode. If none // is specified, the default language model in the CubeRecoContext is used. // Returns the sorted list of alternate answers. Called by both // RecognizerWord (word_mode is true) or RecognizePhrase (word mode is false) WordAltList *Recognize(LangModel *lang_mod, bool word_mode); CubeRecoContext *cntxt_; BeamSearch *beam_obj_; BeamSearch *deslanted_beam_obj_; bool own_char_samp_; bool deslanted_; CharSamp *char_samp_; CharSamp *deslanted_char_samp_; CubeSearchObject *srch_obj_; CubeSearchObject *deslanted_srch_obj_; WordAltList *alt_list_; WordAltList *deslanted_alt_list_; }; } #endif // CUBE_OBJECT_H
C++
/********************************************************************** * File: word_altlist.h * Description: Declaration of the Word Alternate List 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 WordAltList abstracts a alternate list of words and their corresponding // costs that result from the word recognition process. The class inherits // from the AltList class // It provides methods to add a new word alternate, its corresponding score and // a tag. #ifndef WORD_ALT_LIST_H #define WORD_ALT_LIST_H #include "altlist.h" namespace tesseract { class WordAltList : public AltList { public: explicit WordAltList(int max_alt); ~WordAltList(); // Sort the list of alternates based on cost void Sort(); // insert an alternate word with the specified cost and tag bool Insert(char_32 *char_ptr, int cost, void *tag = NULL); // returns the alternate string at the specified position inline char_32 * Alt(int alt_idx) { return word_alt_[alt_idx]; } // print each entry of the altlist, both UTF8 and unichar ids, and // their costs, to stderr void PrintDebug(); private: char_32 **word_alt_; }; } // namespace tesseract #endif // WORD_ALT_LIST_H
C++
/********************************************************************** * File: cube_search_object.h * Description: Declaration of the Cube Search Object 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 CubeSearchObject class represents a char_samp (a word bitmap) that is // being searched for characters (or recognizeable entities). // The Class detects the connected components and peforms an oversegmentation // on each ConComp. The result of which is a list of segments that are ordered // in reading order. // The class provided methods that inquire about the number of segments, the // CharSamp corresponding to any segment range and the recognition results // of any segment range // An object of Class CubeSearchObject is used by the BeamSearch algorithm // to recognize a CharSamp into a list of word alternates #ifndef CUBE_SEARCH_OBJECT_H #define CUBE_SEARCH_OBJECT_H #include "search_object.h" #include "char_samp.h" #include "conv_net_classifier.h" #include "cube_reco_context.h" #include "allheaders.h" namespace tesseract { class CubeSearchObject : public SearchObject { public: CubeSearchObject(CubeRecoContext *cntxt, CharSamp *samp); ~CubeSearchObject(); // returns the Segmentation Point count of the CharSamp owned by the class int SegPtCnt(); // Recognize the set of segments given by the specified range and return // a list of possible alternate answers CharAltList * RecognizeSegment(int start_pt, int end_pt); // Returns the CharSamp corresponding to the specified segment range CharSamp *CharSample(int start_pt, int end_pt); // Returns a leptonica box corresponding to the specified segment range Box *CharBox(int start_pt, int end_pt); // Returns the cost of having a space before the specified segmentation pt int SpaceCost(int seg_pt); // Returns the cost of not having a space before the specified // segmentation pt int NoSpaceCost(int seg_pt); // Returns the cost of not having any spaces within the specified range // of segmentation points int NoSpaceCost(int seg_pt, int end_pt); private: // Maximum reasonable segment count static const int kMaxSegmentCnt = 128; // Use cropped samples static const bool kUseCroppedChars; // reading order flag bool rtl_; // cached dimensions of char samp int left_; int itop_; int wid_; int hgt_; // minimum and maximum and possible inter-segment gaps for spaces int min_spc_gap_; int max_spc_gap_; // initialization flag bool init_; // maximum segments per character: Cached from tuning parameters object int max_seg_per_char_; // char sample to be processed CharSamp *samp_; // segment count int segment_cnt_; // segments of the processed char samp ConComp **segments_; // Cache data members: // There are two caches kept; a CharSamp cache and a CharAltList cache // Each is a 2-D array of CharSamp and CharAltList pointers respectively // hence the triple pointer. CharAltList ***reco_cache_; CharSamp ***samp_cache_; // Cached costs of space and no-space after every segment. Computed only // in phrase mode int *space_cost_; int *no_space_cost_; // init and allocate variables, perform segmentation bool Init(); // Cleanup void Cleanup(); // Perform segmentation of the bitmap by detecting connected components, // segmenting each connected component using windowed vertical pixel density // histogram and sorting the resulting segments in reading order // Returns true on success bool Segment(); // validate the segment ranges. inline bool IsValidSegmentRange(int start_pt, int end_pt) { return (end_pt > start_pt && start_pt >= -1 && start_pt < segment_cnt_ && end_pt >= 0 && end_pt <= segment_cnt_ && end_pt <= (start_pt + max_seg_per_char_)); } // computes the space and no space costs at gaps between segments // return true on sucess bool ComputeSpaceCosts(); }; } #endif // CUBE_SEARCH_OBJECT_H
C++
/********************************************************************** * File: lang_mod_edge.h * Description: Declaration of the Language Model Edge Base 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 LangModEdge abstracts an Edge in the language model trie // This is an abstract class that any Language Model Edge should inherit from // It provides methods for: // 1- Returns the class ID corresponding to the edge // 2- If the edge is a valid EndOfWord (EOW) // 3- If the edge is coming from a OutOfDictionary (OOF) state machine // 4- If the edge is a Terminal (has no children) // 5- A Hash of the edge that will be used to retrieve the edge // quickly from the BeamSearch lattice // 6- If two edges are identcial // 7- Returns a verbal description of the edge (use by debuggers) // 8- the language model cost of the edge (if any) // 9- The string corresponding to this edge // 10- Getting and setting the "Root" status of the edge #ifndef LANG_MOD_EDGE_H #define LANG_MOD_EDGE_H #include "cube_tuning_params.h" #include "char_set.h" namespace tesseract { class LangModEdge { public: LangModEdge() {} virtual ~LangModEdge() {} // The string corresponding to this edge virtual const char_32 * EdgeString() const = 0; // Returns the class ID corresponding to the edge virtual int ClassID() const = 0; // If the edge is the root edge virtual bool IsRoot() const = 0; // Set the Root flag virtual void SetRoot(bool flag) = 0; // If the edge is a valid EndOfWord (EOW) virtual bool IsEOW() const = 0; // is the edge is coming from a OutOfDictionary (OOF) state machine virtual bool IsOOD() const = 0; // Is the edge is a Terminal (has no children) virtual bool IsTerminal() const = 0; // Returns A hash of the edge that will be used to retrieve the edge virtual unsigned int Hash() const = 0; // Are the two edges identcial? virtual bool IsIdentical(LangModEdge *edge) const = 0; // a verbal description of the edge (use by debuggers) virtual char *Description() const = 0; // the language model cost of the edge (if any) virtual int PathCost() const = 0; }; } #endif // LANG_MOD_EDGE_H
C++
/********************************************************************** * File: classifier_factory.cpp * Description: Implementation of the Base Character Classifier * 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 <stdio.h> #include <stdlib.h> #include <string> #include "classifier_factory.h" #include "conv_net_classifier.h" #include "feature_base.h" #include "feature_bmp.h" #include "feature_chebyshev.h" #include "feature_hybrid.h" #include "hybrid_neural_net_classifier.h" namespace tesseract { // Creates a CharClassifier object of the appropriate type depending on the // classifier type in the settings file CharClassifier *CharClassifierFactory::Create(const string &data_file_path, const string &lang, LangModel *lang_mod, CharSet *char_set, TuningParams *params) { // create the feature extraction object FeatureBase *feat_extract; switch (params->TypeFeature()) { case TuningParams::BMP: feat_extract = new FeatureBmp(params); break; case TuningParams::CHEBYSHEV: feat_extract = new FeatureChebyshev(params); break; case TuningParams::HYBRID: feat_extract = new FeatureHybrid(params); break; default: fprintf(stderr, "Cube ERROR (CharClassifierFactory::Create): invalid " "feature type.\n"); return NULL; } if (feat_extract == NULL) { fprintf(stderr, "Cube ERROR (CharClassifierFactory::Create): unable " "to instantiate feature extraction object.\n"); return NULL; } // create the classifier object CharClassifier *classifier_obj; switch (params->TypeClassifier()) { case TuningParams::NN: classifier_obj = new ConvNetCharClassifier(char_set, params, feat_extract); break; case TuningParams::HYBRID_NN: classifier_obj = new HybridNeuralNetCharClassifier(char_set, params, feat_extract); break; default: fprintf(stderr, "Cube ERROR (CharClassifierFactory::Create): invalid " "classifier type.\n"); return NULL; } if (classifier_obj == NULL) { fprintf(stderr, "Cube ERROR (CharClassifierFactory::Create): error " "allocating memory for character classifier object.\n"); return NULL; } // Init the classifier if (!classifier_obj->Init(data_file_path, lang, lang_mod)) { delete classifier_obj; fprintf(stderr, "Cube ERROR (CharClassifierFactory::Create): unable " "to Init() character classifier object.\n"); return NULL; } return classifier_obj; } }
C++
/********************************************************************** * File: char_samp.h * Description: Declaration of a Character Bitmap Sample 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 CharSamp inherits the Bmp8 class that represents images of // words, characters and segments throughout Cube // CharSamp adds more data members to hold the physical location of the image // in a page, page number in a book if available. // It also holds the label (GT) of the image that might correspond to a single // character or a word // It also provides methods for segmenting, scaling and cropping of the sample #ifndef CHAR_SAMP_H #define CHAR_SAMP_H #include <stdlib.h> #include <stdio.h> #include <string> #include "bmp_8.h" #include "string_32.h" namespace tesseract { class CharSamp : public Bmp8 { public: CharSamp(); CharSamp(int wid, int hgt); CharSamp(int left, int top, int wid, int hgt); ~CharSamp(); // accessor methods unsigned short Left() const { return left_; } unsigned short Right() const { return left_ + wid_; } unsigned short Top() const { return top_; } unsigned short Bottom() const { return top_ + hgt_; } unsigned short Page() const { return page_; } unsigned short NormTop() const { return norm_top_; } unsigned short NormBottom() const { return norm_bottom_; } unsigned short NormAspectRatio() const { return norm_aspect_ratio_; } unsigned short FirstChar() const { return first_char_; } unsigned short LastChar() const { return last_char_; } char_32 Label() const { if (label32_ == NULL || LabelLen() != 1) { return 0; } return label32_[0]; } char_32 * StrLabel() const { return label32_; } string stringLabel() const; void SetLeft(unsigned short left) { left_ = left; } void SetTop(unsigned short top) { top_ = top; } void SetPage(unsigned short page) { page_ = page; } void SetLabel(char_32 label) { if (label32_ != NULL) { delete []label32_; } label32_ = new char_32[2]; if (label32_ != NULL) { label32_[0] = label; label32_[1] = 0; } } void SetLabel(const char_32 *label32) { if (label32_ != NULL) { delete []label32_; label32_ = NULL; } if (label32 != NULL) { // remove any byte order markes if any if (label32[0] == 0xfeff) { label32++; } int len = LabelLen(label32); label32_ = new char_32[len + 1]; if (label32_ != NULL) { memcpy(label32_, label32, len * sizeof(*label32)); label32_[len] = 0; } } } void SetLabel(string str); void SetNormTop(unsigned short norm_top) { norm_top_ = norm_top; } void SetNormBottom(unsigned short norm_bottom) { norm_bottom_ = norm_bottom; } void SetNormAspectRatio(unsigned short norm_aspect_ratio) { norm_aspect_ratio_ = norm_aspect_ratio; } void SetFirstChar(unsigned short first_char) { first_char_ = first_char; } void SetLastChar(unsigned short last_char) { last_char_ = last_char; } // Saves the charsamp to a dump file bool Save2CharDumpFile(FILE *fp) const; // Crops the underlying image and returns a new CharSamp with the // same character information but new dimensions. Warning: does not // necessarily set the normalized top and bottom correctly since // those depend on its location within the word (or CubeSearchObject). CharSamp *Crop(); // Computes the connected components of the char sample ConComp **Segment(int *seg_cnt, bool right_2_left, int max_hist_wnd, int min_con_comp_size) const; // returns a copy of the charsamp that is scaled to the // specified width and height CharSamp *Scale(int wid, int hgt, bool isotropic = true); // returns a Clone of the charsample CharSamp *Clone() const; // computes the features corresponding to the char sample bool ComputeFeatures(int conv_grid_size, float *features); // Load a Char Samp from a dump file static CharSamp *FromCharDumpFile(CachedFile *fp); static CharSamp *FromCharDumpFile(FILE *fp); static CharSamp *FromCharDumpFile(unsigned char **raw_data); static CharSamp *FromRawData(int left, int top, int wid, int hgt, unsigned char *data); static CharSamp *FromConComps(ConComp **concomp_array, int strt_concomp, int seg_flags_size, int *seg_flags, bool *left_most, bool *right_most, int word_hgt); static int AuxFeatureCnt() { return (5); } // Return the length of the label string int LabelLen() const { return LabelLen(label32_); } static int LabelLen(const char_32 *label32) { if (label32 == NULL) { return 0; } int len = 0; while (label32[++len] != 0); return len; } private: char_32 * label32_; unsigned short page_; unsigned short left_; unsigned short top_; // top of sample normalized to a word height of 255 unsigned short norm_top_; // bottom of sample normalized to a word height of 255 unsigned short norm_bottom_; // 255 * ratio of character width to (width + height) unsigned short norm_aspect_ratio_; unsigned short first_char_; unsigned short last_char_; }; } #endif // CHAR_SAMP_H
C++
/********************************************************************** * File: lang_model.h * Description: Declaration of the Language Model Edge Base 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 LanguageModel class abstracts a State machine that is modeled as a Trie // structure. The state machine models the language being recognized by the OCR // Engine // This is an abstract class that is to be inherited by any language model #ifndef LANG_MODEL_H #define LANG_MODEL_H #include "lang_mod_edge.h" #include "char_altlist.h" #include "char_set.h" #include "tuning_params.h" namespace tesseract { class LangModel { public: LangModel() { ood_enabled_ = true; numeric_enabled_ = true; word_list_enabled_ = true; punc_enabled_ = true; } virtual ~LangModel() {} // Returns an edge pointer to the Root virtual LangModEdge *Root() = 0; // Returns the edges that fan-out of the specified edge and their count virtual LangModEdge **GetEdges(CharAltList *alt_list, LangModEdge *parent_edge, int *edge_cnt) = 0; // Returns is a sequence of 32-bit characters are valid within this language // model or net. And EndOfWord flag is specified. If true, the sequence has // to end on a valid word. The function also optionally returns the list // of language model edges traversed to parse the string virtual bool IsValidSequence(const char_32 *str, bool eow_flag, LangModEdge **edge_array = NULL) = 0; virtual bool IsLeadingPunc(char_32 ch) = 0; virtual bool IsTrailingPunc(char_32 ch) = 0; virtual bool IsDigit(char_32 ch) = 0; // accessor functions inline bool OOD() { return ood_enabled_; } inline bool Numeric() { return numeric_enabled_; } inline bool WordList() { return word_list_enabled_; } inline bool Punc() { return punc_enabled_; } inline void SetOOD(bool ood) { ood_enabled_ = ood; } inline void SetNumeric(bool numeric) { numeric_enabled_ = numeric; } inline void SetWordList(bool word_list) { word_list_enabled_ = word_list; } inline void SetPunc(bool punc_enabled) { punc_enabled_ = punc_enabled; } protected: bool ood_enabled_; bool numeric_enabled_; bool word_list_enabled_; bool punc_enabled_; }; } #endif // LANG_MODEL_H
C++
/********************************************************************** * File: tess_lang_model.cpp * Description: Implementation 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. * **********************************************************************/ // The TessLangModel class abstracts the Tesseract language model. It inherits // from the LangModel class. The Tesseract language model encompasses several // Dawgs (words from training data, punctuation, numbers, document words). // On top of this Cube adds an OOD state machine // The class provides methods to traverse the language model in a generative // fashion. Given any node in the DAWG, the language model can generate a list // of children (or fan-out) edges #include <string> #include <vector> #include "char_samp.h" #include "cube_utils.h" #include "dict.h" #include "tesseractclass.h" #include "tess_lang_model.h" #include "tessdatamanager.h" #include "unicharset.h" namespace tesseract { // max fan-out (used for preallocation). Initialized here, but modified by // constructor int TessLangModel::max_edge_ = 4096; // Language model extra State machines const Dawg *TessLangModel::ood_dawg_ = reinterpret_cast<Dawg *>(DAWG_OOD); const Dawg *TessLangModel::number_dawg_ = reinterpret_cast<Dawg *>(DAWG_NUMBER); // number state machine const int TessLangModel::num_state_machine_[kStateCnt][kNumLiteralCnt] = { {0, 1, 1, NUM_TRM, NUM_TRM}, {NUM_TRM, 1, 1, 3, 2}, {NUM_TRM, NUM_TRM, 1, NUM_TRM, 2}, {NUM_TRM, NUM_TRM, 3, NUM_TRM, 2}, }; const int TessLangModel::num_max_repeat_[kStateCnt] = {3, 32, 8, 3}; // thresholds and penalties int TessLangModel::max_ood_shape_cost_ = CubeUtils::Prob2Cost(1e-4); TessLangModel::TessLangModel(const string &lm_params, const string &data_file_path, bool load_system_dawg, TessdataManager *tessdata_manager, CubeRecoContext *cntxt) { cntxt_ = cntxt; has_case_ = cntxt_->HasCase(); // Load the rest of the language model elements from file LoadLangModelElements(lm_params); // Load word_dawgs_ if needed. if (tessdata_manager->SeekToStart(TESSDATA_CUBE_UNICHARSET)) { word_dawgs_ = new DawgVector(); if (load_system_dawg && tessdata_manager->SeekToStart(TESSDATA_CUBE_SYSTEM_DAWG)) { // The last parameter to the Dawg constructor (the debug level) is set to // false, until Cube has a way to express its preferred debug level. *word_dawgs_ += new SquishedDawg(tessdata_manager->GetDataFilePtr(), DAWG_TYPE_WORD, cntxt_->Lang().c_str(), SYSTEM_DAWG_PERM, false); } } else { word_dawgs_ = NULL; } } // Cleanup an edge array void TessLangModel::FreeEdges(int edge_cnt, LangModEdge **edge_array) { if (edge_array != NULL) { for (int edge_idx = 0; edge_idx < edge_cnt; edge_idx++) { if (edge_array[edge_idx] != NULL) { delete edge_array[edge_idx]; } } delete []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 TessLangModel::IsValidSequence(LangModEdge *edge, const char_32 *sequence, bool eow_flag, LangModEdge **final_edge) { // get the edges emerging from this edge int edge_cnt = 0; LangModEdge **edge_array = GetEdges(NULL, edge, &edge_cnt); // find the 1st char in the sequence in the children for (int edge_idx = 0; edge_idx < edge_cnt; edge_idx++) { // found a match if (sequence[0] == edge_array[edge_idx]->EdgeString()[0]) { // if this is the last char if (sequence[1] == 0) { // succeed if we are in prefix mode or this is a terminal edge if (eow_flag == false || edge_array[edge_idx]->IsEOW()) { if (final_edge != NULL) { (*final_edge) = edge_array[edge_idx]; edge_array[edge_idx] = NULL; } FreeEdges(edge_cnt, edge_array); return true; } } else { // not the last char continue checking if (IsValidSequence(edge_array[edge_idx], sequence + 1, eow_flag, final_edge) == true) { FreeEdges(edge_cnt, edge_array); return true; } } } } FreeEdges(edge_cnt, edge_array); return false; } // 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 TessLangModel::IsValidSequence(const char_32 *sequence, bool eow_flag, LangModEdge **final_edge) { if (final_edge != NULL) { (*final_edge) = NULL; } return IsValidSequence(NULL, sequence, eow_flag, final_edge); } bool TessLangModel::IsLeadingPunc(const char_32 ch) { return lead_punc_.find(ch) != string::npos; } bool TessLangModel::IsTrailingPunc(const char_32 ch) { return trail_punc_.find(ch) != string::npos; } bool TessLangModel::IsDigit(const char_32 ch) { return digits_.find(ch) != string::npos; } // 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 ** TessLangModel::GetEdges(CharAltList *alt_list, LangModEdge *lang_mod_edge, int *edge_cnt) { TessLangModEdge *tess_lm_edge = reinterpret_cast<TessLangModEdge *>(lang_mod_edge); LangModEdge **edge_array = NULL; (*edge_cnt) = 0; // if we are starting from the root, we'll instantiate every DAWG // and get the all the edges that emerge from the root if (tess_lm_edge == NULL) { // get DAWG count from Tesseract int dawg_cnt = NumDawgs(); // preallocate the edge buffer (*edge_cnt) = dawg_cnt * max_edge_; edge_array = new LangModEdge *[(*edge_cnt)]; if (edge_array == NULL) { return NULL; } for (int dawg_idx = (*edge_cnt) = 0; dawg_idx < dawg_cnt; dawg_idx++) { const Dawg *curr_dawg = GetDawg(dawg_idx); // Only look through word Dawgs (since there is a special way of // handling numbers and punctuation). if (curr_dawg->type() == DAWG_TYPE_WORD) { (*edge_cnt) += FanOut(alt_list, curr_dawg, 0, 0, NULL, true, edge_array + (*edge_cnt)); } } // dawg (*edge_cnt) += FanOut(alt_list, number_dawg_, 0, 0, NULL, true, edge_array + (*edge_cnt)); // OOD: it is intentionally not added to the list to make sure it comes // at the end (*edge_cnt) += FanOut(alt_list, ood_dawg_, 0, 0, NULL, true, edge_array + (*edge_cnt)); // set the root flag for all root edges for (int edge_idx = 0; edge_idx < (*edge_cnt); edge_idx++) { edge_array[edge_idx]->SetRoot(true); } } else { // not starting at the root // preallocate the edge buffer (*edge_cnt) = max_edge_; // allocate memory for edges edge_array = new LangModEdge *[(*edge_cnt)]; if (edge_array == NULL) { return NULL; } // get the FanOut edges from the root of each dawg (*edge_cnt) = FanOut(alt_list, tess_lm_edge->GetDawg(), tess_lm_edge->EndEdge(), tess_lm_edge->EdgeMask(), tess_lm_edge->EdgeString(), false, edge_array); } return edge_array; } // generate edges from an NULL terminated string // (used for punctuation, operators and digits) int TessLangModel::Edges(const char *strng, const Dawg *dawg, EDGE_REF edge_ref, EDGE_REF edge_mask, LangModEdge **edge_array) { int edge_idx, edge_cnt = 0; for (edge_idx = 0; strng[edge_idx] != 0; edge_idx++) { int class_id = cntxt_->CharacterSet()->ClassID((char_32)strng[edge_idx]); if (class_id != INVALID_UNICHAR_ID) { // create an edge object edge_array[edge_cnt] = new TessLangModEdge(cntxt_, dawg, edge_ref, class_id); if (edge_array[edge_cnt] == NULL) { return 0; } reinterpret_cast<TessLangModEdge *>(edge_array[edge_cnt])-> SetEdgeMask(edge_mask); edge_cnt++; } } return edge_cnt; } // generate OOD edges int TessLangModel::OODEdges(CharAltList *alt_list, EDGE_REF edge_ref, EDGE_REF edge_ref_mask, LangModEdge **edge_array) { int class_cnt = cntxt_->CharacterSet()->ClassCount(); int edge_cnt = 0; for (int class_id = 0; class_id < class_cnt; class_id++) { // produce an OOD edge only if the cost of the char is low enough if ((alt_list == NULL || alt_list->ClassCost(class_id) <= max_ood_shape_cost_)) { // create an edge object edge_array[edge_cnt] = new TessLangModEdge(cntxt_, class_id); if (edge_array[edge_cnt] == NULL) { return 0; } edge_cnt++; } } return edge_cnt; } // computes and returns the edges that fan out of an edge ref int TessLangModel::FanOut(CharAltList *alt_list, const Dawg *dawg, EDGE_REF edge_ref, EDGE_REF edge_mask, const char_32 *str, bool root_flag, LangModEdge **edge_array) { int edge_cnt = 0; NODE_REF next_node = NO_EDGE; // OOD if (dawg == reinterpret_cast<Dawg *>(DAWG_OOD)) { if (ood_enabled_ == true) { return OODEdges(alt_list, edge_ref, edge_mask, edge_array); } else { return 0; } } else if (dawg == reinterpret_cast<Dawg *>(DAWG_NUMBER)) { // Number if (numeric_enabled_ == true) { return NumberEdges(edge_ref, edge_array); } else { return 0; } } else if (IsTrailingPuncEdge(edge_mask)) { // a TRAILING PUNC MASK, generate more trailing punctuation and return if (punc_enabled_ == true) { EDGE_REF trail_cnt = TrailingPuncCount(edge_mask); return Edges(trail_punc_.c_str(), dawg, edge_ref, TrailingPuncEdgeMask(trail_cnt + 1), edge_array); } else { return 0; } } else if (root_flag == true || edge_ref == 0) { // Root, generate leading punctuation and continue if (root_flag) { if (punc_enabled_ == true) { edge_cnt += Edges(lead_punc_.c_str(), dawg, 0, LEAD_PUNC_EDGE_REF_MASK, edge_array); } } next_node = 0; } else { // a node in the main trie bool eow_flag = (dawg->end_of_word(edge_ref) != 0); // for EOW if (eow_flag == true) { // generate trailing punctuation if (punc_enabled_ == true) { edge_cnt += Edges(trail_punc_.c_str(), dawg, edge_ref, TrailingPuncEdgeMask((EDGE_REF)1), edge_array); // generate a hyphen and go back to the root edge_cnt += Edges("-/", dawg, 0, 0, edge_array + edge_cnt); } } // advance node next_node = dawg->next_node(edge_ref); if (next_node == 0 || next_node == NO_EDGE) { return edge_cnt; } } // now get all the emerging edges if word list is enabled if (word_list_enabled_ == true && next_node != NO_EDGE) { // create child edges int child_edge_cnt = TessLangModEdge::CreateChildren(cntxt_, dawg, next_node, edge_array + edge_cnt); int strt_cnt = edge_cnt; // set the edge mask for (int child = 0; child < child_edge_cnt; child++) { reinterpret_cast<TessLangModEdge *>(edge_array[edge_cnt++])-> SetEdgeMask(edge_mask); } // if we are at the root, create upper case forms of these edges if possible if (root_flag == true) { for (int child = 0; child < child_edge_cnt; child++) { TessLangModEdge *child_edge = reinterpret_cast<TessLangModEdge *>(edge_array[strt_cnt + child]); if (has_case_ == true) { const char_32 *edge_str = child_edge->EdgeString(); if (edge_str != NULL && islower(edge_str[0]) != 0 && edge_str[1] == 0) { int class_id = cntxt_->CharacterSet()->ClassID(toupper(edge_str[0])); if (class_id != INVALID_UNICHAR_ID) { // generate an upper case edge for lower case chars edge_array[edge_cnt] = new TessLangModEdge(cntxt_, dawg, child_edge->StartEdge(), child_edge->EndEdge(), class_id); if (edge_array[edge_cnt] != NULL) { reinterpret_cast<TessLangModEdge *>(edge_array[edge_cnt])-> SetEdgeMask(edge_mask); edge_cnt++; } } } } } } } return edge_cnt; } // Generate the edges fanning-out from an edge in the number state machine int TessLangModel::NumberEdges(EDGE_REF edge_ref, LangModEdge **edge_array) { EDGE_REF new_state, state; inT64 repeat_cnt, new_repeat_cnt; state = ((edge_ref & NUMBER_STATE_MASK) >> NUMBER_STATE_SHIFT); repeat_cnt = ((edge_ref & NUMBER_REPEAT_MASK) >> NUMBER_REPEAT_SHIFT); if (state < 0 || state >= kStateCnt) { return 0; } // go thru all valid transitions from the state int edge_cnt = 0; EDGE_REF new_edge_ref; for (int lit = 0; lit < kNumLiteralCnt; lit++) { // move to the new state new_state = num_state_machine_[state][lit]; if (new_state == NUM_TRM) { continue; } if (new_state == state) { new_repeat_cnt = repeat_cnt + 1; } else { new_repeat_cnt = 1; } // not allowed to repeat beyond this if (new_repeat_cnt > num_max_repeat_[state]) { continue; } new_edge_ref = (new_state << NUMBER_STATE_SHIFT) | (lit << NUMBER_LITERAL_SHIFT) | (new_repeat_cnt << NUMBER_REPEAT_SHIFT); edge_cnt += Edges(literal_str_[lit]->c_str(), number_dawg_, new_edge_ref, 0, edge_array + edge_cnt); } return edge_cnt; } // Loads Language model elements from contents of the <lang>.cube.lm file bool TessLangModel::LoadLangModelElements(const string &lm_params) { bool success = true; // split into lines, each corresponding to a token type below vector<string> str_vec; CubeUtils::SplitStringUsing(lm_params, "\r\n", &str_vec); for (int entry = 0; entry < str_vec.size(); entry++) { vector<string> tokens; // should be only two tokens: type and value CubeUtils::SplitStringUsing(str_vec[entry], "=", &tokens); if (tokens.size() != 2) success = false; if (tokens[0] == "LeadPunc") { lead_punc_ = tokens[1]; } else if (tokens[0] == "TrailPunc") { trail_punc_ = tokens[1]; } else if (tokens[0] == "NumLeadPunc") { num_lead_punc_ = tokens[1]; } else if (tokens[0] == "NumTrailPunc") { num_trail_punc_ = tokens[1]; } else if (tokens[0] == "Operators") { operators_ = tokens[1]; } else if (tokens[0] == "Digits") { digits_ = tokens[1]; } else if (tokens[0] == "Alphas") { alphas_ = tokens[1]; } else { success = false; } } RemoveInvalidCharacters(&num_lead_punc_); RemoveInvalidCharacters(&num_trail_punc_); RemoveInvalidCharacters(&digits_); RemoveInvalidCharacters(&operators_); RemoveInvalidCharacters(&alphas_); // form the array of literal strings needed for number state machine // It is essential that the literal strings go in the order below literal_str_[0] = &num_lead_punc_; literal_str_[1] = &num_trail_punc_; literal_str_[2] = &digits_; literal_str_[3] = &operators_; literal_str_[4] = &alphas_; return success; } void TessLangModel::RemoveInvalidCharacters(string *lm_str) { CharSet *char_set = cntxt_->CharacterSet(); tesseract::string_32 lm_str32; CubeUtils::UTF8ToUTF32(lm_str->c_str(), &lm_str32); int len = CubeUtils::StrLen(lm_str32.c_str()); char_32 *clean_str32 = new char_32[len + 1]; if (!clean_str32) return; int clean_len = 0; for (int i = 0; i < len; ++i) { int class_id = char_set->ClassID((char_32)lm_str32[i]); if (class_id != INVALID_UNICHAR_ID) { clean_str32[clean_len] = lm_str32[i]; ++clean_len; } } clean_str32[clean_len] = 0; if (clean_len < len) { lm_str->clear(); CubeUtils::UTF32ToUTF8(clean_str32, lm_str); } delete [] clean_str32; } int TessLangModel::NumDawgs() const { return (word_dawgs_ != NULL) ? word_dawgs_->size() : cntxt_->TesseractObject()->getDict().NumDawgs(); } // Returns the dawgs with the given index from either the dawgs // stored by the Tesseract object, or the word_dawgs_. const Dawg *TessLangModel::GetDawg(int index) const { if (word_dawgs_ != NULL) { ASSERT_HOST(index < word_dawgs_->size()); return (*word_dawgs_)[index]; } else { ASSERT_HOST(index < cntxt_->TesseractObject()->getDict().NumDawgs()); return cntxt_->TesseractObject()->getDict().GetDawg(index); } } }
C++
/********************************************************************** * File: char_bigrams.cpp * Description: Implementation of a Character Bigrams 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 <algorithm> #include <math.h> #include <string> #include <vector> #include "char_bigrams.h" #include "cube_utils.h" #include "ndminx.h" #include "cube_const.h" namespace tesseract { CharBigrams::CharBigrams() { memset(&bigram_table_, 0, sizeof(bigram_table_)); } CharBigrams::~CharBigrams() { if (bigram_table_.char_bigram != NULL) { for (int ch1 = 0; ch1 <= bigram_table_.max_char; ch1++) { CharBigram *char_bigram = bigram_table_.char_bigram + ch1; if (char_bigram->bigram != NULL) { delete []char_bigram->bigram; } } delete []bigram_table_.char_bigram; } } CharBigrams *CharBigrams::Create(const string &data_file_path, const string &lang) { string file_name; string str; file_name = data_file_path + lang; file_name += ".cube.bigrams"; // load the string into memory if (!CubeUtils::ReadFileToString(file_name, &str)) { return NULL; } // construct a new object CharBigrams *char_bigrams_obj = new CharBigrams(); if (char_bigrams_obj == NULL) { fprintf(stderr, "Cube ERROR (CharBigrams::Create): could not create " "character bigrams object.\n"); return NULL; } CharBigramTable *table = &char_bigrams_obj->bigram_table_; table->total_cnt = 0; table->max_char = -1; table->char_bigram = NULL; // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(str, "\r\n", &str_vec); for (int big = 0; big < str_vec.size(); big++) { char_32 ch1; char_32 ch2; int cnt; if (sscanf(str_vec[big].c_str(), "%d %x %x", &cnt, &ch1, &ch2) != 3) { fprintf(stderr, "Cube ERROR (CharBigrams::Create): invalid format " "reading line: %s\n", str_vec[big].c_str()); delete char_bigrams_obj; return NULL; } // expand the bigram table if (ch1 > table->max_char) { CharBigram *char_bigram = new CharBigram[ch1 + 1]; if (char_bigram == NULL) { fprintf(stderr, "Cube ERROR (CharBigrams::Create): error allocating " "additional memory for character bigram table.\n"); return NULL; } if (table->char_bigram != NULL && table->max_char >= 0) { memcpy(char_bigram, table->char_bigram, (table->max_char + 1) * sizeof(*char_bigram)); delete []table->char_bigram; } table->char_bigram = char_bigram; // init for (int new_big = table->max_char + 1; new_big <= ch1; new_big++) { table->char_bigram[new_big].total_cnt = 0; table->char_bigram[new_big].max_char = -1; table->char_bigram[new_big].bigram = NULL; } table->max_char = ch1; } if (ch2 > table->char_bigram[ch1].max_char) { Bigram *bigram = new Bigram[ch2 + 1]; if (bigram == NULL) { fprintf(stderr, "Cube ERROR (CharBigrams::Create): error allocating " "memory for bigram.\n"); delete char_bigrams_obj; return NULL; } if (table->char_bigram[ch1].bigram != NULL && table->char_bigram[ch1].max_char >= 0) { memcpy(bigram, table->char_bigram[ch1].bigram, (table->char_bigram[ch1].max_char + 1) * sizeof(*bigram)); delete []table->char_bigram[ch1].bigram; } table->char_bigram[ch1].bigram = bigram; // init for (int new_big = table->char_bigram[ch1].max_char + 1; new_big <= ch2; new_big++) { table->char_bigram[ch1].bigram[new_big].cnt = 0; } table->char_bigram[ch1].max_char = ch2; } table->char_bigram[ch1].bigram[ch2].cnt = cnt; table->char_bigram[ch1].total_cnt += cnt; table->total_cnt += cnt; } // compute costs (-log probs) table->worst_cost = static_cast<int>( -PROB2COST_SCALE * log(0.5 / table->total_cnt)); for (char_32 ch1 = 0; ch1 <= table->max_char; ch1++) { for (char_32 ch2 = 0; ch2 <= table->char_bigram[ch1].max_char; ch2++) { int cnt = table->char_bigram[ch1].bigram[ch2].cnt; table->char_bigram[ch1].bigram[ch2].cost = static_cast<int>(-PROB2COST_SCALE * log(MAX(0.5, static_cast<double>(cnt)) / table->total_cnt)); } } return char_bigrams_obj; } int CharBigrams::PairCost(char_32 ch1, char_32 ch2) const { if (ch1 > bigram_table_.max_char) { return bigram_table_.worst_cost; } if (ch2 > bigram_table_.char_bigram[ch1].max_char) { return bigram_table_.worst_cost; } return bigram_table_.char_bigram[ch1].bigram[ch2].cost; } int CharBigrams::Cost(const char_32 *char_32_ptr, CharSet *char_set) const { if (!char_32_ptr || char_32_ptr[0] == 0) { return bigram_table_.worst_cost; } int cost = MeanCostWithSpaces(char_32_ptr); if (CubeUtils::StrLen(char_32_ptr) >= kMinLengthCaseInvariant && CubeUtils::IsCaseInvariant(char_32_ptr, char_set)) { char_32 *lower_32 = CubeUtils::ToLower(char_32_ptr, char_set); if (lower_32 && lower_32[0] != 0) { int cost_lower = MeanCostWithSpaces(lower_32); cost = MIN(cost, cost_lower); delete [] lower_32; } char_32 *upper_32 = CubeUtils::ToUpper(char_32_ptr, char_set); if (upper_32 && upper_32[0] != 0) { int cost_upper = MeanCostWithSpaces(upper_32); cost = MIN(cost, cost_upper); delete [] upper_32; } } return cost; } int CharBigrams::MeanCostWithSpaces(const char_32 *char_32_ptr) const { if (!char_32_ptr) return bigram_table_.worst_cost; int len = CubeUtils::StrLen(char_32_ptr); int cost = 0; int c = 0; cost = PairCost(' ', char_32_ptr[0]); for (c = 1; c < len; c++) { cost += PairCost(char_32_ptr[c - 1], char_32_ptr[c]); } cost += PairCost(char_32_ptr[len - 1], ' '); return static_cast<int>(cost / static_cast<double>(len + 1)); } } // namespace tesseract
C++
/********************************************************************** * File: beam_search.cpp * Description: Class to implement Beam Word Search Algorithm * 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 <algorithm> #include "beam_search.h" #include "tesseractclass.h" namespace tesseract { BeamSearch::BeamSearch(CubeRecoContext *cntxt, bool word_mode) { cntxt_ = cntxt; seg_pt_cnt_ = 0; col_cnt_ = 1; col_ = NULL; word_mode_ = word_mode; } // Cleanup the lattice corresponding to the last search void BeamSearch::Cleanup() { if (col_ != NULL) { for (int col = 0; col < col_cnt_; col++) { if (col_[col]) delete col_[col]; } delete []col_; } col_ = NULL; } BeamSearch::~BeamSearch() { Cleanup(); } // Creates a set of children nodes emerging from a parent node based on // the character alternate list and the language model. void BeamSearch::CreateChildren(SearchColumn *out_col, LangModel *lang_mod, SearchNode *parent_node, LangModEdge *lm_parent_edge, CharAltList *char_alt_list, int extra_cost) { // get all the edges from this parent int edge_cnt; LangModEdge **lm_edges = lang_mod->GetEdges(char_alt_list, lm_parent_edge, &edge_cnt); if (lm_edges) { // add them to the ending column with the appropriate parent for (int edge = 0; edge < edge_cnt; edge++) { // add a node to the column if the current column is not the // last one, or if the lang model edge indicates it is valid EOW if (!cntxt_->NoisyInput() && out_col->ColIdx() >= seg_pt_cnt_ && !lm_edges[edge]->IsEOW()) { // free edge since no object is going to own it delete lm_edges[edge]; continue; } // compute the recognition cost of this node int recognition_cost = MIN_PROB_COST; if (char_alt_list && char_alt_list->AltCount() > 0) { recognition_cost = MAX(0, char_alt_list->ClassCost( lm_edges[edge]->ClassID())); // Add the no space cost. This should zero in word mode recognition_cost += extra_cost; } // Note that the edge will be freed inside the column if // AddNode is called if (recognition_cost >= 0) { out_col->AddNode(lm_edges[edge], recognition_cost, parent_node, cntxt_); } else { delete lm_edges[edge]; } } // edge // free edge array delete []lm_edges; } // lm_edges } // Performs a beam seach in the specified search using the specified // language model; returns an alternate list of possible words as a result. WordAltList * BeamSearch::Search(SearchObject *srch_obj, LangModel *lang_mod) { // verifications if (!lang_mod) lang_mod = cntxt_->LangMod(); if (!lang_mod) { fprintf(stderr, "Cube ERROR (BeamSearch::Search): could not construct " "LangModel\n"); return NULL; } // free existing state Cleanup(); // get seg pt count seg_pt_cnt_ = srch_obj->SegPtCnt(); if (seg_pt_cnt_ < 0) { return NULL; } col_cnt_ = seg_pt_cnt_ + 1; // disregard suspicious cases if (seg_pt_cnt_ > 128) { fprintf(stderr, "Cube ERROR (BeamSearch::Search): segment point count is " "suspiciously high; bailing out\n"); return NULL; } // alloc memory for columns col_ = new SearchColumn *[col_cnt_]; if (!col_) { fprintf(stderr, "Cube ERROR (BeamSearch::Search): could not construct " "SearchColumn array\n"); return NULL; } memset(col_, 0, col_cnt_ * sizeof(*col_)); // for all possible segments for (int end_seg = 1; end_seg <= (seg_pt_cnt_ + 1); end_seg++) { // create a search column col_[end_seg - 1] = new SearchColumn(end_seg - 1, cntxt_->Params()->BeamWidth()); if (!col_[end_seg - 1]) { fprintf(stderr, "Cube ERROR (BeamSearch::Search): could not construct " "SearchColumn for column %d\n", end_seg - 1); return NULL; } // for all possible start segments int init_seg = MAX(0, end_seg - cntxt_->Params()->MaxSegPerChar()); for (int strt_seg = init_seg; strt_seg < end_seg; strt_seg++) { int parent_nodes_cnt; SearchNode **parent_nodes; // for the root segment, we do not have a parent if (strt_seg == 0) { parent_nodes_cnt = 1; parent_nodes = NULL; } else { // for all the existing nodes in the starting column parent_nodes_cnt = col_[strt_seg - 1]->NodeCount(); parent_nodes = col_[strt_seg - 1]->Nodes(); } // run the shape recognizer CharAltList *char_alt_list = srch_obj->RecognizeSegment(strt_seg - 1, end_seg - 1); // for all the possible parents for (int parent_idx = 0; parent_idx < parent_nodes_cnt; parent_idx++) { // point to the parent node SearchNode *parent_node = !parent_nodes ? NULL : parent_nodes[parent_idx]; LangModEdge *lm_parent_edge = !parent_node ? lang_mod->Root() : parent_node->LangModelEdge(); // compute the cost of not having spaces within the segment range int contig_cost = srch_obj->NoSpaceCost(strt_seg - 1, end_seg - 1); // In phrase mode, compute the cost of not having a space before // this character int no_space_cost = 0; if (!word_mode_ && strt_seg > 0) { no_space_cost = srch_obj->NoSpaceCost(strt_seg - 1); } // if the no space cost is low enough if ((contig_cost + no_space_cost) < MIN_PROB_COST) { // Add the children nodes CreateChildren(col_[end_seg - 1], lang_mod, parent_node, lm_parent_edge, char_alt_list, contig_cost + no_space_cost); } // In phrase mode and if not starting at the root if (!word_mode_ && strt_seg > 0) { // parent_node must be non-NULL // consider starting a new word for nodes that are valid EOW if (parent_node->LangModelEdge()->IsEOW()) { // get the space cost int space_cost = srch_obj->SpaceCost(strt_seg - 1); // if the space cost is low enough if ((contig_cost + space_cost) < MIN_PROB_COST) { // Restart the language model and add nodes as children to the // space node. CreateChildren(col_[end_seg - 1], lang_mod, parent_node, NULL, char_alt_list, contig_cost + space_cost); } } } } // parent } // strt_seg // prune the column nodes col_[end_seg - 1]->Prune(); // Free the column hash table. No longer needed col_[end_seg - 1]->FreeHashTable(); } // end_seg WordAltList *alt_list = CreateWordAltList(srch_obj); return alt_list; } // Creates a Word alternate list from the results in the lattice. WordAltList *BeamSearch::CreateWordAltList(SearchObject *srch_obj) { // create an alternate list of all the nodes in the last column int node_cnt = col_[col_cnt_ - 1]->NodeCount(); SearchNode **srch_nodes = col_[col_cnt_ - 1]->Nodes(); CharBigrams *bigrams = cntxt_->Bigrams(); WordUnigrams *word_unigrams = cntxt_->WordUnigramsObj(); // Save the index of the best-cost node before the alt list is // sorted, so that we can retrieve it from the node list when backtracking. best_presorted_node_idx_ = 0; int best_cost = -1; if (node_cnt <= 0) return NULL; // start creating the word alternate list WordAltList *alt_list = new WordAltList(node_cnt + 1); for (int node_idx = 0; node_idx < node_cnt; node_idx++) { // recognition cost int recognition_cost = srch_nodes[node_idx]->BestCost(); // compute the size cost of the alternate char_32 *ch_buff = NULL; int size_cost = SizeCost(srch_obj, srch_nodes[node_idx], &ch_buff); // accumulate other costs if (ch_buff) { int cost = 0; // char bigram cost int bigram_cost = !bigrams ? 0 : bigrams->Cost(ch_buff, cntxt_->CharacterSet()); // word unigram cost int unigram_cost = !word_unigrams ? 0 : word_unigrams->Cost(ch_buff, cntxt_->LangMod(), cntxt_->CharacterSet()); // overall cost cost = static_cast<int>( (size_cost * cntxt_->Params()->SizeWgt()) + (bigram_cost * cntxt_->Params()->CharBigramWgt()) + (unigram_cost * cntxt_->Params()->WordUnigramWgt()) + (recognition_cost * cntxt_->Params()->RecoWgt())); // insert into word alt list alt_list->Insert(ch_buff, cost, static_cast<void *>(srch_nodes[node_idx])); // Note that strict < is necessary because WordAltList::Sort() // uses it in a bubble sort to swap entries. if (best_cost < 0 || cost < best_cost) { best_presorted_node_idx_ = node_idx; best_cost = cost; } delete []ch_buff; } } // sort the alternates based on cost alt_list->Sort(); return alt_list; } // Returns the lattice column corresponding to the specified column index. SearchColumn *BeamSearch::Column(int col) const { if (col < 0 || col >= col_cnt_ || !col_) return NULL; return col_[col]; } // Returns the best node in the last column of last performed search. SearchNode *BeamSearch::BestNode() const { if (col_cnt_ < 1 || !col_ || !col_[col_cnt_ - 1]) return NULL; int node_cnt = col_[col_cnt_ - 1]->NodeCount(); SearchNode **srch_nodes = col_[col_cnt_ - 1]->Nodes(); if (node_cnt < 1 || !srch_nodes || !srch_nodes[0]) return NULL; return srch_nodes[0]; } // Returns the string corresponding to the specified alt. char_32 *BeamSearch::Alt(int alt) const { // get the last column of the lattice if (col_cnt_ <= 0) return NULL; SearchColumn *srch_col = col_[col_cnt_ - 1]; if (!srch_col) return NULL; // point to the last node in the selected path if (alt >= srch_col->NodeCount() || srch_col->Nodes() == NULL) { return NULL; } SearchNode *srch_node = srch_col->Nodes()[alt]; if (!srch_node) return NULL; // get string char_32 *str32 = srch_node->PathString(); if (!str32) return NULL; return str32; } // Backtracks from the specified node index and returns the corresponding // character mapped segments and character count. Optional return // arguments are the char_32 result string and character bounding // boxes, if non-NULL values are passed in. CharSamp **BeamSearch::BackTrack(SearchObject *srch_obj, int node_index, int *char_cnt, char_32 **str32, Boxa **char_boxes) const { // get the last column of the lattice if (col_cnt_ <= 0) return NULL; SearchColumn *srch_col = col_[col_cnt_ - 1]; if (!srch_col) return NULL; // point to the last node in the selected path if (node_index >= srch_col->NodeCount() || !srch_col->Nodes()) return NULL; SearchNode *srch_node = srch_col->Nodes()[node_index]; if (!srch_node) return NULL; return BackTrack(srch_obj, srch_node, char_cnt, str32, char_boxes); } // Backtracks from the specified node index and returns the corresponding // character mapped segments and character count. Optional return // arguments are the char_32 result string and character bounding // boxes, if non-NULL values are passed in. CharSamp **BeamSearch::BackTrack(SearchObject *srch_obj, SearchNode *srch_node, int *char_cnt, char_32 **str32, Boxa **char_boxes) const { if (!srch_node) return NULL; if (str32) { if (*str32) delete [](*str32); // clear existing value *str32 = srch_node->PathString(); if (!*str32) return NULL; } if (char_boxes && *char_boxes) { boxaDestroy(char_boxes); // clear existing value } CharSamp **chars; chars = SplitByNode(srch_obj, srch_node, char_cnt, char_boxes); if (!chars && str32) delete []*str32; return chars; } // Backtracks from the given lattice node and return the corresponding // char mapped segments and character count. The character bounding // boxes are optional return arguments, if non-NULL values are passed in. CharSamp **BeamSearch::SplitByNode(SearchObject *srch_obj, SearchNode *srch_node, int *char_cnt, Boxa **char_boxes) const { // Count the characters (could be less than the path length when in // phrase mode) *char_cnt = 0; SearchNode *node = srch_node; while (node) { node = node->ParentNode(); (*char_cnt)++; } if (*char_cnt == 0) return NULL; // Allocate box array if (char_boxes) { if (*char_boxes) boxaDestroy(char_boxes); // clear existing value *char_boxes = boxaCreate(*char_cnt); if (*char_boxes == NULL) return NULL; } // Allocate memory for CharSamp array. CharSamp **chars = new CharSamp *[*char_cnt]; if (!chars) { if (char_boxes) boxaDestroy(char_boxes); return NULL; } int ch_idx = *char_cnt - 1; int seg_pt_cnt = srch_obj->SegPtCnt(); bool success=true; while (srch_node && ch_idx >= 0) { // Parent node (could be null) SearchNode *parent_node = srch_node->ParentNode(); // Get the seg pts corresponding to the search node int st_col = !parent_node ? 0 : parent_node->ColIdx() + 1; int st_seg_pt = st_col <= 0 ? -1 : st_col - 1; int end_col = srch_node->ColIdx(); int end_seg_pt = end_col >= seg_pt_cnt ? seg_pt_cnt : end_col; // Get a char sample corresponding to the segmentation points CharSamp *samp = srch_obj->CharSample(st_seg_pt, end_seg_pt); if (!samp) { success = false; break; } samp->SetLabel(srch_node->NodeString()); chars[ch_idx] = samp; if (char_boxes) { // Create the corresponding character bounding box Box *char_box = boxCreate(samp->Left(), samp->Top(), samp->Width(), samp->Height()); if (!char_box) { success = false; break; } boxaAddBox(*char_boxes, char_box, L_INSERT); } srch_node = parent_node; ch_idx--; } if (!success) { delete []chars; if (char_boxes) boxaDestroy(char_boxes); return NULL; } // Reverse the order of boxes. if (char_boxes) { int char_boxa_size = boxaGetCount(*char_boxes); int limit = char_boxa_size / 2; for (int i = 0; i < limit; ++i) { int box1_idx = i; int box2_idx = char_boxa_size - 1 - i; Box *box1 = boxaGetBox(*char_boxes, box1_idx, L_CLONE); Box *box2 = boxaGetBox(*char_boxes, box2_idx, L_CLONE); boxaReplaceBox(*char_boxes, box2_idx, box1); boxaReplaceBox(*char_boxes, box1_idx, box2); } } return chars; } // Returns the size cost of a string for a lattice path that // ends at the specified lattice node. int BeamSearch::SizeCost(SearchObject *srch_obj, SearchNode *node, char_32 **str32) const { CharSamp **chars = NULL; int char_cnt = 0; if (!node) return 0; // Backtrack to get string and character segmentation chars = BackTrack(srch_obj, node, &char_cnt, str32, NULL); if (!chars) return WORST_COST; int size_cost = (cntxt_->SizeModel() == NULL) ? 0 : cntxt_->SizeModel()->Cost(chars, char_cnt); delete []chars; return size_cost; } } // namespace tesesract
C++
/********************************************************************** * File: char_samp_enum.cpp * Description: Implementation of a Character Set 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 "char_set.h" #include "cube_utils.h" #include "tessdatamanager.h" namespace tesseract { CharSet::CharSet() { class_cnt_ = 0; class_strings_ = NULL; unicharset_map_ = NULL; init_ = false; // init hash table memset(hash_bin_size_, 0, sizeof(hash_bin_size_)); } CharSet::~CharSet() { if (class_strings_ != NULL) { for (int cls = 0; cls < class_cnt_; cls++) { if (class_strings_[cls] != NULL) { delete class_strings_[cls]; } } delete []class_strings_; class_strings_ = NULL; } delete []unicharset_map_; } // Creates CharSet object by reading the unicharset from the // TessDatamanager, and mapping Cube's unicharset to Tesseract's if // they differ. CharSet *CharSet::Create(TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset) { CharSet *char_set = new CharSet(); if (char_set == NULL) { return NULL; } // First look for Cube's unicharset; if not there, use tesseract's bool cube_unicharset_exists; if (!(cube_unicharset_exists = tessdata_manager->SeekToStart(TESSDATA_CUBE_UNICHARSET)) && !tessdata_manager->SeekToStart(TESSDATA_UNICHARSET)) { fprintf(stderr, "Cube ERROR (CharSet::Create): could not find " "either cube or tesseract unicharset\n"); return NULL; } FILE *charset_fp = tessdata_manager->GetDataFilePtr(); if (!charset_fp) { fprintf(stderr, "Cube ERROR (CharSet::Create): could not load " "a unicharset\n"); return NULL; } // If we found a cube unicharset separate from tesseract's, load it and // map its unichars to tesseract's; if only one unicharset exists, // just load it. bool loaded; if (cube_unicharset_exists) { char_set->cube_unicharset_.load_from_file(charset_fp); loaded = tessdata_manager->SeekToStart(TESSDATA_CUBE_UNICHARSET); loaded = loaded && char_set->LoadSupportedCharList( tessdata_manager->GetDataFilePtr(), tess_unicharset); char_set->unicharset_ = &char_set->cube_unicharset_; } else { loaded = char_set->LoadSupportedCharList(charset_fp, NULL); char_set->unicharset_ = tess_unicharset; } if (!loaded) { delete char_set; return NULL; } char_set->init_ = true; return char_set; } // Load the list of supported chars from the given data file pointer. bool CharSet::LoadSupportedCharList(FILE *fp, UNICHARSET *tess_unicharset) { if (init_) return true; char str_line[256]; // init hash table memset(hash_bin_size_, 0, sizeof(hash_bin_size_)); // read the char count if (fgets(str_line, sizeof(str_line), fp) == NULL) { fprintf(stderr, "Cube ERROR (CharSet::InitMemory): could not " "read char count.\n"); return false; } class_cnt_ = atoi(str_line); if (class_cnt_ < 2) { fprintf(stderr, "Cube ERROR (CharSet::InitMemory): invalid " "class count: %d\n", class_cnt_); return false; } // memory for class strings class_strings_ = new string_32*[class_cnt_]; if (class_strings_ == NULL) { fprintf(stderr, "Cube ERROR (CharSet::InitMemory): could not " "allocate memory for class strings.\n"); return false; } // memory for unicharset map if (tess_unicharset) { unicharset_map_ = new int[class_cnt_]; if (unicharset_map_ == NULL) { fprintf(stderr, "Cube ERROR (CharSet::InitMemory): could not " "allocate memory for unicharset map.\n"); return false; } } // Read in character strings and add to hash table for (int class_id = 0; class_id < class_cnt_; class_id++) { // Read the class string if (fgets(str_line, sizeof(str_line), fp) == NULL) { fprintf(stderr, "Cube ERROR (CharSet::ReadAndHashStrings): " "could not read class string with class_id=%d.\n", class_id); return false; } // Terminate at space if any char *p = strchr(str_line, ' '); if (p != NULL) *p = '\0'; // Convert to UTF32 and store string_32 str32; // Convert NULL to a space if (strcmp(str_line, "NULL") == 0) { strcpy(str_line, " "); } CubeUtils::UTF8ToUTF32(str_line, &str32); class_strings_[class_id] = new string_32(str32); if (class_strings_[class_id] == NULL) { fprintf(stderr, "Cube ERROR (CharSet::ReadAndHashStrings): could not " "allocate memory for class string with class_id=%d.\n", class_id); return false; } // Add to hash-table int hash_val = Hash(reinterpret_cast<const char_32 *>(str32.c_str())); if (hash_bin_size_[hash_val] >= kMaxHashSize) { fprintf(stderr, "Cube ERROR (CharSet::LoadSupportedCharList): hash " "table is full.\n"); return false; } hash_bins_[hash_val][hash_bin_size_[hash_val]++] = class_id; if (tess_unicharset != NULL) { // Add class id to unicharset map UNICHAR_ID tess_id = tess_unicharset->unichar_to_id(str_line); if (tess_id == INVALID_UNICHAR_ID) { tess_unicharset->unichar_insert(str_line); tess_id = tess_unicharset->unichar_to_id(str_line); } ASSERT_HOST(tess_id != INVALID_UNICHAR_ID); unicharset_map_[class_id] = tess_id; } } return true; } } // tesseract
C++
/********************************************************************** * File: alt_list.cpp * Description: Class to abstarct a list of alternate results * 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 "altlist.h" #include <stdlib.h> namespace tesseract { AltList::AltList(int max_alt) { max_alt_ = max_alt; alt_cnt_ = 0; alt_cost_ = NULL; alt_tag_ = NULL; } AltList::~AltList() { if (alt_cost_ != NULL) { delete []alt_cost_; alt_cost_ = NULL; } if (alt_tag_ != NULL) { delete []alt_tag_; alt_tag_ = NULL; } } // return the best possible cost and index of corresponding alternate int AltList::BestCost(int *best_alt) const { if (alt_cnt_ <= 0) { (*best_alt) = -1; return -1; } int best_alt_idx = 0; for (int alt_idx = 1; alt_idx < alt_cnt_; alt_idx++) { if (alt_cost_[alt_idx] < alt_cost_[best_alt_idx]) { best_alt_idx = alt_idx; } } (*best_alt) = best_alt_idx; return alt_cost_[best_alt_idx]; } }
C++
/********************************************************************** * File: cube_page_segmenter.h * Description: Declaration of the Cube Page Segmenter 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. * **********************************************************************/ // TODO(ahmadab) // This is really a makeshift line segmenter that works well for Arabic // This should eventually be replaced by Ray Smith's Page segmenter // There are lots of magic numbers below that were determined empirically // but not thoroughly tested #ifndef CUBE_LINE_SEGMENTER_H #define CUBE_LINE_SEGMENTER_H #include "cube_reco_context.h" #include "allheaders.h" namespace tesseract { class CubeLineSegmenter { public: CubeLineSegmenter(CubeRecoContext *cntxt, Pix *img); ~CubeLineSegmenter(); // Accessor functions Pix *PostProcessedImage() { if (init_ == false && Init() == false) { return NULL; } return img_; } int ColumnCnt() { if (init_ == false && Init() == false) { return 0; } return columns_->n; } Box *Column(int col) { if (init_ == false && Init() == false) { return NULL; } return columns_->boxa->box[col]; } int LineCnt() { if (init_ == false && Init() == false) { return 0; } return line_cnt_; } Pixa *ConComps() { if (init_ == false && Init() == false) { return NULL; } return con_comps_; } Pixaa *Columns() { if (init_ == false && Init() == false) { return NULL; } return columns_; } inline double AlefHgtEst() { return est_alef_hgt_; } inline double DotHgtEst() { return est_dot_hgt_; } Pix *Line(int line, Box **line_box); private: static const float kMinValidLineHgtRatio; static const int kLineSepMorphMinHgt; static const int kHgtBins; static const int kMaxConnCompHgt; static const int kMaxConnCompWid; static const int kMaxHorzAspectRatio; static const int kMaxVertAspectRatio; static const int kMinWid; static const int kMinHgt; static const double kMaxValidLineRatio; // Cube Reco context CubeRecoContext *cntxt_; // Original image Pix *orig_img_; // Post processed image Pix *img_; // Init flag bool init_; // Output Line and column info int line_cnt_; Pixaa *columns_; Pixa *con_comps_; Pixa *lines_pixa_; // Estimates for sizes of ALEF and DOT needed for Arabic analysis double est_alef_hgt_; double est_dot_hgt_; // Init the page analysis bool Init(); // Performs line segmentation bool LineSegment(); // Cleanup function Pix *CleanUp(Pix *pix); // compute validity ratio for a line double ValidityRatio(Pix *line_mask_pix, Box *line_box); // validate line bool ValidLine(Pix *line_mask_pix, Box *line_box); // split a line continuously until valid or fail Pixa *SplitLine(Pix *line_mask_pix, Box *line_box); // do a desperate attempt at cracking lines Pixa *CrackLine(Pix *line_mask_pix, Box *line_box); Pixa *CrackLine(Pix *line_mask_pix, Box *line_box, int line_cnt); // Checks of a line is too small bool SmallLine(Box *line_box); // Compute the connected components in a line Boxa * ComputeLineConComps(Pix *line_mask_pix, Box *line_box, Pixa **con_comps_pixa); // create a union of two arbitrary pix Pix *PixUnion(Pix *dest_pix, Box *dest_box, Pix *src_pix, Box *src_box); // create a union of a pixa subset Pix *Pixa2Pix(Pixa *pixa, Box **dest_box, int start_pix, int pix_cnt); // create a union of a pixa Pix *Pixa2Pix(Pixa *pixa, Box **dest_box); // merges a number of lines into one line given a bounding box and a mask bool MergeLine(Pix *line_mask_pix, Box *line_box, Pixa *lines, Boxaa *lines_con_comps); // Creates new set of lines from the computed columns bool AddLines(Pixa *lines); // Estimate the parameters of the font(s) used in the page bool EstimateFontParams(); // perform a vertical Closing with the specified threshold // returning the resulting conn comps as a pixa Pixa *VerticalClosing(Pix *pix, int thresold, Boxa **boxa); // Index the specific pixa using RTL reading order int *IndexRTL(Pixa *pixa); // Implements a rudimentary page & line segmenter bool FindLines(); }; } #endif // CUBE_LINE_SEGMENTER_H
C++
/********************************************************************** * File: search_column.cpp * Description: Implementation of the Beam Search Column 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. * **********************************************************************/ #include "search_column.h" #include <stdlib.h> namespace tesseract { SearchColumn::SearchColumn(int col_idx, int max_node) { col_idx_ = col_idx; node_cnt_ = 0; node_array_ = NULL; max_node_cnt_ = max_node; node_hash_table_ = NULL; init_ = false; min_cost_ = INT_MAX; max_cost_ = 0; } // Cleanup data void SearchColumn::Cleanup() { if (node_array_ != NULL) { for (int node_idx = 0; node_idx < node_cnt_; node_idx++) { if (node_array_[node_idx] != NULL) { delete node_array_[node_idx]; } } delete []node_array_; node_array_ = NULL; } FreeHashTable(); init_ = false; } SearchColumn::~SearchColumn() { Cleanup(); } // Initializations bool SearchColumn::Init() { if (init_ == true) { return true; } // create hash table if (node_hash_table_ == NULL) { node_hash_table_ = new SearchNodeHashTable(); if (node_hash_table_ == NULL) { return false; } } init_ = true; return true; } // Prune the nodes if necessary. Pruning is done such that a max // number of nodes is kept, i.e., the beam width void SearchColumn::Prune() { // no need to prune if (node_cnt_ <= max_node_cnt_) { return; } // compute the cost histogram memset(score_bins_, 0, sizeof(score_bins_)); int cost_range = max_cost_ - min_cost_ + 1; for (int node_idx = 0; node_idx < node_cnt_; node_idx++) { int cost_bin = static_cast<int>( ((node_array_[node_idx]->BestCost() - min_cost_) * kScoreBins) / static_cast<double>(cost_range)); if (cost_bin >= kScoreBins) { cost_bin = kScoreBins - 1; } score_bins_[cost_bin]++; } // determine the pruning cost by scanning the cost histogram from // least to greatest cost bins and finding the cost at which the // max number of nodes is exceeded int pruning_cost = 0; int new_node_cnt = 0; for (int cost_bin = 0; cost_bin < kScoreBins; cost_bin++) { if (new_node_cnt > 0 && (new_node_cnt + score_bins_[cost_bin]) > max_node_cnt_) { pruning_cost = min_cost_ + ((cost_bin * cost_range) / kScoreBins); break; } new_node_cnt += score_bins_[cost_bin]; } // prune out all the nodes above this cost for (int node_idx = new_node_cnt = 0; node_idx < node_cnt_; node_idx++) { // prune this node out if (node_array_[node_idx]->BestCost() > pruning_cost || new_node_cnt > max_node_cnt_) { delete node_array_[node_idx]; } else { // keep it node_array_[new_node_cnt++] = node_array_[node_idx]; } } node_cnt_ = new_node_cnt; } // sort all nodes void SearchColumn::Sort() { if (node_cnt_ > 0 && node_array_ != NULL) { qsort(node_array_, node_cnt_, sizeof(*node_array_), SearchNode::SearchNodeComparer); } } // add a new node SearchNode *SearchColumn::AddNode(LangModEdge *edge, int reco_cost, SearchNode *parent_node, CubeRecoContext *cntxt) { // init if necessary if (init_ == false && Init() == false) { return NULL; } // find out if we have an node with the same edge // look in the hash table SearchNode *new_node = node_hash_table_->Lookup(edge, parent_node); // node does not exist if (new_node == NULL) { new_node = new SearchNode(cntxt, parent_node, reco_cost, edge, col_idx_); if (new_node == NULL) { return NULL; } // if the max node count has already been reached, check if the cost of // the new node exceeds the max cost. This indicates that it will be pruned // and so there is no point adding it if (node_cnt_ >= max_node_cnt_ && new_node->BestCost() > max_cost_) { delete new_node; return NULL; } // expand the node buffer if necc if ((node_cnt_ % kNodeAllocChunk) == 0) { // alloc a new buff SearchNode **new_node_buff = new SearchNode *[node_cnt_ + kNodeAllocChunk]; if (new_node_buff == NULL) { delete new_node; return NULL; } // free existing after copying contents if (node_array_ != NULL) { memcpy(new_node_buff, node_array_, node_cnt_ * sizeof(*new_node_buff)); delete []node_array_; } node_array_ = new_node_buff; } // add the node to the hash table only if it is non-OOD edge // because the langmod state is not unique if (edge->IsOOD() == false) { if (!node_hash_table_->Insert(edge, new_node)) { tprintf("Hash table full!!!"); delete new_node; return NULL; } } node_array_[node_cnt_++] = new_node; } else { // node exists before // if no update occurred, return NULL if (new_node->UpdateParent(parent_node, reco_cost, edge) == false) { new_node = NULL; } // free the edge if (edge != NULL) { delete edge; } } // update Min and Max Costs if (new_node != NULL) { if (min_cost_ > new_node->BestCost()) { min_cost_ = new_node->BestCost(); } if (max_cost_ < new_node->BestCost()) { max_cost_ = new_node->BestCost(); } } return new_node; } SearchNode *SearchColumn::BestNode() { SearchNode *best_node = NULL; for (int node_idx = 0; node_idx < node_cnt_; node_idx++) { if (best_node == NULL || best_node->BestCost() > node_array_[node_idx]->BestCost()) { best_node = node_array_[node_idx]; } } return best_node; } } // namespace tesseract
C++
/********************************************************************** * File: char_samp_enum.h * Description: Declaration of a Character Sample Enumerator 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 CharSampEnum class provides the base class for CharSamp class // Enumerators. This is typically used to implement dump file readers #ifndef CHARSAMP_ENUM_H #define CHARSAMP_ENUM_H #include "char_samp.h" namespace tesseract { class CharSampEnum { public: CharSampEnum(); virtual ~CharSampEnum(); virtual bool EnumCharSamp(CharSamp *char_samp, float progress) = 0; }; } #endif // CHARSAMP_ENUM_H
C++
/********************************************************************** * File: feature_chebyshev.h * Description: Declaration of the Chebyshev coefficients Feature 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 FeatureChebyshev class implements a Bitmap feature extractor class. It // inherits from the FeatureBase class // The feature vector is the composed of the chebyshev coefficients of 4 time // sequences. The time sequences are the left, top, right & bottom // bitmap profiles of the input samples #ifndef FEATURE_CHEBYSHEV_H #define FEATURE_CHEBYSHEV_H #include "char_samp.h" #include "feature_base.h" namespace tesseract { class FeatureChebyshev : public FeatureBase { public: explicit FeatureChebyshev(TuningParams *params); virtual ~FeatureChebyshev(); // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers virtual CharSamp *ComputeFeatureBitmap(CharSamp *samp); // Compute the features for a given CharSamp virtual bool ComputeFeatures(CharSamp *samp, float *features); // Returns the count of features virtual int FeatureCnt() { return (4 * kChebychevCoefficientCnt); } protected: static const int kChebychevCoefficientCnt = 40; // Compute Chebychev coefficients for the specified vector void ChebyshevCoefficients(const vector<float> &input, int coeff_cnt, float *coeff); // Compute the features for a given CharSamp bool ComputeChebyshevCoefficients(CharSamp *samp, float *features); }; } #endif // FEATURE_CHEBYSHEV_H
C++
/********************************************************************** * File: conv_net_classifier.h * Description: Declaration of Convolutional-NeuralNet Character Classifier * 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. * **********************************************************************/ #ifndef HYBRID_NEURAL_NET_CLASSIFIER_H #define HYBRID_NEURAL_NET_CLASSIFIER_H #include <string> #include <vector> #include "char_samp.h" #include "char_altlist.h" #include "char_set.h" #include "classifier_base.h" #include "feature_base.h" #include "lang_model.h" #include "neural_net.h" #include "tuning_params.h" namespace tesseract { // Folding Ratio is the ratio of the max-activation of members of a folding // set that is used to compute the min-activation of the rest of the set // static const float kFoldingRatio = 0.75; // see conv_net_classifier.h class HybridNeuralNetCharClassifier : public CharClassifier { public: HybridNeuralNetCharClassifier(CharSet *char_set, TuningParams *params, FeatureBase *feat_extract); virtual ~HybridNeuralNetCharClassifier(); // The main training function. Given a sample and a class ID the classifier // updates its parameters according to its learning algorithm. This function // is currently not implemented. TODO(ahmadab): implement end-2-end training virtual bool Train(CharSamp *char_samp, int ClassID); // A secondary function needed for training. Allows the trainer to set the // value of any train-time paramter. This function is currently not // implemented. TODO(ahmadab): implement end-2-end training virtual bool SetLearnParam(char *var_name, float val); // Externally sets the Neural Net used by the classifier. Used for training void SetNet(tesseract::NeuralNet *net); // Classifies an input charsamp and return a CharAltList object containing // the possible candidates and corresponding scores virtual CharAltList *Classify(CharSamp *char_samp); // Computes the cost of a specific charsamp being a character (versus a // non-character: part-of-a-character OR more-than-one-character) virtual int CharCost(CharSamp *char_samp); private: // Neural Net object used for classification vector<tesseract::NeuralNet *> nets_; vector<float> net_wgts_; // data buffers used to hold Neural Net inputs and outputs float *net_input_; float *net_output_; // Init the classifier provided a data-path and a language string virtual bool Init(const string &data_file_path, const string &lang, LangModel *lang_mod); // Loads the NeuralNets needed for the classifier bool LoadNets(const string &data_file_path, const string &lang); // Load folding sets // This function returns true on success or if the file can't be read, // returns false if an error is encountered. virtual bool LoadFoldingSets(const string &data_file_path, const string &lang, LangModel *lang_mod); // Folds the output of the NeuralNet using the loaded folding sets virtual void Fold(); // Scales the input char_samp and feeds it to the NeuralNet as input bool RunNets(CharSamp *char_samp); }; } #endif // HYBRID_NEURAL_NET_CLASSIFIER_H
C++
/********************************************************************** * File: word_unigrams.h * Description: Declaration of the Word Unigrams 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 WordUnigram class holds the unigrams of the most frequent set of words // in a language. It is an optional component of the Cube OCR engine. If // present, the unigram cost of a word is aggregated with the other costs // (Recognition, Language Model, Size) to compute a cost for a word. // The word list is assumed to be sorted in lexicographic order. #ifndef WORD_UNIGRAMS_H #define WORD_UNIGRAMS_H #include <string> #include "char_set.h" #include "lang_model.h" namespace tesseract { class WordUnigrams { public: WordUnigrams(); ~WordUnigrams(); // Load the word-list and unigrams from file and create an object // The word list is assumed to be sorted static WordUnigrams *Create(const string &data_file_path, const string &lang); // Compute the unigram cost of a UTF-32 string. Splits into // space-separated tokens, strips trailing punctuation from each // token, evaluates case properties, and calls internal Cost() // function on UTF-8 version. To avoid unnecessarily penalizing // all-one-case words or capitalized words (first-letter // upper-case and remaining letters lower-case) when not all // versions of the word appear in the <lang>.cube.word-freq file, a // case-invariant cost is computed in those cases, assuming the word // meets a minimum length. int Cost(const char_32 *str32, LangModel *lang_mod, CharSet *char_set) const; protected: // Compute the word unigram cost of a UTF-8 string with binary // search of sorted words_ array. int CostInternal(const char *str) const; private: // Only words this length or greater qualify for all-numeric or // case-invariant word unigram cost. static const int kMinLengthNumOrCaseInvariant = 4; int word_cnt_; char **words_; int *costs_; int not_in_list_cost_; }; } #endif // WORD_UNIGRAMS_H
C++
/********************************************************************** * 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
C++
/********************************************************************** * File: tuning_params.h * Description: Declaration of the Tuning Parameters Base 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 TuningParams class abstracts all the parameters that can be learned or // tuned during the training process. It is a base class that all TuningParams // classes should inherit from. #ifndef TUNING_PARAMS_H #define TUNING_PARAMS_H #include <string> #ifdef USE_STD_NAMESPACE using std::string; #endif namespace tesseract { class TuningParams { public: enum type_classifer { NN, HYBRID_NN }; enum type_feature { BMP, CHEBYSHEV, HYBRID }; TuningParams() {} virtual ~TuningParams() {} // Accessor functions inline double RecoWgt() const { return reco_wgt_; } inline double SizeWgt() const { return size_wgt_; } inline double CharBigramWgt() const { return char_bigrams_wgt_; } inline double WordUnigramWgt() const { return word_unigrams_wgt_; } inline int MaxSegPerChar() const { return max_seg_per_char_; } inline int BeamWidth() const { return beam_width_; } inline int TypeClassifier() const { return tp_classifier_; } inline int TypeFeature() const { return tp_feat_; } inline int ConvGridSize() const { return conv_grid_size_; } inline int HistWindWid() const { return hist_wind_wid_; } inline int MinConCompSize() const { return min_con_comp_size_; } inline double MaxWordAspectRatio() const { return max_word_aspect_ratio_; } inline double MinSpaceHeightRatio() const { return min_space_height_ratio_; } inline double MaxSpaceHeightRatio() const { return max_space_height_ratio_; } inline double CombinerRunThresh() const { return combiner_run_thresh_; } inline double CombinerClassifierThresh() const { return combiner_classifier_thresh_; } inline void SetRecoWgt(double wgt) { reco_wgt_ = wgt; } inline void SetSizeWgt(double wgt) { size_wgt_ = wgt; } inline void SetCharBigramWgt(double wgt) { char_bigrams_wgt_ = wgt; } inline void SetWordUnigramWgt(double wgt) { word_unigrams_wgt_ = wgt; } inline void SetMaxSegPerChar(int max_seg_per_char) { max_seg_per_char_ = max_seg_per_char; } inline void SetBeamWidth(int beam_width) { beam_width_ = beam_width; } inline void SetTypeClassifier(type_classifer tp_classifier) { tp_classifier_ = tp_classifier; } inline void SetTypeFeature(type_feature tp_feat) {tp_feat_ = tp_feat;} inline void SetHistWindWid(int hist_wind_wid) { hist_wind_wid_ = hist_wind_wid; } virtual bool Save(string file_name) = 0; virtual bool Load(string file_name) = 0; protected: // weight of recognition cost. This includes the language model cost double reco_wgt_; // weight of size cost double size_wgt_; // weight of character bigrams cost double char_bigrams_wgt_; // weight of word unigrams cost double word_unigrams_wgt_; // Maximum number of segments per character int max_seg_per_char_; // Beam width equal to the maximum number of nodes kept in the beam search // trellis column after pruning int beam_width_; // Classifier type: See enum type_classifer for classifier types type_classifer tp_classifier_; // Feature types: See enum type_feature for feature types type_feature tp_feat_; // Grid size to scale a grapheme bitmap used by the BMP feature type int conv_grid_size_; // Histogram window size as a ratio of the word height used in computing // the vertical pixel density histogram in the segmentation algorithm int hist_wind_wid_; // Minimum possible size of a connected component int min_con_comp_size_; // Maximum aspect ratio of a word (width / height) double max_word_aspect_ratio_; // Minimum ratio relative to the line height of a gap to be considered as // a word break double min_space_height_ratio_; // Maximum ratio relative to the line height of a gap to be considered as // a definite word break double max_space_height_ratio_; // When Cube and Tesseract are run in combined mode, only run // combiner classifier when tesseract confidence is below this // threshold. When Cube is run without Tesseract, this is ignored. double combiner_run_thresh_; // When Cube and tesseract are run in combined mode, threshold on // output of combiner binary classifier (chosen from ROC during // combiner training). When Cube is run without Tesseract, this is ignored. double combiner_classifier_thresh_; }; } #endif // TUNING_PARAMS_H
C++
/********************************************************************** * File: char_bigrams.h * Description: Declaration of a Character Bigrams 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 CharBigram class represents the interface to the character bigram // table used by Cube // A CharBigram object can be constructed from the Char Bigrams file // Given a sequence of characters, the "Cost" method returns the Char Bigram // cost of the string according to the table #ifndef CHAR_BIGRAMS_H #define CHAR_BIGRAMS_H #include <string> #include "char_set.h" namespace tesseract { // structure representing a single bigram value struct Bigram { int cnt; int cost; }; // structure representing the char bigram array of characters // following a specific character struct CharBigram { int total_cnt; char_32 max_char; Bigram *bigram; }; // structure representing the whole bigram table struct CharBigramTable { int total_cnt; int worst_cost; char_32 max_char; CharBigram *char_bigram; }; class CharBigrams { public: CharBigrams(); ~CharBigrams(); // Construct the CharBigrams class from a file static CharBigrams *Create(const string &data_file_path, const string &lang); // Top-level function to return the mean character bigram cost of a // sequence of characters. If char_set is not NULL, use // tesseract functions to return a case-invariant cost. // This avoids unnecessarily penalizing all-one-case words or // capitalized words (first-letter upper-case and remaining letters // lower-case). int Cost(const char_32 *str, CharSet *char_set) const; protected: // Returns the character bigram cost of two characters. int PairCost(char_32 ch1, char_32 ch2) const; // Returns the mean character bigram cost of a sequence of // characters. Adds a space at the beginning and end to account for // cost of starting and ending characters. int MeanCostWithSpaces(const char_32 *char_32_ptr) const; private: // Only words this length or greater qualify for case-invariant character // bigram cost. static const int kMinLengthCaseInvariant = 4; CharBigramTable bigram_table_; }; } #endif // CHAR_BIGRAMS_H
C++
/********************************************************************** * File: char_samp.cpp * Description: Implementation of a Character Bitmap Sample 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.h> #include <string> #include "char_samp.h" #include "cube_utils.h" namespace tesseract { #define MAX_LINE_LEN 1024 CharSamp::CharSamp() : Bmp8(0, 0) { left_ = 0; top_ = 0; label32_ = NULL; page_ = -1; } CharSamp::CharSamp(int wid, int hgt) : Bmp8(wid, hgt) { left_ = 0; top_ = 0; label32_ = NULL; page_ = -1; } CharSamp::CharSamp(int left, int top, int wid, int hgt) : Bmp8(wid, hgt) , left_(left) , top_(top) { label32_ = NULL; page_ = -1; } CharSamp::~CharSamp() { if (label32_ != NULL) { delete []label32_; label32_ = NULL; } } // returns a UTF-8 version of the string label string CharSamp::stringLabel() const { string str = ""; if (label32_ != NULL) { string_32 str32(label32_); CubeUtils::UTF32ToUTF8(str32.c_str(), &str); } return str; } // set a the string label using a UTF encoded string void CharSamp::SetLabel(string str) { if (label32_ != NULL) { delete []label32_; label32_ = NULL; } string_32 str32; CubeUtils::UTF8ToUTF32(str.c_str(), &str32); SetLabel(reinterpret_cast<const char_32 *>(str32.c_str())); } // creates a CharSamp object from file CharSamp *CharSamp::FromCharDumpFile(CachedFile *fp) { unsigned short left; unsigned short top; unsigned short page; unsigned short first_char; unsigned short last_char; unsigned short norm_top; unsigned short norm_bottom; unsigned short norm_aspect_ratio; unsigned int val32; char_32 *label32; // read and check 32 bit marker if (fp->Read(&val32, sizeof(val32)) != sizeof(val32)) { return NULL; } if (val32 != 0xabd0fefe) { return NULL; } // read label length, if (fp->Read(&val32, sizeof(val32)) != sizeof(val32)) { return NULL; } // the label is not null terminated in the file if (val32 > 0 && val32 < MAX_UINT32) { label32 = new char_32[val32 + 1]; if (label32 == NULL) { return NULL; } // read label if (fp->Read(label32, val32 * sizeof(*label32)) != (val32 * sizeof(*label32))) { return NULL; } // null terminate label32[val32] = 0; } else { label32 = NULL; } // read coordinates if (fp->Read(&page, sizeof(page)) != sizeof(page)) { return NULL; } if (fp->Read(&left, sizeof(left)) != sizeof(left)) { return NULL; } if (fp->Read(&top, sizeof(top)) != sizeof(top)) { return NULL; } if (fp->Read(&first_char, sizeof(first_char)) != sizeof(first_char)) { return NULL; } if (fp->Read(&last_char, sizeof(last_char)) != sizeof(last_char)) { return NULL; } if (fp->Read(&norm_top, sizeof(norm_top)) != sizeof(norm_top)) { return NULL; } if (fp->Read(&norm_bottom, sizeof(norm_bottom)) != sizeof(norm_bottom)) { return NULL; } if (fp->Read(&norm_aspect_ratio, sizeof(norm_aspect_ratio)) != sizeof(norm_aspect_ratio)) { return NULL; } // create the object CharSamp *char_samp = new CharSamp(); if (char_samp == NULL) { return NULL; } // init char_samp->label32_ = label32; char_samp->page_ = page; char_samp->left_ = left; char_samp->top_ = top; char_samp->first_char_ = first_char; char_samp->last_char_ = last_char; char_samp->norm_top_ = norm_top; char_samp->norm_bottom_ = norm_bottom; char_samp->norm_aspect_ratio_ = norm_aspect_ratio; // load the Bmp8 part if (char_samp->LoadFromCharDumpFile(fp) == false) { delete char_samp; return NULL; } return char_samp; } // Load a Char Samp from a dump file CharSamp *CharSamp::FromCharDumpFile(FILE *fp) { unsigned short left; unsigned short top; unsigned short page; unsigned short first_char; unsigned short last_char; unsigned short norm_top; unsigned short norm_bottom; unsigned short norm_aspect_ratio; unsigned int val32; char_32 *label32; // read and check 32 bit marker if (fread(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return NULL; } if (val32 != 0xabd0fefe) { return NULL; } // read label length, if (fread(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return NULL; } // the label is not null terminated in the file if (val32 > 0 && val32 < MAX_UINT32) { label32 = new char_32[val32 + 1]; if (label32 == NULL) { return NULL; } // read label if (fread(label32, 1, val32 * sizeof(*label32), fp) != (val32 * sizeof(*label32))) { delete [] label32; return NULL; } // null terminate label32[val32] = 0; } else { label32 = NULL; } // read coordinates if (fread(&page, 1, sizeof(page), fp) != sizeof(page) || fread(&left, 1, sizeof(left), fp) != sizeof(left) || fread(&top, 1, sizeof(top), fp) != sizeof(top) || fread(&first_char, 1, sizeof(first_char), fp) != sizeof(first_char) || fread(&last_char, 1, sizeof(last_char), fp) != sizeof(last_char) || fread(&norm_top, 1, sizeof(norm_top), fp) != sizeof(norm_top) || fread(&norm_bottom, 1, sizeof(norm_bottom), fp) != sizeof(norm_bottom) || fread(&norm_aspect_ratio, 1, sizeof(norm_aspect_ratio), fp) != sizeof(norm_aspect_ratio)) { delete [] label32; return NULL; } // create the object CharSamp *char_samp = new CharSamp(); if (char_samp == NULL) { delete [] label32; return NULL; } // init char_samp->label32_ = label32; char_samp->page_ = page; char_samp->left_ = left; char_samp->top_ = top; char_samp->first_char_ = first_char; char_samp->last_char_ = last_char; char_samp->norm_top_ = norm_top; char_samp->norm_bottom_ = norm_bottom; char_samp->norm_aspect_ratio_ = norm_aspect_ratio; // load the Bmp8 part if (char_samp->LoadFromCharDumpFile(fp) == false) { delete char_samp; // It owns label32. return NULL; } return char_samp; } // returns a copy of the charsamp that is scaled to the // specified width and height CharSamp *CharSamp::Scale(int wid, int hgt, bool isotropic) { CharSamp *scaled_samp = new CharSamp(wid, hgt); if (scaled_samp == NULL) { return NULL; } if (scaled_samp->ScaleFrom(this, isotropic) == false) { delete scaled_samp; return NULL; } scaled_samp->left_ = left_; scaled_samp->top_ = top_; scaled_samp->page_ = page_; scaled_samp->SetLabel(label32_); scaled_samp->first_char_ = first_char_; scaled_samp->last_char_ = last_char_; scaled_samp->norm_top_ = norm_top_; scaled_samp->norm_bottom_ = norm_bottom_; scaled_samp->norm_aspect_ratio_ = norm_aspect_ratio_; return scaled_samp; } // Load a Char Samp from a dump file CharSamp *CharSamp::FromRawData(int left, int top, int wid, int hgt, unsigned char *data) { // create the object CharSamp *char_samp = new CharSamp(left, top, wid, hgt); if (char_samp == NULL) { return NULL; } if (char_samp->LoadFromRawData(data) == false) { delete char_samp; return NULL; } return char_samp; } // Saves the charsamp to a dump file bool CharSamp::Save2CharDumpFile(FILE *fp) const { unsigned int val32; // write and check 32 bit marker val32 = 0xabd0fefe; if (fwrite(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } // write label length val32 = (label32_ == NULL) ? 0 : LabelLen(label32_); if (fwrite(&val32, 1, sizeof(val32), fp) != sizeof(val32)) { return false; } // write label if (label32_ != NULL) { if (fwrite(label32_, 1, val32 * sizeof(*label32_), fp) != (val32 * sizeof(*label32_))) { return false; } } // write coordinates if (fwrite(&page_, 1, sizeof(page_), fp) != sizeof(page_)) { return false; } if (fwrite(&left_, 1, sizeof(left_), fp) != sizeof(left_)) { return false; } if (fwrite(&top_, 1, sizeof(top_), fp) != sizeof(top_)) { return false; } if (fwrite(&first_char_, 1, sizeof(first_char_), fp) != sizeof(first_char_)) { return false; } if (fwrite(&last_char_, 1, sizeof(last_char_), fp) != sizeof(last_char_)) { return false; } if (fwrite(&norm_top_, 1, sizeof(norm_top_), fp) != sizeof(norm_top_)) { return false; } if (fwrite(&norm_bottom_, 1, sizeof(norm_bottom_), fp) != sizeof(norm_bottom_)) { return false; } if (fwrite(&norm_aspect_ratio_, 1, sizeof(norm_aspect_ratio_), fp) != sizeof(norm_aspect_ratio_)) { return false; } if (SaveBmp2CharDumpFile(fp) == false) { return false; } return true; } // Crop the char samp such that there are no white spaces on any side. // The norm_top_ and norm_bottom_ fields are the character top/bottom // with respect to whatever context the character is being recognized // in (e.g. word bounding box) normalized to a standard size of // 255. Here they default to 0 and 255 (word box boundaries), but // since they are context dependent, they may need to be reset by the // calling function. CharSamp *CharSamp::Crop() { // get the dimesions of the cropped img int cropped_left = 0; int cropped_top = 0; int cropped_wid = wid_; int cropped_hgt = hgt_; Bmp8::Crop(&cropped_left, &cropped_top, &cropped_wid, &cropped_hgt); if (cropped_wid == 0 || cropped_hgt == 0) { return NULL; } // create the cropped char samp CharSamp *cropped_samp = new CharSamp(left_ + cropped_left, top_ + cropped_top, cropped_wid, cropped_hgt); cropped_samp->SetLabel(label32_); cropped_samp->SetFirstChar(first_char_); cropped_samp->SetLastChar(last_char_); // the following 3 fields may/should be reset by the calling function // using context information, i.e., location of character box // w.r.t. the word bounding box cropped_samp->SetNormAspectRatio(255 * cropped_wid / (cropped_wid + cropped_hgt)); cropped_samp->SetNormTop(0); cropped_samp->SetNormBottom(255); // copy the bitmap to the cropped img Copy(cropped_left, cropped_top, cropped_wid, cropped_hgt, cropped_samp); return cropped_samp; } // segment the char samp to connected components // based on contiguity and vertical pixel density histogram ConComp **CharSamp::Segment(int *segment_cnt, bool right_2_left, int max_hist_wnd, int min_con_comp_size) const { // init (*segment_cnt) = 0; int concomp_cnt = 0; int seg_cnt = 0; // find the concomps of the image ConComp **concomp_array = FindConComps(&concomp_cnt, min_con_comp_size); if (concomp_cnt <= 0 || !concomp_array) { if (concomp_array) delete []concomp_array; return NULL; } ConComp **seg_array = NULL; // segment each concomp further using vertical histogram for (int concomp = 0; concomp < concomp_cnt; concomp++) { int concomp_seg_cnt = 0; // segment the concomp ConComp **concomp_seg_array = NULL; ConComp **concomp_alloc_seg = concomp_array[concomp]->Segment(max_hist_wnd, &concomp_seg_cnt); // no segments, add the whole concomp if (concomp_alloc_seg == NULL) { concomp_seg_cnt = 1; concomp_seg_array = concomp_array + concomp; } else { // delete the original concomp, we no longer need it concomp_seg_array = concomp_alloc_seg; delete concomp_array[concomp]; } // add the resulting segments for (int seg_idx = 0; seg_idx < concomp_seg_cnt; seg_idx++) { // too small of a segment: ignore if (concomp_seg_array[seg_idx]->Width() < 2 && concomp_seg_array[seg_idx]->Height() < 2) { delete concomp_seg_array[seg_idx]; } else { // add the new segment // extend the segment array if ((seg_cnt % kConCompAllocChunk) == 0) { ConComp **temp_segm_array = new ConComp *[seg_cnt + kConCompAllocChunk]; if (temp_segm_array == NULL) { fprintf(stderr, "Cube ERROR (CharSamp::Segment): could not " "allocate additional connected components\n"); delete []concomp_seg_array; delete []concomp_array; delete []seg_array; return NULL; } if (seg_cnt > 0) { memcpy(temp_segm_array, seg_array, seg_cnt * sizeof(*seg_array)); delete []seg_array; } seg_array = temp_segm_array; } seg_array[seg_cnt++] = concomp_seg_array[seg_idx]; } } // segment if (concomp_alloc_seg != NULL) { delete []concomp_alloc_seg; } } // concomp delete []concomp_array; // sort the concomps from Left2Right or Right2Left, based on the reading order if (seg_cnt > 0 && seg_array != NULL) { qsort(seg_array, seg_cnt, sizeof(*seg_array), right_2_left ? ConComp::Right2LeftComparer : ConComp::Left2RightComparer); } (*segment_cnt) = seg_cnt; return seg_array; } // builds a char samp from a set of connected components CharSamp *CharSamp::FromConComps(ConComp **concomp_array, int strt_concomp, int seg_flags_size, int *seg_flags, bool *left_most, bool *right_most, int word_hgt) { int concomp; int end_concomp; int concomp_cnt = 0; end_concomp = strt_concomp + seg_flags_size; // determine ID range bool once = false; int min_id = -1; int max_id = -1; for (concomp = strt_concomp; concomp < end_concomp; concomp++) { if (!seg_flags || seg_flags[concomp - strt_concomp] != 0) { if (!once) { min_id = concomp_array[concomp]->ID(); max_id = concomp_array[concomp]->ID(); once = true; } else { UpdateRange(concomp_array[concomp]->ID(), &min_id, &max_id); } concomp_cnt++; } } if (concomp_cnt < 1 || !once || min_id == -1 || max_id == -1) { return NULL; } // alloc memo for computing leftmost and right most attributes int id_cnt = max_id - min_id + 1; bool *id_exist = new bool[id_cnt]; bool *left_most_exist = new bool[id_cnt]; bool *right_most_exist = new bool[id_cnt]; if (!id_exist || !left_most_exist || !right_most_exist) return NULL; memset(id_exist, 0, id_cnt * sizeof(*id_exist)); memset(left_most_exist, 0, id_cnt * sizeof(*left_most_exist)); memset(right_most_exist, 0, id_cnt * sizeof(*right_most_exist)); // find the dimensions of the charsamp once = false; int left = -1; int right = -1; int top = -1; int bottom = -1; int unq_ids = 0; int unq_left_most = 0; int unq_right_most = 0; for (concomp = strt_concomp; concomp < end_concomp; concomp++) { if (!seg_flags || seg_flags[concomp - strt_concomp] != 0) { if (!once) { left = concomp_array[concomp]->Left(); right = concomp_array[concomp]->Right(); top = concomp_array[concomp]->Top(); bottom = concomp_array[concomp]->Bottom(); once = true; } else { UpdateRange(concomp_array[concomp]->Left(), concomp_array[concomp]->Right(), &left, &right); UpdateRange(concomp_array[concomp]->Top(), concomp_array[concomp]->Bottom(), &top, &bottom); } // count unq ids, unq left most and right mosts ids int concomp_id = concomp_array[concomp]->ID() - min_id; if (!id_exist[concomp_id]) { id_exist[concomp_id] = true; unq_ids++; } if (concomp_array[concomp]->LeftMost()) { if (left_most_exist[concomp_id] == false) { left_most_exist[concomp_id] = true; unq_left_most++; } } if (concomp_array[concomp]->RightMost()) { if (right_most_exist[concomp_id] == false) { right_most_exist[concomp_id] = true; unq_right_most++; } } } } delete []id_exist; delete []left_most_exist; delete []right_most_exist; if (!once || left == -1 || top == -1 || right == -1 || bottom == -1) { return NULL; } (*left_most) = (unq_left_most >= unq_ids); (*right_most) = (unq_right_most >= unq_ids); // create the char sample object CharSamp *samp = new CharSamp(left, top, right - left + 1, bottom - top + 1); if (!samp) { return NULL; } // set the foreground pixels for (concomp = strt_concomp; concomp < end_concomp; concomp++) { if (!seg_flags || seg_flags[concomp - strt_concomp] != 0) { ConCompPt *pt_ptr = concomp_array[concomp]->Head(); while (pt_ptr) { samp->line_buff_[pt_ptr->y() - top][pt_ptr->x() - left] = 0; pt_ptr = pt_ptr->Next(); } } } return samp; } // clones the object CharSamp *CharSamp::Clone() const { // create the cropped char samp CharSamp *samp = new CharSamp(left_, top_, wid_, hgt_); samp->SetLabel(label32_); samp->SetFirstChar(first_char_); samp->SetLastChar(last_char_); samp->SetNormTop(norm_top_); samp->SetNormBottom(norm_bottom_); samp->SetNormAspectRatio(norm_aspect_ratio_); // copy the bitmap to the cropped img Copy(0, 0, wid_, hgt_, samp); return samp; } // Load a Char Samp from a dump file CharSamp *CharSamp::FromCharDumpFile(unsigned char **raw_data_ptr) { unsigned int val32; char_32 *label32; unsigned char *raw_data = *raw_data_ptr; // read and check 32 bit marker memcpy(&val32, raw_data, sizeof(val32)); raw_data += sizeof(val32); if (val32 != 0xabd0fefe) { return NULL; } // read label length, memcpy(&val32, raw_data, sizeof(val32)); raw_data += sizeof(val32); // the label is not null terminated in the file if (val32 > 0 && val32 < MAX_UINT32) { label32 = new char_32[val32 + 1]; if (label32 == NULL) { return NULL; } // read label memcpy(label32, raw_data, val32 * sizeof(*label32)); raw_data += (val32 * sizeof(*label32)); // null terminate label32[val32] = 0; } else { label32 = NULL; } // create the object CharSamp *char_samp = new CharSamp(); if (char_samp == NULL) { return NULL; } // read coordinates char_samp->label32_ = label32; memcpy(&char_samp->page_, raw_data, sizeof(char_samp->page_)); raw_data += sizeof(char_samp->page_); memcpy(&char_samp->left_, raw_data, sizeof(char_samp->left_)); raw_data += sizeof(char_samp->left_); memcpy(&char_samp->top_, raw_data, sizeof(char_samp->top_)); raw_data += sizeof(char_samp->top_); memcpy(&char_samp->first_char_, raw_data, sizeof(char_samp->first_char_)); raw_data += sizeof(char_samp->first_char_); memcpy(&char_samp->last_char_, raw_data, sizeof(char_samp->last_char_)); raw_data += sizeof(char_samp->last_char_); memcpy(&char_samp->norm_top_, raw_data, sizeof(char_samp->norm_top_)); raw_data += sizeof(char_samp->norm_top_); memcpy(&char_samp->norm_bottom_, raw_data, sizeof(char_samp->norm_bottom_)); raw_data += sizeof(char_samp->norm_bottom_); memcpy(&char_samp->norm_aspect_ratio_, raw_data, sizeof(char_samp->norm_aspect_ratio_)); raw_data += sizeof(char_samp->norm_aspect_ratio_); // load the Bmp8 part if (char_samp->LoadFromCharDumpFile(&raw_data) == false) { delete char_samp; return NULL; } (*raw_data_ptr) = raw_data; return char_samp; } // computes the features corresponding to the char sample bool CharSamp::ComputeFeatures(int conv_grid_size, float *features) { // Create a scaled BMP CharSamp *scaled_bmp = Scale(conv_grid_size, conv_grid_size); if (!scaled_bmp) { return false; } // prepare input unsigned char *buff = scaled_bmp->RawData(); // bitmap features int input; int bmp_size = conv_grid_size * conv_grid_size; for (input = 0; input < bmp_size; input++) { features[input] = 255.0f - (1.0f * buff[input]); } // word context features features[input++] = FirstChar(); features[input++] = LastChar(); features[input++] = NormTop(); features[input++] = NormBottom(); features[input++] = NormAspectRatio(); delete scaled_bmp; return true; } } // namespace tesseract
C++
/********************************************************************** * File: cube_tuning_params.h * Description: Declaration of the CubeTuningParameters 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 CubeTuningParams class abstracts all the parameters that are used // in Cube and are tuned/learned during the training process. Inherits // from the TuningParams class. #ifndef CUBE_TUNING_PARAMS_H #define CUBE_TUNING_PARAMS_H #include <string> #include "tuning_params.h" namespace tesseract { class CubeTuningParams : public TuningParams { public: CubeTuningParams(); ~CubeTuningParams(); // Accessor functions inline double OODWgt() { return ood_wgt_; } inline double NumWgt() { return num_wgt_; } inline void SetOODWgt(double wgt) { ood_wgt_ = wgt; } inline void SetNumWgt(double wgt) { num_wgt_ = wgt; } // Create an object given the data file path and the language by loading // the approporiate file static CubeTuningParams * Create(const string &data_file, const string &lang); // Save and load the tuning parameters to a specified file bool Save(string file_name); bool Load(string file_name); private: double ood_wgt_; double num_wgt_; }; } #endif // CUBE_TUNING_PARAMS_H
C++
/********************************************************************** * File: char_altlist.h * Description: Declaration of a Character Alternate List 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. * **********************************************************************/ #ifndef CHAR_ALT_LIST_H #define CHAR_ALT_LIST_H // The CharAltList class holds the list of class alternates returned from // a character classifier. Each alternate represents a class ID. // It inherits from the AltList class. // The CharAltList owns a CharSet object that maps a class-id to a string. #include "altlist.h" #include "char_set.h" namespace tesseract { class CharAltList : public AltList { public: CharAltList(const CharSet *char_set, int max_alt = kMaxCharAlt); ~CharAltList(); // Sort the alternate list based on cost void Sort(); // insert a new alternate with the specified class-id, cost and tag bool Insert(int class_id, int cost, void *tag = NULL); // returns the cost of a specific class ID inline int ClassCost(int class_id) const { if (class_id_cost_ == NULL || class_id < 0 || class_id >= char_set_->ClassCount()) { return WORST_COST; } return class_id_cost_[class_id]; } // returns the alternate class-id corresponding to an alternate index inline int Alt(int alt_idx) const { return class_id_alt_[alt_idx]; } // set the cost of a certain alternate void SetAltCost(int alt_idx, int cost) { alt_cost_[alt_idx] = cost; class_id_cost_[class_id_alt_[alt_idx]] = cost; } private: // character set object. Passed at construction time const CharSet *char_set_; // array of alternate class-ids int *class_id_alt_; // array of alternate costs int *class_id_cost_; // default max count of alternates static const int kMaxCharAlt = 256; }; } #endif // CHAR_ALT_LIST_H
C++
/********************************************************************** * File: feature_bmp.h * Description: Declaration of the Bitmap Feature Class * Author: PingPing xiu (xiupingping) & 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 FeatureBmp class implements a Bitmap feature extractor class. It // inherits from the FeatureBase class // The Bitmap feature vectors is the the bitmap of the specified CharSamp // scaled to a fixed grid size and then augmented by a 5 aux features that // describe the size, aspect ration and placement within a word #ifndef FEATURE_BMP_H #define FEATURE_BMP_H #include "char_samp.h" #include "feature_base.h" namespace tesseract { class FeatureBmp : public FeatureBase { public: explicit FeatureBmp(TuningParams *params); virtual ~FeatureBmp(); // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers virtual CharSamp *ComputeFeatureBitmap(CharSamp *samp); // Compute the features for a given CharSamp virtual bool ComputeFeatures(CharSamp *samp, float *features); // Returns the count of features virtual int FeatureCnt() { return 5 + (conv_grid_size_ * conv_grid_size_); } protected: // grid size, cached from the TuningParams object int conv_grid_size_; }; } #endif // FEATURE_BMP_H
C++
/********************************************************************** * File: beam_search.h * Description: Declaration of Beam Word Search Algorithm 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 Beam Search class implements a Beam Search algorithm for the // N-best paths through the lattice of a search object using a language model // The search object is a segmented bitmap of a word image. The language model // is a state machine that defines valid sequences of characters // The cost of each path is the combined (product) probabilities of the // characters along the path. The character probabilities are computed using // the character classifier member of the RecoContext // The BeamSearch class itself holds the state of the last search it performed // using its "Search" method. Subsequent class to the Search method erase the // states of previously done searches #ifndef BEAM_SEARCH_H #define BEAM_SEARCH_H #include "search_column.h" #include "word_altlist.h" #include "search_object.h" #include "lang_model.h" #include "cube_utils.h" #include "cube_reco_context.h" #include "allheaders.h" namespace tesseract { class BeamSearch { public: explicit BeamSearch(CubeRecoContext *cntxt, bool word_mode = true); ~BeamSearch(); // Performs a beam seach in the specified search using the specified // language model; returns an alternate list of possible words as a result. WordAltList *Search(SearchObject *srch_obj, LangModel *lang_mod = NULL); // Returns the best node in the last column of last performed search. SearchNode *BestNode() const; // Returns the string corresponding to the specified alt. char_32 *Alt(int alt) const; // Backtracks from the specified lattice node and returns the corresponding // character-mapped segments, character count, char_32 result string, and // character bounding boxes (if char_boxes is not NULL). If the segments // cannot be constructed, returns NULL, and all result arguments // will be NULL. CharSamp **BackTrack(SearchObject *srch_obj, int node_index, int *char_cnt, char_32 **str32, Boxa **char_boxes) const; // Same as above, except it takes a pointer to a search node object // instead of node index. CharSamp **BackTrack(SearchObject *srch_obj, SearchNode *node, int *char_cnt, char_32 **str32, Boxa **char_boxes) const; // Returns the size cost of a specified string of a lattice // path that ends at the specified lattice node. int SizeCost(SearchObject *srch_obj, SearchNode *node, char_32 **str32 = NULL) const; // Returns the word unigram cost of the given string, possibly // stripping out a single trailing punctuation character. int WordUnigramCost(char_32 *str32, WordUnigrams* word_unigrams) const; // Supplementary functions needed for visualization // Return column count of the lattice. inline int ColCnt() const { return col_cnt_; } // Returns the lattice column corresponding to the specified column index. SearchColumn *Column(int col_idx) const; // Return the index of the best node in the last column of the // best-cost path before the alternates list is sorted. inline int BestPresortedNodeIndex() const { return best_presorted_node_idx_; }; private: // Maximum reasonable segmentation point count static const int kMaxSegPointCnt = 128; // Recognition context object; the context holds the character classifier // and the tuning parameters object CubeRecoContext *cntxt_; // Count of segmentation pts int seg_pt_cnt_; // Lattice column count; currently redundant with respect to seg_pt_cnt_ // but that might change in the future int col_cnt_; // Array of lattice columns SearchColumn **col_; // Run in word or phrase mode bool word_mode_; // Node index of best-cost node, before alternates are merged and sorted int best_presorted_node_idx_; // Cleans up beam search state void Cleanup(); // Creates a Word alternate list from the results in the lattice. // This function computes a cost for each node in the final column // of the lattice, which is a weighted average of several costs: // size cost, character bigram cost, word unigram cost, and // recognition cost from the beam search. The weights are the // CubeTuningParams, which are learned together with the character // classifiers. WordAltList *CreateWordAltList(SearchObject *srch_obj); // Creates a set of children nodes emerging from a parent node based on // the character alternate list and the language model. void CreateChildren(SearchColumn *out_col, LangModel *lang_mod, SearchNode *parent_node, LangModEdge *lm_parent_edge, CharAltList *char_alt_list, int extra_cost); // Backtracks from the given lattice node and returns the corresponding // char mapped segments, character count, and character bounding boxes (if // char_boxes is not NULL). If the segments cannot be constructed, // returns NULL, and all result arguments will be NULL. CharSamp **SplitByNode(SearchObject *srch_obj, SearchNode *srch_node, int* char_cnt, Boxa **char_boxes) const; }; } #endif // BEAM_SEARCH_H
C++
/********************************************************************** * File: classifier_base.h * Description: Declaration of the Base Character Classifier * 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 CharClassifier class is the abstract class for any character/grapheme // classifier. #ifndef CHAR_CLASSIFIER_BASE_H #define CHAR_CLASSIFIER_BASE_H #include <string> #include "char_samp.h" #include "char_altlist.h" #include "char_set.h" #include "feature_base.h" #include "lang_model.h" #include "tuning_params.h" namespace tesseract { class CharClassifier { public: CharClassifier(CharSet *char_set, TuningParams *params, FeatureBase *feat_extract) { char_set_ = char_set; params_ = params; feat_extract_ = feat_extract; fold_sets_ = NULL; fold_set_cnt_ = 0; fold_set_len_ = NULL; init_ = false; case_sensitive_ = true; } virtual ~CharClassifier() { if (fold_sets_ != NULL) { for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { if (fold_sets_[fold_set] != NULL) { delete []fold_sets_[fold_set]; } } delete []fold_sets_; fold_sets_ = NULL; } if (fold_set_len_ != NULL) { delete []fold_set_len_; fold_set_len_ = NULL; } if (feat_extract_ != NULL) { delete feat_extract_; feat_extract_ = NULL; } } // pure virtual functions that need to be implemented by any inheriting class virtual CharAltList * Classify(CharSamp *char_samp) = 0; virtual int CharCost(CharSamp *char_samp) = 0; virtual bool Train(CharSamp *char_samp, int ClassID) = 0; virtual bool SetLearnParam(char *var_name, float val) = 0; virtual bool Init(const string &data_file_path, const string &lang, LangModel *lang_mod) = 0; // accessors FeatureBase *FeatureExtractor() {return feat_extract_;} inline bool CaseSensitive() const { return case_sensitive_; } inline void SetCaseSensitive(bool case_sensitive) { case_sensitive_ = case_sensitive; } protected: virtual void Fold() = 0; virtual bool LoadFoldingSets(const string &data_file_path, const string &lang, LangModel *lang_mod) = 0; FeatureBase *feat_extract_; CharSet *char_set_; TuningParams *params_; int **fold_sets_; int *fold_set_len_; int fold_set_cnt_; bool init_; bool case_sensitive_; }; } // tesseract #endif // CHAR_CLASSIFIER_BASE_H
C++
/********************************************************************** * File: word_list_lang_model.h * Description: Declaration of the Word List 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. * **********************************************************************/ // The WordListLangModel class abstracts a language model that is based on // a list of words. It inherits from the LangModel abstract class // Besides providing the methods inherited from the LangModel abstract class, // the class provided methods to add new strings to the Language Model: // AddString & AddString32 #ifndef WORD_LIST_LANG_MODEL_H #define WORD_LIST_LANG_MODEL_H #include <vector> #include "cube_reco_context.h" #include "lang_model.h" #include "tess_lang_mod_edge.h" namespace tesseract { class Trie; class WordListLangModel : public LangModel { public: explicit WordListLangModel(CubeRecoContext *cntxt); ~WordListLangModel(); // Returns an edge pointer to the Root LangModEdge *Root(); // Returns the edges that fan-out of the specified edge and their count LangModEdge **GetEdges(CharAltList *alt_list, LangModEdge *edge, int *edge_cnt); // Returns is a sequence of 32-bit characters are valid within this language // model or net. And EndOfWord flag is specified. If true, the sequence has // to end on a valid word. The function also optionally returns the list // of language model edges traversed to parse the string bool IsValidSequence(const char_32 *sequence, bool eow_flag, LangModEdge **edges); bool IsLeadingPunc(char_32 ch) { return false; } // not yet implemented bool IsTrailingPunc(char_32 ch) { return false; } // not yet implemented bool IsDigit(char_32 ch) { return false; } // not yet implemented // Adds a new UTF-8 string to the language model bool AddString(const char *char_ptr); // Adds a new UTF-32 string to the language model bool AddString32(const char_32 *char_32_ptr); // Compute all the variants of a 32-bit string in terms of the class-ids. // This is needed for languages that have ligatures. A word can then have // more than one spelling in terms of the class-ids. static void WordVariants(const CharSet &char_set, const UNICHARSET *uchset, string_32 str32, vector<WERD_CHOICE *> *word_variants); private: // constants needed to configure the language model static const int kMaxEdge = 512; CubeRecoContext *cntxt_; Trie *dawg_; bool init_; // Initialize the language model bool Init(); // Cleanup void Cleanup(); // Recursive helper function for WordVariants(). static void WordVariants( const CharSet &char_set, string_32 prefix_str32, WERD_CHOICE *word_so_far, string_32 str32, vector<WERD_CHOICE *> *word_variants); }; } // tesseract #endif // WORD_LIST_LANG_MODEL_H
C++
/********************************************************************** * File: con_comp.cpp * Description: Implementation of a Connected Component 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 <stdlib.h> #include <string.h> #include "con_comp.h" #include "cube_const.h" namespace tesseract { ConComp::ConComp() { head_ = NULL; tail_ = NULL; left_ = 0; top_ = 0; right_ = 0; bottom_ = 0; left_most_ = false; right_most_ = false; id_ = -1; pt_cnt_ = 0; } ConComp::~ConComp() { if (head_ != NULL) { ConCompPt *pt_ptr = head_; while (pt_ptr != NULL) { ConCompPt *pptNext = pt_ptr->Next(); delete pt_ptr; pt_ptr = pptNext; } head_ = NULL; } } // adds a pt to the conn comp and updates its boundaries bool ConComp::Add(int x, int y) { ConCompPt *pt_ptr = new ConCompPt(x, y); if (pt_ptr == NULL) { return false; } if (head_ == NULL) { left_ = x; right_ = x; top_ = y; bottom_ = y; head_ = pt_ptr; } else { left_ = left_ <= x ? left_ : x; top_ = top_ <= y ? top_ : y; right_ = right_ >= x ? right_ : x; bottom_ = bottom_ >= y ? bottom_ : y; } if (tail_ != NULL) { tail_->SetNext(pt_ptr); } tail_ = pt_ptr; pt_cnt_++; return true; } // merges two connected components bool ConComp::Merge(ConComp *concomp) { if (head_ == NULL || tail_ == NULL || concomp->head_ == NULL || concomp->tail_ == NULL) { return false; } tail_->SetNext(concomp->head_); tail_ = concomp->tail_; left_ = left_ <= concomp->left_ ? left_ : concomp->left_; top_ = top_ <= concomp->top_ ? top_ : concomp->top_; right_ = right_ >= concomp->right_ ? right_ : concomp->right_; bottom_ = bottom_ >= concomp->bottom_ ? bottom_ : concomp->bottom_; pt_cnt_ += concomp->pt_cnt_; concomp->head_ = NULL; concomp->tail_ = NULL; return true; } // Creates the x-coord density histogram after spreading // each x-coord position by the HIST_WND_RATIO fraction of the // height of the ConComp, but limited to max_hist_wnd int *ConComp::CreateHistogram(int max_hist_wnd) { int wid = right_ - left_ + 1, hgt = bottom_ - top_ + 1, hist_wnd = static_cast<int>(hgt * HIST_WND_RATIO); if (hist_wnd > max_hist_wnd) { hist_wnd = max_hist_wnd; } // alloc memo for histogram int *hist_array = new int[wid]; if (hist_array == NULL) { return NULL; } memset(hist_array, 0, wid * sizeof(*hist_array)); // compute windowed histogram ConCompPt *pt_ptr = head_; while (pt_ptr != NULL) { int x = pt_ptr->x() - left_, xw = x - hist_wnd; for (int xdel = -hist_wnd; xdel <= hist_wnd; xdel++, xw++) { if (xw >= 0 && xw < wid) { hist_array[xw]++; } } pt_ptr = pt_ptr->Next(); } return hist_array; } // find out the seg pts by looking for local minima in the histogram int *ConComp::SegmentHistogram(int *hist_array, int *seg_pt_cnt) { // init (*seg_pt_cnt) = 0; int wid = right_ - left_ + 1, hgt = bottom_ - top_ + 1; int *x_seg_pt = new int[wid]; if (x_seg_pt == NULL) { return NULL; } int seg_pt_wnd = static_cast<int>(hgt * SEG_PT_WND_RATIO); if (seg_pt_wnd > 1) { seg_pt_wnd = 1; } for (int x = 2; x < (wid - 2); x++) { if (hist_array[x] < hist_array[x - 1] && hist_array[x] < hist_array[x - 2] && hist_array[x] <= hist_array[x + 1] && hist_array[x] <= hist_array[x + 2]) { x_seg_pt[(*seg_pt_cnt)++] = x; x += seg_pt_wnd; } else if (hist_array[x] <= hist_array[x - 1] && hist_array[x] <= hist_array[x - 2] && hist_array[x] < hist_array[x + 1] && hist_array[x] < hist_array[x + 2]) { x_seg_pt[(*seg_pt_cnt)++] = x; x += seg_pt_wnd; } } // no segments, nothing to do if ((*seg_pt_cnt) == 0) { delete []x_seg_pt; return NULL; } return x_seg_pt; } // segments a concomp based on pixel density histogram local minima // if there were none found, it returns NULL // this is more useful than creating a clone of itself ConComp **ConComp::Segment(int max_hist_wnd, int *concomp_cnt) { // init (*concomp_cnt) = 0; // No pts if (head_ == NULL) { return NULL; } int seg_pt_cnt = 0; // create the histogram int *hist_array = CreateHistogram(max_hist_wnd); if (hist_array == NULL) { return NULL; } int *x_seg_pt = SegmentHistogram(hist_array, &seg_pt_cnt); // free histogram delete []hist_array; // no segments, nothing to do if (seg_pt_cnt == 0) { delete []x_seg_pt; return NULL; } // create concomp array ConComp **concomp_array = new ConComp *[seg_pt_cnt + 1]; if (concomp_array == NULL) { delete []x_seg_pt; return NULL; } for (int concomp = 0; concomp <= seg_pt_cnt; concomp++) { concomp_array[concomp] = new ConComp(); if (concomp_array[concomp] == NULL) { delete []x_seg_pt; delete []concomp_array; return NULL; } // split concomps inherit the ID this concomp concomp_array[concomp]->SetID(id_); } // set the left and right most attributes of the // appropriate concomps concomp_array[0]->left_most_ = true; concomp_array[seg_pt_cnt]->right_most_ = true; // assign pts to concomps ConCompPt *pt_ptr = head_; while (pt_ptr != NULL) { int seg_pt; // find the first seg-pt that exceeds the x value // of the pt for (seg_pt = 0; seg_pt < seg_pt_cnt; seg_pt++) { if ((x_seg_pt[seg_pt] + left_) > pt_ptr->x()) { break; } } // add the pt to the proper concomp if (concomp_array[seg_pt]->Add(pt_ptr->x(), pt_ptr->y()) == false) { delete []x_seg_pt; delete []concomp_array; return NULL; } pt_ptr = pt_ptr->Next(); } delete []x_seg_pt; (*concomp_cnt) = (seg_pt_cnt + 1); return concomp_array; } // Shifts the co-ordinates of all points by the specified x & y deltas void ConComp::Shift(int dx, int dy) { ConCompPt *pt_ptr = head_; while (pt_ptr != NULL) { pt_ptr->Shift(dx, dy); pt_ptr = pt_ptr->Next(); } left_ += dx; right_ += dx; top_ += dy; bottom_ += dy; } } // namespace tesseract
C++
/********************************************************************** * File: alt_list.h * Description: Class to abstarct a list of alternate results * 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 AltList class is the base class for the list of alternate recognition // results. Each alternate has a cost an an optional tag associated with it #ifndef ALT_LIST_H #define ALT_LIST_H #include <math.h> #include "cube_utils.h" namespace tesseract { class AltList { public: explicit AltList(int max_alt); virtual ~AltList(); // sort the list of alternates based virtual void Sort() = 0; // return the best possible cost and index of corresponding alternate int BestCost (int *best_alt) const; // return the count of alternates inline int AltCount() const { return alt_cnt_; } // returns the cost (-ve log prob) of an alternate inline int AltCost(int alt_idx) const { return alt_cost_[alt_idx]; } // returns the prob of an alternate inline double AltProb(int alt_idx) const { return CubeUtils::Cost2Prob(AltCost(alt_idx)); } // returns the alternate tag inline void *AltTag(int alt_idx) const { return alt_tag_[alt_idx]; } protected: // max number of alternates the list can hold int max_alt_; // actual alternate count int alt_cnt_; // array of alternate costs int *alt_cost_; // array of alternate tags void **alt_tag_; }; } #endif // ALT_LIST_H
C++
/********************************************************************** * File: char_samp_set.h * Description: Declaration of a Character Sample Set 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 CharSampSet set encapsulates a set of CharSet objects typically // but not necessarily loaded from a file // It provides methods to load samples from File, Create a new file and // Add new char samples to the set #ifndef CHAR_SAMP_SET_H #define CHAR_SAMP_SET_H #include <stdlib.h> #include <stdio.h> #include <string> #include "char_samp.h" #include "char_samp_enum.h" #include "char_set.h" namespace tesseract { // chunks of samp pointers to allocate #define SAMP_ALLOC_BLOCK 10000 class CharSampSet { public: CharSampSet(); ~CharSampSet(); // return sample count int SampleCount() const { return cnt_; } // returns samples buffer CharSamp ** Samples() const { return samp_buff_; } // Create a CharSampSet set object from a file static CharSampSet *FromCharDumpFile(string file_name); // Enumerate the Samples in the set one-by-one calling the enumertor's // EnumCharSamp method for each sample static bool EnumSamples(string file_name, CharSampEnum *enumerator); // Create a new Char Dump file static FILE *CreateCharDumpFile(string file_name); // Add a new sample to the set bool Add(CharSamp *char_samp); private: // sample count int cnt_; // the char samp array CharSamp **samp_buff_; // Are the samples owned by the set or not. // Determines whether we should cleanup in the end bool own_samples_; // Cleanup void Cleanup(); // Load character samples from a file bool LoadCharSamples(FILE *fp); }; } #endif // CHAR_SAMP_SET_H
C++
/********************************************************************** * File: search_node.h * Description: Declaration of the Beam Search Node 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 SearchNode class abstracts the search lattice node in the lattice // generated by the BeamSearch class // The SearchNode class holds the lang_mod_edge associated with the lattice // node. It also holds a pointer to the parent SearchNode in the search path // In addition it holds the recognition and the language model costs of the // node and the path leading to this node #ifndef SEARCH_NODE_H #define SEARCH_NODE_H #include "lang_mod_edge.h" #include "cube_reco_context.h" namespace tesseract { class SearchNode { public: SearchNode(CubeRecoContext *cntxt, SearchNode *parent_node, int char_reco_cost, LangModEdge *edge, int col_idx); ~SearchNode(); // Updates the parent of the current node if the specified path yields // a better path cost bool UpdateParent(SearchNode *new_parent, int new_reco_cost, LangModEdge *new_edge); // returns the 32-bit string corresponding to the path leading to this node char_32 *PathString(); // True if the two input nodes correspond to the same path static bool IdenticalPath(SearchNode *node1, SearchNode *node2); inline const char_32 *NodeString() { return str_; } inline void SetString(char_32 *str) { str_ = str; } // This node's character recognition cost. inline int CharRecoCost() { return char_reco_cost_; } // Total character recognition cost of the nodes in the best path, // excluding this node. inline int BestPathRecoCost() { return best_path_reco_cost_; } // Number of nodes in best path. inline int BestPathLength() { return best_path_len_; } // Mean mixed cost, i.e., mean character recognition cost + // current language model cost, all weighted by the RecoWgt parameter inline int BestCost() { return best_cost_; } // Mean character recognition cost of the nodes on the best path, // including this node. inline int BestRecoCost() { return mean_char_reco_cost_ ; } inline int ColIdx() { return col_idx_; } inline SearchNode *ParentNode() { return parent_node_; } inline LangModEdge *LangModelEdge() { return lang_mod_edge_;} inline int LangModCost() { return LangModCost(lang_mod_edge_, parent_node_); } // A comparer function that allows the SearchColumn class to sort the // nodes based on the path cost inline static int SearchNodeComparer(const void *node1, const void *node2) { return (*(reinterpret_cast<SearchNode * const *>(node1)))->best_cost_ - (*(reinterpret_cast<SearchNode * const *>(node2)))->best_cost_; } private: CubeRecoContext *cntxt_; // Character code const char_32 *str_; // Recognition cost of most recent character int char_reco_cost_; // Mean mixed cost, i.e., mean character recognition cost + // current language model cost, all weighted by the RecoWgt parameter int best_cost_; // Mean character recognition cost of the nodes on the best path, // including this node. int mean_char_reco_cost_ ; // Total character recognition cost of the nodes in the best path, // excluding this node. int best_path_reco_cost_; // Number of nodes in best path. int best_path_len_; // Column index int col_idx_; // Parent Node SearchNode *parent_node_; // Language model edge LangModEdge *lang_mod_edge_; static int LangModCost(LangModEdge *lang_mod_edge, SearchNode *parent_node); }; // Implments a SearchNode hash table used to detect if a Search Node exists // or not. This is needed to make sure that identical paths in the BeamSearch // converge class SearchNodeHashTable { public: SearchNodeHashTable() { memset(bin_size_array_, 0, sizeof(bin_size_array_)); } ~SearchNodeHashTable() { } // inserts an entry in the hash table inline bool Insert(LangModEdge *lang_mod_edge, SearchNode *srch_node) { // compute hash based on the edge and its parent node edge unsigned int edge_hash = lang_mod_edge->Hash(); unsigned int parent_hash = (srch_node->ParentNode() == NULL ? 0 : srch_node->ParentNode()->LangModelEdge()->Hash()); unsigned int hash_bin = (edge_hash + parent_hash) % kSearchNodeHashBins; // already maxed out, just fail if (bin_size_array_[hash_bin] >= kMaxSearchNodePerBin) { return false; } bin_array_[hash_bin][bin_size_array_[hash_bin]++] = srch_node; return true; } // Looks up an entry in the hash table inline SearchNode *Lookup(LangModEdge *lang_mod_edge, SearchNode *parent_node) { // compute hash based on the edge and its parent node edge unsigned int edge_hash = lang_mod_edge->Hash(); unsigned int parent_hash = (parent_node == NULL ? 0 : parent_node->LangModelEdge()->Hash()); unsigned int hash_bin = (edge_hash + parent_hash) % kSearchNodeHashBins; // lookup the entries in the hash bin for (int node_idx = 0; node_idx < bin_size_array_[hash_bin]; node_idx++) { if (lang_mod_edge->IsIdentical( bin_array_[hash_bin][node_idx]->LangModelEdge()) == true && SearchNode::IdenticalPath( bin_array_[hash_bin][node_idx]->ParentNode(), parent_node) == true) { return bin_array_[hash_bin][node_idx]; } } return NULL; } private: // Hash bin size parameters. These were determined emperically. These affect // the speed of the beam search but have no impact on accuracy static const int kSearchNodeHashBins = 4096; static const int kMaxSearchNodePerBin = 512; int bin_size_array_[kSearchNodeHashBins]; SearchNode *bin_array_[kSearchNodeHashBins][kMaxSearchNodePerBin]; }; } #endif // SEARCH_NODE_H
C++
/********************************************************************** * File: word_size_model.cpp * Description: Implementation of the Word Size 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. * **********************************************************************/ #include <math.h> #include <string> #include <vector> #include "word_size_model.h" #include "cube_utils.h" namespace tesseract { WordSizeModel::WordSizeModel(CharSet * char_set, bool contextual) { char_set_ = char_set; contextual_ = contextual; } WordSizeModel::~WordSizeModel() { for (int fnt = 0; fnt < font_pair_size_models_.size(); fnt++) { FontPairSizeInfo fnt_info = font_pair_size_models_[fnt]; delete []fnt_info.pair_size_info[0]; delete []fnt_info.pair_size_info; } } WordSizeModel *WordSizeModel::Create(const string &data_file_path, const string &lang, CharSet *char_set, bool contextual) { WordSizeModel *obj = new WordSizeModel(char_set, contextual); if (!obj) { fprintf(stderr, "Cube ERROR (WordSizeModel::Create): unable to allocate " "new word size model object\n"); return NULL; } if (!obj->Init(data_file_path, lang)) { delete obj; return NULL; } return obj; } bool WordSizeModel::Init(const string &data_file_path, const string &lang) { string stats_file_name; stats_file_name = data_file_path + lang; stats_file_name += ".cube.size"; // read file to memory string str_data; if (!CubeUtils::ReadFileToString(stats_file_name, &str_data)) { return false; } // split to words vector<string> tokens; CubeUtils::SplitStringUsing(str_data, "\t\r\n", &tokens); if (tokens.size() < 1) { fprintf(stderr, "Cube ERROR (WordSizeModel::Init): invalid " "file contents: %s\n", stats_file_name.c_str()); return false; } font_pair_size_models_.clear(); // token count per line depends on whether the language is contextual or not int token_cnt = contextual_ ? (kExpectedTokenCount + 4) : kExpectedTokenCount; // the count of size classes depends on whether the language is contextual // or not. For non contextual languages (Ex: Eng), it is equal to the class // count. For contextual languages (Ex: Ara), it is equal to the class count // multiplied by the position count (4: start, middle, final, isolated) int size_class_cnt = contextual_ ? (char_set_->ClassCount() * 4) : char_set_->ClassCount(); string fnt_name = ""; for (int tok = 0; tok < tokens.size(); tok += token_cnt) { // a new font, write the old font data and re-init if (tok == 0 || fnt_name != tokens[tok]) { FontPairSizeInfo fnt_info; fnt_info.pair_size_info = new PairSizeInfo *[size_class_cnt]; if (!fnt_info.pair_size_info) { fprintf(stderr, "Cube ERROR (WordSizeModel::Init): error allcoating " "memory for font pair size info\n"); return false; } fnt_info.pair_size_info[0] = new PairSizeInfo[size_class_cnt * size_class_cnt]; if (!fnt_info.pair_size_info[0]) { fprintf(stderr, "Cube ERROR (WordSizeModel::Init): error allocating " "memory for font pair size info\n"); return false; } memset(fnt_info.pair_size_info[0], 0, size_class_cnt * size_class_cnt * sizeof(PairSizeInfo)); for (int cls = 1; cls < size_class_cnt; cls++) { fnt_info.pair_size_info[cls] = fnt_info.pair_size_info[cls - 1] + size_class_cnt; } // strip out path and extension string stripped_font_name = tokens[tok].substr(0, tokens[tok].find('.')); string::size_type strt_pos = stripped_font_name.find_last_of("/\\"); if (strt_pos != string::npos) { fnt_info.font_name = stripped_font_name.substr(strt_pos); } else { fnt_info.font_name = stripped_font_name; } font_pair_size_models_.push_back(fnt_info); } // parse the data int cls_0; int cls_1; double delta_top; double wid_0; double hgt_0; double wid_1; double hgt_1; int size_code_0; int size_code_1; // read and parse the tokens if (contextual_) { int start_0; int end_0; int start_1; int end_1; // The expected format for a character size bigram is as follows: // ClassId0<delim>Start-flag0<delim>End-flag0<delim>String0(ignored) // Width0<delim>Height0<delim> // ClassId1<delim>Start-flag1<delim>End-flag1<delim>String1(ignored) // HeightDelta<delim>Width1<delim>Height0<delim> // In case of non-contextual languages, the Start and End flags are // omitted if (sscanf(tokens[tok + 1].c_str(), "%d", &cls_0) != 1 || sscanf(tokens[tok + 2].c_str(), "%d", &start_0) != 1 || sscanf(tokens[tok + 3].c_str(), "%d", &end_0) != 1 || sscanf(tokens[tok + 5].c_str(), "%lf", &wid_0) != 1 || sscanf(tokens[tok + 6].c_str(), "%lf", &hgt_0) != 1 || sscanf(tokens[tok + 7].c_str(), "%d", &cls_1) != 1 || sscanf(tokens[tok + 8].c_str(), "%d", &start_1) != 1 || sscanf(tokens[tok + 9].c_str(), "%d", &end_1) != 1 || sscanf(tokens[tok + 11].c_str(), "%lf", &delta_top) != 1 || sscanf(tokens[tok + 12].c_str(), "%lf", &wid_1) != 1 || sscanf(tokens[tok + 13].c_str(), "%lf", &hgt_1) != 1 || (start_0 != 0 && start_0 != 1) || (end_0 != 0 && end_0 != 1) || (start_1 != 0 && start_1 != 1) || (end_1 != 0 && end_1 != 1)) { fprintf(stderr, "Cube ERROR (WordSizeModel::Init): bad format at " "line %d\n", 1 + (tok / token_cnt)); return false; } size_code_0 = SizeCode(cls_0, start_0, end_0); size_code_1 = SizeCode(cls_1, start_1, end_1); } else { if (sscanf(tokens[tok + 1].c_str(), "%d", &cls_0) != 1 || sscanf(tokens[tok + 3].c_str(), "%lf", &wid_0) != 1 || sscanf(tokens[tok + 4].c_str(), "%lf", &hgt_0) != 1 || sscanf(tokens[tok + 5].c_str(), "%d", &cls_1) != 1 || sscanf(tokens[tok + 7].c_str(), "%lf", &delta_top) != 1 || sscanf(tokens[tok + 8].c_str(), "%lf", &wid_1) != 1 || sscanf(tokens[tok + 9].c_str(), "%lf", &hgt_1) != 1) { fprintf(stderr, "Cube ERROR (WordSizeModel::Init): bad format at " "line %d\n", 1 + (tok / token_cnt)); return false; } size_code_0 = cls_0; size_code_1 = cls_1; } // copy the data to the size tables FontPairSizeInfo fnt_info = font_pair_size_models_.back(); fnt_info.pair_size_info[size_code_0][size_code_1].delta_top = static_cast<int>(delta_top * kShapeModelScale); fnt_info.pair_size_info[size_code_0][size_code_1].wid_0 = static_cast<int>(wid_0 * kShapeModelScale); fnt_info.pair_size_info[size_code_0][size_code_1].hgt_0 = static_cast<int>(hgt_0 * kShapeModelScale); fnt_info.pair_size_info[size_code_0][size_code_1].wid_1 = static_cast<int>(wid_1 * kShapeModelScale); fnt_info.pair_size_info[size_code_0][size_code_1].hgt_1 = static_cast<int>(hgt_1 * kShapeModelScale); fnt_name = tokens[tok]; } return true; } int WordSizeModel::Cost(CharSamp **samp_array, int samp_cnt) const { if (samp_cnt < 2) { return 0; } double best_dist = static_cast<double>(WORST_COST); int best_fnt = -1; for (int fnt = 0; fnt < font_pair_size_models_.size(); fnt++) { const FontPairSizeInfo *fnt_info = &font_pair_size_models_[fnt]; double mean_dist = 0; int pair_cnt = 0; for (int smp_0 = 0; smp_0 < samp_cnt; smp_0++) { int cls_0 = char_set_->ClassID(samp_array[smp_0]->StrLabel()); if (cls_0 < 1) { continue; } // compute size code for samp 0 based on class id and position int size_code_0; if (contextual_) { size_code_0 = SizeCode(cls_0, samp_array[smp_0]->FirstChar() == 0 ? 0 : 1, samp_array[smp_0]->LastChar() == 0 ? 0 : 1); } else { size_code_0 = cls_0; } int char0_height = samp_array[smp_0]->Height(); int char0_width = samp_array[smp_0]->Width(); int char0_top = samp_array[smp_0]->Top(); for (int smp_1 = smp_0 + 1; smp_1 < samp_cnt; smp_1++) { int cls_1 = char_set_->ClassID(samp_array[smp_1]->StrLabel()); if (cls_1 < 1) { continue; } // compute size code for samp 0 based on class id and position int size_code_1; if (contextual_) { size_code_1 = SizeCode(cls_1, samp_array[smp_1]->FirstChar() == 0 ? 0 : 1, samp_array[smp_1]->LastChar() == 0 ? 0 : 1); } else { size_code_1 = cls_1; } double dist = PairCost( char0_width, char0_height, char0_top, samp_array[smp_1]->Width(), samp_array[smp_1]->Height(), samp_array[smp_1]->Top(), fnt_info->pair_size_info[size_code_0][size_code_1]); if (dist > 0) { mean_dist += dist; pair_cnt++; } } // smp_1 } // smp_0 if (pair_cnt == 0) { continue; } mean_dist /= pair_cnt; if (best_fnt == -1 || mean_dist < best_dist) { best_dist = mean_dist; best_fnt = fnt; } } if (best_fnt == -1) { return static_cast<int>(WORST_COST); } else { return static_cast<int>(best_dist); } } double WordSizeModel::PairCost(int width_0, int height_0, int top_0, int width_1, int height_1, int top_1, const PairSizeInfo& pair_info) { double scale_factor = static_cast<double>(pair_info.hgt_0) / static_cast<double>(height_0); double dist = 0.0; if (scale_factor > 0) { double norm_width_0 = width_0 * scale_factor; double norm_width_1 = width_1 * scale_factor; double norm_height_1 = height_1 * scale_factor; double norm_delta_top = (top_1 - top_0) * scale_factor; // accumulate the distance between the model character and the // predicted one on all dimensions of the pair dist += fabs(pair_info.wid_0 - norm_width_0); dist += fabs(pair_info.wid_1 - norm_width_1); dist += fabs(pair_info.hgt_1 - norm_height_1); dist += fabs(pair_info.delta_top - norm_delta_top); } return dist; } } // namespace tesseract
C++
/********************************************************************** * File: feature_bmp.cpp * Description: Implementation of the Bitmap Feature 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 <stdio.h> #include <stdlib.h> #include <string> #include "feature_base.h" #include "feature_bmp.h" #include "cube_utils.h" #include "const.h" #include "char_samp.h" namespace tesseract { FeatureBmp::FeatureBmp(TuningParams *params) :FeatureBase(params) { conv_grid_size_ = params->ConvGridSize(); } FeatureBmp::~FeatureBmp() { } // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers CharSamp *FeatureBmp::ComputeFeatureBitmap(CharSamp *char_samp) { return char_samp->Scale(conv_grid_size_, conv_grid_size_); } // Compute the features for a given CharSamp bool FeatureBmp::ComputeFeatures(CharSamp *char_samp, float *features) { return char_samp->ComputeFeatures(conv_grid_size_, features); } }
C++
/********************************************************************** * File: char_altlist.cpp * Description: Implementation of a Character Alternate List 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 "char_altlist.h" namespace tesseract { // The CharSet is not class owned and must exist for // the life time of this class CharAltList::CharAltList(const CharSet *char_set, int max_alt) : AltList(max_alt) { char_set_ = char_set; max_alt_ = max_alt; class_id_alt_ = NULL; class_id_cost_ = NULL; } CharAltList::~CharAltList() { if (class_id_alt_ != NULL) { delete []class_id_alt_; class_id_alt_ = NULL; } if (class_id_cost_ != NULL) { delete []class_id_cost_; class_id_cost_ = NULL; } } // Insert a new char alternate bool CharAltList::Insert(int class_id, int cost, void *tag) { // validate class ID if (class_id < 0 || class_id >= char_set_->ClassCount()) { return false; } // allocate buffers if nedded if (class_id_alt_ == NULL || alt_cost_ == NULL) { class_id_alt_ = new int[max_alt_]; alt_cost_ = new int[max_alt_]; alt_tag_ = new void *[max_alt_]; if (class_id_alt_ == NULL || alt_cost_ == NULL || alt_tag_ == NULL) { return false; } memset(alt_tag_, 0, max_alt_ * sizeof(*alt_tag_)); } if (class_id_cost_ == NULL) { int class_cnt = char_set_->ClassCount(); class_id_cost_ = new int[class_cnt]; if (class_id_cost_ == NULL) { return false; } for (int ich = 0; ich < class_cnt; ich++) { class_id_cost_[ich] = WORST_COST; } } if (class_id < 0 || class_id >= char_set_->ClassCount()) { return false; } // insert the alternate class_id_alt_[alt_cnt_] = class_id; alt_cost_[alt_cnt_] = cost; alt_tag_[alt_cnt_] = tag; alt_cnt_++; class_id_cost_[class_id] = cost; return true; } // sort the alternate Desc. based on prob void CharAltList::Sort() { for (int alt_idx = 0; alt_idx < alt_cnt_; alt_idx++) { for (int alt = alt_idx + 1; alt < alt_cnt_; alt++) { if (alt_cost_[alt_idx] > alt_cost_[alt]) { int temp = class_id_alt_[alt_idx]; class_id_alt_[alt_idx] = class_id_alt_[alt]; class_id_alt_[alt] = temp; temp = alt_cost_[alt_idx]; alt_cost_[alt_idx] = alt_cost_[alt]; alt_cost_[alt] = temp; void *tag = alt_tag_[alt_idx]; alt_tag_[alt_idx] = alt_tag_[alt]; alt_tag_[alt] = tag; } } } } }
C++
/********************************************************************** * File: cached_file.h * Description: Declaration of a Cached File 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. * **********************************************************************/ #ifndef CACHED_FILE_H #define CACHED_FILE_H // The CachedFile class provides a large-cache read access to a file // It is mainly designed for loading large word dump files #include <stdio.h> #include <string> #ifdef USE_STD_NAMESPACE using std::string; #endif namespace tesseract { class CachedFile { public: explicit CachedFile(string file_name); ~CachedFile(); // reads a specified number of bytes to the specified buffer and // returns the actual number of bytes read int Read(void *read_buff, int bytes); // Returns the file size long Size(); // returns the current position in the file long Tell(); // End of file flag bool eof(); private: static const unsigned int kCacheSize = 0x8000000; // file name string file_name_; // internal file buffer unsigned char *buff_; // file position long file_pos_; // file size long file_size_; // position of file within buffer int buff_pos_; // buffer size int buff_size_; // file handle FILE *fp_; // Opens the file bool Open(); }; } #endif // CACHED_FILE_H
C++
/********************************************************************** * File: cube_utils.cpp * Description: Implementation 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. * **********************************************************************/ #include <math.h> #include <string> #include <vector> #include "cube_utils.h" #include "char_set.h" #include "unichar.h" namespace tesseract { CubeUtils::CubeUtils() { } CubeUtils::~CubeUtils() { } // convert a prob to a cost (-ve log prob) int CubeUtils::Prob2Cost(double prob_val) { if (prob_val < MIN_PROB) { return MIN_PROB_COST; } return static_cast<int>(-log(prob_val) * PROB2COST_SCALE); } // converts a cost to probability double CubeUtils::Cost2Prob(int cost) { return exp(-cost / PROB2COST_SCALE); } // computes the length of a NULL terminated char_32 string int CubeUtils::StrLen(const char_32 *char_32_ptr) { if (char_32_ptr == NULL) { return 0; } int len = -1; while (char_32_ptr[++len]); return len; } // compares two char_32 strings int CubeUtils::StrCmp(const char_32 *str1, const char_32 *str2) { const char_32 *pch1 = str1; const char_32 *pch2 = str2; for (; (*pch1) != 0 && (*pch2) != 0; pch1++, pch2++) { if ((*pch1) != (*pch2)) { return (*pch1) - (*pch2); } } if ((*pch1) == 0) { if ((*pch2) == 0) { return 0; } else { return -1; } } else { return 1; } } // Duplicates a 32-bit char buffer char_32 *CubeUtils::StrDup(const char_32 *str32) { int len = StrLen(str32); char_32 *new_str = new char_32[len + 1]; if (new_str == NULL) { return NULL; } memcpy(new_str, str32, len * sizeof(*str32)); new_str[len] = 0; return new_str; } // creates a char samp from a specified portion of the image CharSamp *CubeUtils::CharSampleFromPix(Pix *pix, int left, int top, int wid, int hgt) { // get the raw img data from the image unsigned char *temp_buff = GetImageData(pix, left, top, wid, hgt); if (temp_buff == NULL) { return NULL; } // create a char samp from temp buffer CharSamp *char_samp = CharSamp::FromRawData(left, top, wid, hgt, temp_buff); // clean up temp buffer delete []temp_buff; return char_samp; } // create a B/W image from a char_sample Pix *CubeUtils::PixFromCharSample(CharSamp *char_samp) { // parameter check if (char_samp == NULL) { return NULL; } // get the raw data int stride = char_samp->Stride(); int wid = char_samp->Width(); int hgt = char_samp->Height(); Pix *pix = pixCreate(wid, hgt, 1); if (pix == NULL) { return NULL; } // copy the contents unsigned char *line = char_samp->RawData(); for (int y = 0; y < hgt ; y++, line += stride) { for (int x = 0; x < wid; x++) { if (line[x] != 0) { pixSetPixel(pix, x, y, 0); } else { pixSetPixel(pix, x, y, 255); } } } return pix; } // creates a raw buffer from the specified location of the pix unsigned char *CubeUtils::GetImageData(Pix *pix, int left, int top, int wid, int hgt) { // skip invalid dimensions if (left < 0 || top < 0 || wid < 0 || hgt < 0 || (left + wid) > pix->w || (top + hgt) > pix->h || pix->d != 1) { return NULL; } // copy the char img to a temp buffer unsigned char *temp_buff = new unsigned char[wid * hgt]; if (temp_buff == NULL) { return NULL; } l_int32 w; l_int32 h; l_int32 d; l_int32 wpl; l_uint32 *line; l_uint32 *data; pixGetDimensions(pix, &w, &h, &d); wpl = pixGetWpl(pix); data = pixGetData(pix); line = data + (top * wpl); for (int y = 0, off = 0; y < hgt ; y++) { for (int x = 0; x < wid; x++, off++) { temp_buff[off] = GET_DATA_BIT(line, x + left) ? 0 : 255; } line += wpl; } return temp_buff; } // read file contents to a string bool CubeUtils::ReadFileToString(const string &file_name, string *str) { str->clear(); FILE *fp = fopen(file_name.c_str(), "rb"); if (fp == NULL) { return false; } // get the size of the size fseek(fp, 0, SEEK_END); int file_size = ftell(fp); if (file_size < 1) { fclose(fp); return false; } // adjust string size str->reserve(file_size); // read the contents rewind(fp); char *buff = new char[file_size]; if (buff == NULL) { fclose(fp); return false; } int read_bytes = fread(buff, 1, static_cast<int>(file_size), fp); if (read_bytes == file_size) { str->append(buff, file_size); } delete []buff; fclose(fp); return (read_bytes == file_size); } // splits a string into vectors based on specified delimiters void CubeUtils::SplitStringUsing(const string &str, const string &delims, vector<string> *str_vec) { // Optimize the common case where delims is a single character. if (delims[0] != '\0' && delims[1] == '\0') { char c = delims[0]; const char* p = str.data(); const char* end = p + str.size(); while (p != end) { if (*p == c) { ++p; } else { const char* start = p; while (++p != end && *p != c); str_vec->push_back(string(start, p - start)); } } return; } string::size_type begin_index, end_index; begin_index = str.find_first_not_of(delims); while (begin_index != string::npos) { end_index = str.find_first_of(delims, begin_index); if (end_index == string::npos) { str_vec->push_back(str.substr(begin_index)); return; } str_vec->push_back(str.substr(begin_index, (end_index - begin_index))); begin_index = str.find_first_not_of(delims, end_index); } } // UTF-8 to UTF-32 convesion functions void CubeUtils::UTF8ToUTF32(const char *utf8_str, string_32 *str32) { str32->clear(); int len = strlen(utf8_str); int step = 0; for (int ch = 0; ch < len; ch += step) { step = UNICHAR::utf8_step(utf8_str + ch); if (step > 0) { UNICHAR uni_ch(utf8_str + ch, step); (*str32) += uni_ch.first_uni(); } } } // UTF-8 to UTF-32 convesion functions void CubeUtils::UTF32ToUTF8(const char_32 *utf32_str, string *str) { str->clear(); for (const char_32 *ch_32 = utf32_str; (*ch_32) != 0; ch_32++) { UNICHAR uni_ch((*ch_32)); char *utf8 = uni_ch.utf8_str(); if (utf8 != NULL) { (*str) += utf8; delete []utf8; } } } bool CubeUtils::IsCaseInvariant(const char_32 *str32, CharSet *char_set) { bool all_one_case = true; bool capitalized; bool prev_upper; bool prev_lower; bool first_upper; bool first_lower; bool cur_upper; bool cur_lower; string str8; if (!char_set) { // If cube char_set is missing, use C-locale-dependent functions // on UTF8 characters to determine case properties. first_upper = isupper(str32[0]); first_lower = islower(str32[0]); if (first_upper) capitalized = true; prev_upper = first_upper; prev_lower = islower(str32[0]); for (int c = 1; str32[c] != 0; ++c) { cur_upper = isupper(str32[c]); cur_lower = islower(str32[c]); if ((prev_upper && cur_lower) || (prev_lower && cur_upper)) all_one_case = false; if (cur_upper) capitalized = false; prev_upper = cur_upper; prev_lower = cur_lower; } } else { UNICHARSET *unicharset = char_set->InternalUnicharset(); // Use UNICHARSET functions to determine case properties first_upper = unicharset->get_isupper(char_set->ClassID(str32[0])); first_lower = unicharset->get_islower(char_set->ClassID(str32[0])); if (first_upper) capitalized = true; prev_upper = first_upper; prev_lower = unicharset->get_islower(char_set->ClassID(str32[0])); for (int c = 1; c < StrLen(str32); ++c) { cur_upper = unicharset->get_isupper(char_set->ClassID(str32[c])); cur_lower = unicharset->get_islower(char_set->ClassID(str32[c])); if ((prev_upper && cur_lower) || (prev_lower && cur_upper)) all_one_case = false; if (cur_upper) capitalized = false; prev_upper = cur_upper; prev_lower = cur_lower; } } return all_one_case || capitalized; } char_32 *CubeUtils::ToLower(const char_32 *str32, CharSet *char_set) { if (!char_set) { return NULL; } UNICHARSET *unicharset = char_set->InternalUnicharset(); int len = StrLen(str32); char_32 *lower = new char_32[len + 1]; if (!lower) return NULL; for (int i = 0; i < len; ++i) { char_32 ch = str32[i]; if (ch == INVALID_UNICHAR_ID) { delete [] lower; return NULL; } // convert upper-case characters to lower-case if (unicharset->get_isupper(char_set->ClassID(ch))) { UNICHAR_ID uid_lower = unicharset->get_other_case(char_set->ClassID(ch)); const char_32 *str32_lower = char_set->ClassString(uid_lower); // expect lower-case version of character to be a single character if (!str32_lower || StrLen(str32_lower) != 1) { delete [] lower; return NULL; } lower[i] = str32_lower[0]; } else { lower[i] = ch; } } lower[len] = 0; return lower; } char_32 *CubeUtils::ToUpper(const char_32 *str32, CharSet *char_set) { if (!char_set) { return NULL; } UNICHARSET *unicharset = char_set->InternalUnicharset(); int len = StrLen(str32); char_32 *upper = new char_32[len + 1]; if (!upper) return NULL; for (int i = 0; i < len; ++i) { char_32 ch = str32[i]; if (ch == INVALID_UNICHAR_ID) { delete [] upper; return NULL; } // convert lower-case characters to upper-case if (unicharset->get_islower(char_set->ClassID(ch))) { UNICHAR_ID uid_upper = unicharset->get_other_case(char_set->ClassID(ch)); const char_32 *str32_upper = char_set->ClassString(uid_upper); // expect upper-case version of character to be a single character if (!str32_upper || StrLen(str32_upper) != 1) { delete [] upper; return NULL; } upper[i] = str32_upper[0]; } else { upper[i] = ch; } } upper[len] = 0; return upper; } } // namespace tesseract
C++
/********************************************************************** * File: word_unigrams.cpp * Description: Implementation of the Word Unigrams 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. * **********************************************************************/ #include <math.h> #include <string> #include <vector> #include <algorithm> #include "const.h" #include "cube_utils.h" #include "ndminx.h" #include "word_unigrams.h" namespace tesseract { WordUnigrams::WordUnigrams() { costs_ = NULL; words_ = NULL; word_cnt_ = 0; } WordUnigrams::~WordUnigrams() { if (words_ != NULL) { if (words_[0] != NULL) { delete []words_[0]; } delete []words_; words_ = NULL; } if (costs_ != NULL) { delete []costs_; } } // Load the word-list and unigrams from file and create an object // The word list is assumed to be sorted in lexicographic order. WordUnigrams *WordUnigrams::Create(const string &data_file_path, const string &lang) { string file_name; string str; file_name = data_file_path + lang; file_name += ".cube.word-freq"; // load the string into memory if (CubeUtils::ReadFileToString(file_name, &str) == false) { return NULL; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(str, "\r\n \t", &str_vec); if (str_vec.size() < 2) { return NULL; } // allocate memory WordUnigrams *word_unigrams_obj = new WordUnigrams(); if (word_unigrams_obj == NULL) { fprintf(stderr, "Cube ERROR (WordUnigrams::Create): could not create " "word unigrams object.\n"); return NULL; } int full_len = str.length(); int word_cnt = str_vec.size() / 2; word_unigrams_obj->words_ = new char*[word_cnt]; word_unigrams_obj->costs_ = new int[word_cnt]; if (word_unigrams_obj->words_ == NULL || word_unigrams_obj->costs_ == NULL) { fprintf(stderr, "Cube ERROR (WordUnigrams::Create): error allocating " "word unigram fields.\n"); delete word_unigrams_obj; return NULL; } word_unigrams_obj->words_[0] = new char[full_len]; if (word_unigrams_obj->words_[0] == NULL) { fprintf(stderr, "Cube ERROR (WordUnigrams::Create): error allocating " "word unigram fields.\n"); delete word_unigrams_obj; return NULL; } // construct sorted list of words and costs word_unigrams_obj->word_cnt_ = 0; char *char_buff = word_unigrams_obj->words_[0]; word_cnt = 0; int max_cost = 0; for (int wrd = 0; wrd < str_vec.size(); wrd += 2) { word_unigrams_obj->words_[word_cnt] = char_buff; strcpy(char_buff, str_vec[wrd].c_str()); char_buff += (str_vec[wrd].length() + 1); if (sscanf(str_vec[wrd + 1].c_str(), "%d", word_unigrams_obj->costs_ + word_cnt) != 1) { fprintf(stderr, "Cube ERROR (WordUnigrams::Create): error reading " "word unigram data.\n"); delete word_unigrams_obj; return NULL; } // update max cost max_cost = MAX(max_cost, word_unigrams_obj->costs_[word_cnt]); word_cnt++; } word_unigrams_obj->word_cnt_ = word_cnt; // compute the not-in-list-cost by assuming that a word not in the list // [ahmadab]: This can be computed as follows: // - Given that the distribution of words follow Zipf's law: // (F = K / (rank ^ S)), where s is slightly > 1.0 // - Number of words in the list is N // - The mean frequency of a word that did not appear in the list is the // area under the rest of the Zipf's curve divided by 2 (the mean) // - The area would be the bound integral from N to infinity = // (K * S) / (N ^ (S + 1)) ~= K / (N ^ 2) // - Given that cost = -LOG(prob), the cost of an unlisted word would be // = max_cost + 2*LOG(N) word_unigrams_obj->not_in_list_cost_ = max_cost + (2 * CubeUtils::Prob2Cost(1.0 / word_cnt)); // success return word_unigrams_obj; } // Split input into space-separated tokens, strip trailing punctuation // from each, determine case properties, call UTF-8 flavor of cost // function on each word, and aggregate all into single mean word // cost. int WordUnigrams::Cost(const char_32 *key_str32, LangModel *lang_mod, CharSet *char_set) const { if (!key_str32) return 0; // convert string to UTF8 to split into space-separated words string key_str; CubeUtils::UTF32ToUTF8(key_str32, &key_str); vector<string> words; CubeUtils::SplitStringUsing(key_str, " \t", &words); // no words => no cost if (words.size() <= 0) { return 0; } // aggregate the costs of all the words int cost = 0; for (int word_idx = 0; word_idx < words.size(); word_idx++) { // convert each word back to UTF32 for analyzing case and punctuation string_32 str32; CubeUtils::UTF8ToUTF32(words[word_idx].c_str(), &str32); int len = CubeUtils::StrLen(str32.c_str()); // strip all trailing punctuation string clean_str; int clean_len = len; bool trunc = false; while (clean_len > 0 && lang_mod->IsTrailingPunc(str32.c_str()[clean_len - 1])) { --clean_len; trunc = true; } // If either the original string was not truncated (no trailing // punctuation) or the entire string was removed (all characters // are trailing punctuation), evaluate original word as is; // otherwise, copy all but the trailing punctuation characters char_32 *clean_str32 = NULL; if (clean_len == 0 || !trunc) { clean_str32 = CubeUtils::StrDup(str32.c_str()); } else { clean_str32 = new char_32[clean_len + 1]; for (int i = 0; i < clean_len; ++i) { clean_str32[i] = str32[i]; } clean_str32[clean_len] = '\0'; } ASSERT_HOST(clean_str32 != NULL); string str8; CubeUtils::UTF32ToUTF8(clean_str32, &str8); int word_cost = CostInternal(str8.c_str()); // if case invariant, get costs of all-upper-case and all-lower-case // versions and return the min cost if (clean_len >= kMinLengthNumOrCaseInvariant && CubeUtils::IsCaseInvariant(clean_str32, char_set)) { char_32 *lower_32 = CubeUtils::ToLower(clean_str32, char_set); if (lower_32) { string lower_8; CubeUtils::UTF32ToUTF8(lower_32, &lower_8); word_cost = MIN(word_cost, CostInternal(lower_8.c_str())); delete [] lower_32; } char_32 *upper_32 = CubeUtils::ToUpper(clean_str32, char_set); if (upper_32) { string upper_8; CubeUtils::UTF32ToUTF8(upper_32, &upper_8); word_cost = MIN(word_cost, CostInternal(upper_8.c_str())); delete [] upper_32; } } if (clean_len >= kMinLengthNumOrCaseInvariant) { // if characters are all numeric, incur 0 word cost bool is_numeric = true; for (int i = 0; i < clean_len; ++i) { if (!lang_mod->IsDigit(clean_str32[i])) is_numeric = false; } if (is_numeric) word_cost = 0; } delete [] clean_str32; cost += word_cost; } // word_idx // return the mean cost return static_cast<int>(cost / static_cast<double>(words.size())); } // Search for UTF-8 string using binary search of sorted words_ array. int WordUnigrams::CostInternal(const char *key_str) const { if (strlen(key_str) == 0) return not_in_list_cost_; int hi = word_cnt_ - 1; int lo = 0; while (lo <= hi) { int current = (hi + lo) / 2; int comp = strcmp(key_str, words_[current]); // a match if (comp == 0) { return costs_[current]; } if (comp < 0) { // go lower hi = current - 1; } else { // go higher lo = current + 1; } } return not_in_list_cost_; } } // namespace tesseract
C++
/********************************************************************** * File: feature_chebyshev.h * Description: Declaration of the Chebyshev coefficients Feature 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 FeatureHybrid class implements a Bitmap feature extractor class. It // inherits from the FeatureBase class // This class describes the a hybrid feature vector composed by combining // the bitmap and the chebyshev feature vectors #ifndef FEATURE_HYBRID_H #define FEATURE_HYBRID_H #include "char_samp.h" #include "feature_bmp.h" #include "feature_chebyshev.h" namespace tesseract { class FeatureHybrid : public FeatureBase { public: explicit FeatureHybrid(TuningParams *params); virtual ~FeatureHybrid(); // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers virtual CharSamp *ComputeFeatureBitmap(CharSamp *samp); // Compute the features for a given CharSamp virtual bool ComputeFeatures(CharSamp *samp, float *features); // Returns the count of features virtual int FeatureCnt() { if (feature_bmp_ == NULL || feature_chebyshev_ == NULL) { return 0; } return feature_bmp_->FeatureCnt() + feature_chebyshev_->FeatureCnt(); } protected: FeatureBmp *feature_bmp_; FeatureChebyshev *feature_chebyshev_; }; } #endif // FEATURE_HYBRID_H
C++
/********************************************************************** * File: tess_lang_mod_edge.h * Description: Declaration of the Tesseract Language Model Edge 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 TessLangModEdge models an edge in the Tesseract language models // It inherits from the LangModEdge class #ifndef TESS_LANG_MOD_EDGE_H #define TESS_LANG_MOD_EDGE_H #include "dawg.h" #include "char_set.h" #include "lang_mod_edge.h" #include "cube_reco_context.h" #include "cube_utils.h" // Macros needed to identify punctuation in the langmodel state #ifdef _HMSW32_H #define LEAD_PUNC_EDGE_REF_MASK (inT64) 0x0000000100000000i64 #define TRAIL_PUNC_EDGE_REF_MASK (inT64) 0x0000000200000000i64 #define TRAIL_PUNC_REPEAT_MASK (inT64) 0xffff000000000000i64 #else #define LEAD_PUNC_EDGE_REF_MASK (inT64) 0x0000000100000000ll #define TRAIL_PUNC_EDGE_REF_MASK (inT64) 0x0000000200000000ll #define TRAIL_PUNC_REPEAT_MASK (inT64) 0xffff000000000000ll #endif // Number state machine macros #define NUMBER_STATE_SHIFT 0 #define NUMBER_STATE_MASK 0x0000000fl #define NUMBER_LITERAL_SHIFT 4 #define NUMBER_LITERAL_MASK 0x000000f0l #define NUMBER_REPEAT_SHIFT 8 #define NUMBER_REPEAT_MASK 0x00000f00l #define NUM_TRM -99 #define TRAIL_PUNC_REPEAT_SHIFT 48 #define IsLeadingPuncEdge(edge_mask) \ ((edge_mask & LEAD_PUNC_EDGE_REF_MASK) != 0) #define IsTrailingPuncEdge(edge_mask) \ ((edge_mask & TRAIL_PUNC_EDGE_REF_MASK) != 0) #define TrailingPuncCount(edge_mask) \ ((edge_mask & TRAIL_PUNC_REPEAT_MASK) >> TRAIL_PUNC_REPEAT_SHIFT) #define TrailingPuncEdgeMask(Cnt) \ (TRAIL_PUNC_EDGE_REF_MASK | ((Cnt) << TRAIL_PUNC_REPEAT_SHIFT)) // State machine IDs #define DAWG_OOD 0 #define DAWG_NUMBER 1 namespace tesseract { class TessLangModEdge : public LangModEdge { public: // Different ways of constructing a TessLangModEdge TessLangModEdge(CubeRecoContext *cntxt, const Dawg *edge_array, EDGE_REF edge, int class_id); TessLangModEdge(CubeRecoContext *cntxt, const Dawg *edge_array, EDGE_REF start_edge_idx, EDGE_REF end_edge_idx, int class_id); TessLangModEdge(CubeRecoContext *cntxt, int class_id); ~TessLangModEdge() {} // Accessors inline bool IsRoot() const { return root_; } inline void SetRoot(bool flag) { root_ = flag; } inline bool IsOOD() const { return (dawg_ == (Dawg *)DAWG_OOD); } inline bool IsNumber() const { return (dawg_ == (Dawg *)DAWG_NUMBER); } inline bool IsEOW() const { return (IsTerminal() || (dawg_->end_of_word(end_edge_) != 0)); } inline const Dawg *GetDawg() const { return dawg_; } inline EDGE_REF StartEdge() const { return start_edge_; } inline EDGE_REF EndEdge() const { return end_edge_; } inline EDGE_REF EdgeMask() const { return edge_mask_; } inline const char_32 * EdgeString() const { return str_; } inline int ClassID () const { return class_id_; } inline int PathCost() const { return path_cost_; } inline void SetEdgeMask(EDGE_REF edge_mask) { edge_mask_ = edge_mask; } inline void SetDawg(Dawg *dawg) { dawg_ = dawg; } inline void SetStartEdge(EDGE_REF edge_idx) { start_edge_ = edge_idx; } inline void SetEndEdge(EDGE_REF edge_idx) { end_edge_ = edge_idx; } // is this a terminal node: // we can terminate at any OOD char, trailing punc or // when the dawg terminates inline bool IsTerminal() const { return (IsOOD() || IsNumber() || IsTrailingPuncEdge(start_edge_) || dawg_->next_node(end_edge_) == 0); } // How many signals does the LM provide for tuning. These are flags like: // OOD or not, Number of not that are used by the training to compute // extra costs for each word. inline int SignalCnt() const { return 2; } // returns the weight assigned to a specified signal inline double SignalWgt(int signal) const { CubeTuningParams *params = reinterpret_cast<CubeTuningParams *>(cntxt_->Params()); if (params != NULL) { switch (signal) { case 0: return params->OODWgt(); break; case 1: return params->NumWgt(); break; } } return 0.0; } // sets the weight assigned to a specified signal: Used in training void SetSignalWgt(int signal, double wgt) { CubeTuningParams *params = reinterpret_cast<CubeTuningParams *>(cntxt_->Params()); if (params != NULL) { switch (signal) { case 0: params->SetOODWgt(wgt); break; case 1: params->SetNumWgt(wgt); break; } } } // returns the actual value of a specified signal int Signal(int signal) { switch (signal) { case 0: return IsOOD() ? MIN_PROB_COST : 0; break; case 1: return IsNumber() ? MIN_PROB_COST : 0; break; default: return 0; } } // returns the Hash value of the edge. Used by the SearchNode hash table // to quickly lookup exisiting edges to converge during search inline unsigned int Hash() const { return static_cast<unsigned int>(((start_edge_ | end_edge_) ^ ((reinterpret_cast<unsigned long int>(dawg_)))) ^ ((unsigned int)edge_mask_) ^ class_id_); } // A verbal description of the edge: Used by visualizers char *Description() const; // Is this edge identical to the specified edge inline bool IsIdentical(LangModEdge *lang_mod_edge) const { return (class_id_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->class_id_ && str_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->str_ && dawg_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->dawg_ && start_edge_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->start_edge_ && end_edge_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->end_edge_ && edge_mask_ == reinterpret_cast<TessLangModEdge *>(lang_mod_edge)->edge_mask_); } // Creates a set of fan-out edges for the specified edge static int CreateChildren(CubeRecoContext *cntxt, const Dawg *edges, NODE_REF edge_reg, LangModEdge **lm_edges); private: bool root_; CubeRecoContext *cntxt_; const Dawg *dawg_; EDGE_REF start_edge_; EDGE_REF end_edge_; EDGE_REF edge_mask_; int path_cost_; int class_id_; const char_32 * str_; // returns the cost of the lang_mod_edge inline int Cost() const { if (cntxt_ != NULL) { CubeTuningParams *params = reinterpret_cast<CubeTuningParams *>(cntxt_->Params()); if (dawg_ == (Dawg *)DAWG_OOD) { return static_cast<int>(params->OODWgt() * MIN_PROB_COST); } else if (dawg_ == (Dawg *)DAWG_NUMBER) { return static_cast<int>(params->NumWgt() * MIN_PROB_COST); } } return 0; } }; } // namespace tesseract #endif // TESS_LANG_MOD_EDGE_H
C++
/********************************************************************** * File: tess_lang_mod_edge.cpp * Description: Implementation of the Tesseract Language Model Edge 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. * **********************************************************************/ #include "tess_lang_mod_edge.h" #include "const.h" #include "unichar.h" namespace tesseract { // OOD constructor TessLangModEdge::TessLangModEdge(CubeRecoContext *cntxt, int class_id) { root_ = false; cntxt_ = cntxt; dawg_ = NULL; start_edge_ = 0; end_edge_ = 0; edge_mask_ = 0; class_id_ = class_id; str_ = cntxt_->CharacterSet()->ClassString(class_id); path_cost_ = Cost(); } // leading, trailing punc constructor and single byte UTF char TessLangModEdge::TessLangModEdge(CubeRecoContext *cntxt, const Dawg *dawg, EDGE_REF edge_idx, int class_id) { root_ = false; cntxt_ = cntxt; dawg_ = dawg; start_edge_ = edge_idx; end_edge_ = edge_idx; edge_mask_ = 0; class_id_ = class_id; str_ = cntxt_->CharacterSet()->ClassString(class_id); path_cost_ = Cost(); } // dict constructor: multi byte UTF char TessLangModEdge::TessLangModEdge(CubeRecoContext *cntxt, const Dawg *dawg, EDGE_REF start_edge_idx, EDGE_REF end_edge_idx, int class_id) { root_ = false; cntxt_ = cntxt; dawg_ = dawg; start_edge_ = start_edge_idx; end_edge_ = end_edge_idx; edge_mask_ = 0; class_id_ = class_id; str_ = cntxt_->CharacterSet()->ClassString(class_id); path_cost_ = Cost(); } char *TessLangModEdge::Description() const { char *char_ptr = new char[256]; if (!char_ptr) { return NULL; } char dawg_str[256]; char edge_str[32]; if (dawg_ == (Dawg *)DAWG_OOD) { strcpy(dawg_str, "OOD"); } else if (dawg_ == (Dawg *)DAWG_NUMBER) { strcpy(dawg_str, "NUM"); } else if (dawg_->permuter() == SYSTEM_DAWG_PERM) { strcpy(dawg_str, "Main"); } else if (dawg_->permuter() == USER_DAWG_PERM) { strcpy(dawg_str, "User"); } else if (dawg_->permuter() == DOC_DAWG_PERM) { strcpy(dawg_str, "Doc"); } else { strcpy(dawg_str, "N/A"); } sprintf(edge_str, "%d", static_cast<int>(start_edge_)); if (IsLeadingPuncEdge(edge_mask_)) { strcat(edge_str, "-LP"); } if (IsTrailingPuncEdge(edge_mask_)) { strcat(edge_str, "-TP"); } sprintf(char_ptr, "%s(%s)%s, Wtd Dawg Cost=%d", dawg_str, edge_str, IsEOW() ? "-EOW-" : "", path_cost_); return char_ptr; } int TessLangModEdge::CreateChildren(CubeRecoContext *cntxt, const Dawg *dawg, NODE_REF parent_node, LangModEdge **edge_array) { int edge_cnt = 0; NodeChildVector vec; dawg->unichar_ids_of(parent_node, &vec, false); // find all children for (int i = 0; i < vec.size(); ++i) { const NodeChild &child = vec[i]; if (child.unichar_id == INVALID_UNICHAR_ID) continue; edge_array[edge_cnt] = new TessLangModEdge(cntxt, dawg, child.edge_ref, child.unichar_id); if (edge_array[edge_cnt] != NULL) edge_cnt++; } return edge_cnt; } }
C++
/********************************************************************** * File: search_object.h * Description: Declaration of the Beam Search Object 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 SearchObject class represents a char_samp (a word bitmap) that is // being searched for characters (or recognizeable entities). // This is an abstract class that all SearchObjects should inherit from // A SearchObject class provides methods to: // 1- Returns the count of segments // 2- Recognize a segment range // 3- Creates a CharSamp for a segment range #ifndef SEARCH_OBJECT_H #define SEARCH_OBJECT_H #include "char_altlist.h" #include "char_samp.h" #include "cube_reco_context.h" namespace tesseract { class SearchObject { public: explicit SearchObject(CubeRecoContext *cntxt) { cntxt_ = cntxt; } virtual ~SearchObject() {} virtual int SegPtCnt() = 0; virtual CharAltList *RecognizeSegment(int start_pt, int end_pt) = 0; virtual CharSamp *CharSample(int start_pt, int end_pt) = 0; virtual Box* CharBox(int start_pt, int end_pt) = 0; virtual int SpaceCost(int seg_pt) = 0; virtual int NoSpaceCost(int seg_pt) = 0; virtual int NoSpaceCost(int start_pt, int end_pt) = 0; protected: CubeRecoContext *cntxt_; }; } #endif // SEARCH_OBJECT_H
C++
/********************************************************************** * File: word_list_lang_model.cpp * Description: Implementation of the Word List 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. * **********************************************************************/ #include <string> #include <vector> #include "word_list_lang_model.h" #include "cube_utils.h" #include "ratngs.h" #include "trie.h" namespace tesseract { WordListLangModel::WordListLangModel(CubeRecoContext *cntxt) { cntxt_ = cntxt; dawg_ = NULL; init_ = false; } WordListLangModel::~WordListLangModel() { Cleanup(); } // Cleanup void WordListLangModel::Cleanup() { if (dawg_ != NULL) { delete dawg_; dawg_ = NULL; } init_ = false; } // Initialize the language model bool WordListLangModel::Init() { if (init_ == true) { return true; } // The last parameter to the Trie constructor (the debug level) is set to // false for now, until Cube has a way to express its preferred debug level. dawg_ = new Trie(DAWG_TYPE_WORD, "", NO_PERM, cntxt_->CharacterSet()->ClassCount(), false); if (dawg_ == NULL) { return false; } init_ = true; return true; } // return a pointer to the root LangModEdge * WordListLangModel::Root() { return NULL; } // return the edges emerging from the current state LangModEdge **WordListLangModel::GetEdges(CharAltList *alt_list, LangModEdge *edge, int *edge_cnt) { // initialize if necessary if (init_ == false) { if (Init() == false) { return NULL; } } (*edge_cnt) = 0; EDGE_REF edge_ref; TessLangModEdge *tess_lm_edge = reinterpret_cast<TessLangModEdge *>(edge); if (tess_lm_edge == NULL) { edge_ref = 0; } else { edge_ref = tess_lm_edge->EndEdge(); // advance node edge_ref = dawg_->next_node(edge_ref); if (edge_ref == 0) { return NULL; } } // allocate memory for edges LangModEdge **edge_array = new LangModEdge *[kMaxEdge]; if (edge_array == NULL) { return NULL; } // now get all the emerging edges (*edge_cnt) += TessLangModEdge::CreateChildren(cntxt_, dawg_, edge_ref, edge_array + (*edge_cnt)); return edge_array; } // returns true if the char_32 is supported by the language model // TODO(ahmadab) currently not implemented bool WordListLangModel::IsValidSequence(const char_32 *sequence, bool terminal, LangModEdge **edges) { return false; } // Recursive helper function for WordVariants(). void WordListLangModel::WordVariants(const CharSet &char_set, string_32 prefix_str32, WERD_CHOICE *word_so_far, string_32 str32, vector<WERD_CHOICE *> *word_variants) { int str_len = str32.length(); if (str_len == 0) { if (word_so_far->length() > 0) { word_variants->push_back(new WERD_CHOICE(*word_so_far)); } } else { // Try out all the possible prefixes of the str32. for (int len = 1; len <= str_len; len++) { // Check if prefix is supported in character set. string_32 str_pref32 = str32.substr(0, len); int class_id = char_set.ClassID(reinterpret_cast<const char_32 *>( str_pref32.c_str())); if (class_id <= 0) { continue; } else { string_32 new_prefix_str32 = prefix_str32 + str_pref32; string_32 new_str32 = str32.substr(len); word_so_far->append_unichar_id(class_id, 1, 0.0, 0.0); WordVariants(char_set, new_prefix_str32, word_so_far, new_str32, word_variants); word_so_far->remove_last_unichar_id(); } } } } // Compute all the variants of a 32-bit string in terms of the class-ids // This is needed for languages that have ligatures. A word can then have more // than one spelling in terms of the class-ids void WordListLangModel::WordVariants(const CharSet &char_set, const UNICHARSET *uchset, string_32 str32, vector<WERD_CHOICE *> *word_variants) { for (int i = 0; i < word_variants->size(); i++) { delete (*word_variants)[i]; } word_variants->clear(); string_32 prefix_str32; WERD_CHOICE word_so_far(uchset); WordVariants(char_set, prefix_str32, &word_so_far, str32, word_variants); } // add a new UTF-8 string to the lang model bool WordListLangModel::AddString(const char *char_ptr) { if (!init_ && !Init()) { // initialize if necessary return false; } string_32 str32; CubeUtils::UTF8ToUTF32(char_ptr, &str32); if (str32.length() < 1) { return false; } return AddString32(str32.c_str()); } // add a new UTF-32 string to the lang model bool WordListLangModel::AddString32(const char_32 *char_32_ptr) { if (char_32_ptr == NULL) { return false; } // get all the word variants vector<WERD_CHOICE *> word_variants; WordVariants(*(cntxt_->CharacterSet()), cntxt_->TessUnicharset(), char_32_ptr, &word_variants); if (word_variants.size() > 0) { // find the shortest variant int shortest_word = 0; for (int word = 1; word < word_variants.size(); word++) { if (word_variants[shortest_word]->length() > word_variants[word]->length()) { shortest_word = word; } } // only add the shortest grapheme interpretation of string to the word list dawg_->add_word_to_dawg(*word_variants[shortest_word]); } for (int i = 0; i < word_variants.size(); i++) { delete word_variants[i]; } return true; } }
C++
/********************************************************************** * File: word_altlist.cpp * Description: Implementation of the Word Alternate List 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. * **********************************************************************/ #include "word_altlist.h" namespace tesseract { WordAltList::WordAltList(int max_alt) : AltList(max_alt) { word_alt_ = NULL; } WordAltList::~WordAltList() { if (word_alt_ != NULL) { for (int alt_idx = 0; alt_idx < alt_cnt_; alt_idx++) { if (word_alt_[alt_idx] != NULL) { delete []word_alt_[alt_idx]; } } delete []word_alt_; word_alt_ = NULL; } } // insert an alternate word with the specified cost and tag bool WordAltList::Insert(char_32 *word_str, int cost, void *tag) { if (word_alt_ == NULL || alt_cost_ == NULL) { word_alt_ = new char_32*[max_alt_]; alt_cost_ = new int[max_alt_]; alt_tag_ = new void *[max_alt_]; if (word_alt_ == NULL || alt_cost_ == NULL || alt_tag_ == NULL) { return false; } memset(alt_tag_, 0, max_alt_ * sizeof(*alt_tag_)); } else { // check if alt already exists for (int alt_idx = 0; alt_idx < alt_cnt_; alt_idx++) { if (CubeUtils::StrCmp(word_str, word_alt_[alt_idx]) == 0) { // update the cost if we have a lower one if (cost < alt_cost_[alt_idx]) { alt_cost_[alt_idx] = cost; alt_tag_[alt_idx] = tag; } return true; } } } // determine length of alternate int len = CubeUtils::StrLen(word_str); word_alt_[alt_cnt_] = new char_32[len + 1]; if (word_alt_[alt_cnt_] == NULL) { return false; } if (len > 0) { memcpy(word_alt_[alt_cnt_], word_str, len * sizeof(*word_str)); } word_alt_[alt_cnt_][len] = 0; alt_cost_[alt_cnt_] = cost; alt_tag_[alt_cnt_] = tag; alt_cnt_++; return true; } // sort the alternate in descending order based on the cost void WordAltList::Sort() { for (int alt_idx = 0; alt_idx < alt_cnt_; alt_idx++) { for (int alt = alt_idx + 1; alt < alt_cnt_; alt++) { if (alt_cost_[alt_idx] > alt_cost_[alt]) { char_32 *pchTemp = word_alt_[alt_idx]; word_alt_[alt_idx] = word_alt_[alt]; word_alt_[alt] = pchTemp; int temp = alt_cost_[alt_idx]; alt_cost_[alt_idx] = alt_cost_[alt]; alt_cost_[alt] = temp; void *tag = alt_tag_[alt_idx]; alt_tag_[alt_idx] = alt_tag_[alt]; alt_tag_[alt] = tag; } } } } void WordAltList::PrintDebug() { for (int alt_idx = 0; alt_idx < alt_cnt_; alt_idx++) { char_32 *word_32 = word_alt_[alt_idx]; string word_str; CubeUtils::UTF32ToUTF8(word_32, &word_str); int num_unichars = CubeUtils::StrLen(word_32); fprintf(stderr, "Alt[%d]=%s (cost=%d, num_unichars=%d); unichars=", alt_idx, word_str.c_str(), alt_cost_[alt_idx], num_unichars); for (int i = 0; i < num_unichars; ++i) fprintf(stderr, "%d ", word_32[i]); fprintf(stderr, "\n"); } } } // namespace tesseract
C++
/********************************************************************** * File: feature_base.h * Description: Declaration of the Feature Base Class * Author: Ping Ping (xiupingping), 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 FeatureBase class is the base class for any Feature Extraction class // It provided 3 pure virtual functions (to inherit): // 1- FeatureCnt: A method to returns the count of features // 2- ComputeFeatures: A method to compute the features for a given CharSamp // 3- ComputeFeatureBitmap: A method to render a visualization of the features // to a CharSamp. This is mainly used by visual-debuggers #ifndef FEATURE_BASE_H #define FEATURE_BASE_H #include "char_samp.h" #include "tuning_params.h" namespace tesseract { class FeatureBase { public: explicit FeatureBase(TuningParams *params) : params_(params) { } virtual ~FeatureBase() {} // Compute the features for a given CharSamp virtual bool ComputeFeatures(CharSamp *char_samp, float *features) = 0; // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers virtual CharSamp *ComputeFeatureBitmap(CharSamp *char_samp) = 0; // Returns the count of features virtual int FeatureCnt() = 0; protected: TuningParams *params_; }; } #endif // FEATURE_BASE_H
C++
/********************************************************************** * File: cube_object.cpp * Description: Implementation of the Cube Object 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 <math.h> #include "cube_object.h" #include "cube_utils.h" #include "word_list_lang_model.h" namespace tesseract { CubeObject::CubeObject(CubeRecoContext *cntxt, CharSamp *char_samp) { Init(); char_samp_ = char_samp; cntxt_ = cntxt; } CubeObject::CubeObject(CubeRecoContext *cntxt, Pix *pix, int left, int top, int wid, int hgt) { Init(); char_samp_ = CubeUtils::CharSampleFromPix(pix, left, top, wid, hgt); own_char_samp_ = true; cntxt_ = cntxt; } // Data member initialization function void CubeObject::Init() { char_samp_ = NULL; own_char_samp_ = false; alt_list_ = NULL; srch_obj_ = NULL; deslanted_alt_list_ = NULL; deslanted_srch_obj_ = NULL; deslanted_ = false; deslanted_char_samp_ = NULL; beam_obj_ = NULL; deslanted_beam_obj_ = NULL; cntxt_ = NULL; } // Cleanup function void CubeObject::Cleanup() { if (alt_list_ != NULL) { delete alt_list_; alt_list_ = NULL; } if (deslanted_alt_list_ != NULL) { delete deslanted_alt_list_; deslanted_alt_list_ = NULL; } } CubeObject::~CubeObject() { if (char_samp_ != NULL && own_char_samp_ == true) { delete char_samp_; char_samp_ = NULL; } if (srch_obj_ != NULL) { delete srch_obj_; srch_obj_ = NULL; } if (deslanted_srch_obj_ != NULL) { delete deslanted_srch_obj_; deslanted_srch_obj_ = NULL; } if (beam_obj_ != NULL) { delete beam_obj_; beam_obj_ = NULL; } if (deslanted_beam_obj_ != NULL) { delete deslanted_beam_obj_; deslanted_beam_obj_ = NULL; } if (deslanted_char_samp_ != NULL) { delete deslanted_char_samp_; deslanted_char_samp_ = NULL; } Cleanup(); } // Actually do the recognition using the specified language mode. If none // is specified, the default language model in the CubeRecoContext is used. // Returns the sorted list of alternate answers // The Word mode determines whether recognition is done as a word or a phrase WordAltList *CubeObject::Recognize(LangModel *lang_mod, bool word_mode) { if (char_samp_ == NULL) { return NULL; } // clear alt lists Cleanup(); // no specified language model, use the one in the reco context if (lang_mod == NULL) { lang_mod = cntxt_->LangMod(); } // normalize if necessary if (cntxt_->SizeNormalization()) { Normalize(); } // assume not de-slanted by default deslanted_ = false; // create a beam search object if (beam_obj_ == NULL) { beam_obj_ = new BeamSearch(cntxt_, word_mode); if (beam_obj_ == NULL) { fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not construct " "BeamSearch\n"); return NULL; } } // create a cube search object if (srch_obj_ == NULL) { srch_obj_ = new CubeSearchObject(cntxt_, char_samp_); if (srch_obj_ == NULL) { fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not construct " "CubeSearchObject\n"); return NULL; } } // run a beam search against the tesslang model alt_list_ = beam_obj_->Search(srch_obj_, lang_mod); // deslant (if supported by language) and re-reco if probability is low enough if (cntxt_->HasItalics() == true && (alt_list_ == NULL || alt_list_->AltCount() < 1 || alt_list_->AltCost(0) > CubeUtils::Prob2Cost(kMinProbSkipDeslanted))) { if (deslanted_beam_obj_ == NULL) { deslanted_beam_obj_ = new BeamSearch(cntxt_); if (deslanted_beam_obj_ == NULL) { fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not " "construct deslanted BeamSearch\n"); return NULL; } } if (deslanted_srch_obj_ == NULL) { deslanted_char_samp_ = char_samp_->Clone(); if (deslanted_char_samp_ == NULL) { fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not " "construct deslanted CharSamp\n"); return NULL; } if (deslanted_char_samp_->Deslant() == false) { return NULL; } deslanted_srch_obj_ = new CubeSearchObject(cntxt_, deslanted_char_samp_); if (deslanted_srch_obj_ == NULL) { fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not " "construct deslanted CubeSearchObject\n"); return NULL; } } // run a beam search against the tesslang model deslanted_alt_list_ = deslanted_beam_obj_->Search(deslanted_srch_obj_, lang_mod); // should we use de-slanted altlist? if (deslanted_alt_list_ != NULL && deslanted_alt_list_->AltCount() > 0) { if (alt_list_ == NULL || alt_list_->AltCount() < 1 || deslanted_alt_list_->AltCost(0) < alt_list_->AltCost(0)) { deslanted_ = true; return deslanted_alt_list_; } } } return alt_list_; } // Recognize the member char sample as a word WordAltList *CubeObject::RecognizeWord(LangModel *lang_mod) { return Recognize(lang_mod, true); } // Recognize the member char sample as a word WordAltList *CubeObject::RecognizePhrase(LangModel *lang_mod) { return Recognize(lang_mod, false); } // Computes the cost of a specific string. This is done by performing // recognition of a language model that allows only the specified word int CubeObject::WordCost(const char *str) { WordListLangModel *lang_mod = new WordListLangModel(cntxt_); if (lang_mod == NULL) { return WORST_COST; } if (lang_mod->AddString(str) == false) { delete lang_mod; return WORST_COST; } // run a beam search against the single string wordlist model WordAltList *alt_list = RecognizeWord(lang_mod); delete lang_mod; int cost = WORST_COST; if (alt_list != NULL) { if (alt_list->AltCount() > 0) { cost = alt_list->AltCost(0); } } return cost; } // Recognizes a single character and returns the list of results. CharAltList *CubeObject::RecognizeChar() { if (char_samp_ == NULL) return NULL; CharAltList* alt_list = NULL; CharClassifier *char_classifier = cntxt_->Classifier(); ASSERT_HOST(char_classifier != NULL); alt_list = char_classifier->Classify(char_samp_); return alt_list; } // Normalize the input word bitmap to have a minimum aspect ratio bool CubeObject::Normalize() { // create a cube search object CubeSearchObject *srch_obj = new CubeSearchObject(cntxt_, char_samp_); if (srch_obj == NULL) { return false; } // Perform over-segmentation int seg_cnt = srch_obj->SegPtCnt(); // Only perform normalization if segment count is large enough if (seg_cnt < kMinNormalizationSegmentCnt) { delete srch_obj; return true; } // compute the mean AR of the segments double ar_mean = 0.0; for (int seg_idx = 0; seg_idx <= seg_cnt; seg_idx++) { CharSamp *seg_samp = srch_obj->CharSample(seg_idx - 1, seg_idx); if (seg_samp != NULL && seg_samp->Width() > 0) { ar_mean += (1.0 * seg_samp->Height() / seg_samp->Width()); } } ar_mean /= (seg_cnt + 1); // perform normalization if segment AR is too high if (ar_mean > kMinNormalizationAspectRatio) { // scale down the image in the y-direction to attain AR CharSamp *new_samp = char_samp_->Scale(char_samp_->Width(), 2.0 * char_samp_->Height() / ar_mean, false); if (new_samp != NULL) { // free existing char samp if owned if (own_char_samp_) { delete char_samp_; } // update with new scaled charsamp and set ownership flag char_samp_ = new_samp; own_char_samp_ = true; } } delete srch_obj; return true; } }
C++
/********************************************************************** * File: cube_search_object.cpp * Description: Implementation of the Cube Search Object 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 "cube_search_object.h" #include "cube_utils.h" #include "ndminx.h" namespace tesseract { const bool CubeSearchObject::kUseCroppedChars = true; CubeSearchObject::CubeSearchObject(CubeRecoContext *cntxt, CharSamp *samp) : SearchObject(cntxt) { init_ = false; reco_cache_ = NULL; samp_cache_ = NULL; segments_ = NULL; segment_cnt_ = 0; samp_ = samp; left_ = 0; itop_ = 0; space_cost_ = NULL; no_space_cost_ = NULL; wid_ = samp_->Width(); hgt_ = samp_->Height(); max_seg_per_char_ = cntxt_->Params()->MaxSegPerChar(); rtl_ = (cntxt_->ReadingOrder() == CubeRecoContext::R2L); min_spc_gap_ = static_cast<int>(hgt_ * cntxt_->Params()->MinSpaceHeightRatio()); max_spc_gap_ = static_cast<int>(hgt_ * cntxt_->Params()->MaxSpaceHeightRatio()); } CubeSearchObject::~CubeSearchObject() { Cleanup(); } // Cleanup void CubeSearchObject::Cleanup() { // delete Recognition Cache if (reco_cache_) { for (int strt_seg = 0; strt_seg < segment_cnt_; strt_seg++) { if (reco_cache_[strt_seg]) { for (int end_seg = 0; end_seg < segment_cnt_; end_seg++) { if (reco_cache_[strt_seg][end_seg]) { delete reco_cache_[strt_seg][end_seg]; } } delete []reco_cache_[strt_seg]; } } delete []reco_cache_; reco_cache_ = NULL; } // delete CharSamp Cache if (samp_cache_) { for (int strt_seg = 0; strt_seg < segment_cnt_; strt_seg++) { if (samp_cache_[strt_seg]) { for (int end_seg = 0; end_seg < segment_cnt_; end_seg++) { if (samp_cache_[strt_seg][end_seg]) { delete samp_cache_[strt_seg][end_seg]; } } delete []samp_cache_[strt_seg]; } } delete []samp_cache_; samp_cache_ = NULL; } // delete segment list if (segments_) { for (int seg = 0; seg < segment_cnt_; seg++) { if (segments_[seg]) { delete segments_[seg]; } } delete []segments_; segments_ = NULL; } if (space_cost_) { delete []space_cost_; space_cost_ = NULL; } if (no_space_cost_) { delete []no_space_cost_; no_space_cost_ = NULL; } segment_cnt_ = 0; init_ = false; } // # of segmentation points. One less than the count of segments int CubeSearchObject::SegPtCnt() { if (!init_ && !Init()) return -1; return segment_cnt_ - 1; } // init and allocate variables, perform segmentation bool CubeSearchObject::Init() { if (init_) return true; if (!Segment()) { return false; } // init cache reco_cache_ = new CharAltList **[segment_cnt_]; if (reco_cache_ == NULL) { fprintf(stderr, "Cube ERROR (CubeSearchObject::Init): could not " "allocate CharAltList array\n"); return false; } samp_cache_ = new CharSamp **[segment_cnt_]; if (samp_cache_ == NULL) { fprintf(stderr, "Cube ERROR (CubeSearchObject::Init): could not " "allocate CharSamp array\n"); return false; } for (int seg = 0; seg < segment_cnt_; seg++) { reco_cache_[seg] = new CharAltList *[segment_cnt_]; if (reco_cache_[seg] == NULL) { fprintf(stderr, "Cube ERROR (CubeSearchObject::Init): could not " "allocate a single segment's CharAltList array\n"); return false; } memset(reco_cache_[seg], 0, segment_cnt_ * sizeof(*reco_cache_[seg])); samp_cache_[seg] = new CharSamp *[segment_cnt_]; if (samp_cache_[seg] == NULL) { fprintf(stderr, "Cube ERROR (CubeSearchObject::Init): could not " "allocate a single segment's CharSamp array\n"); return false; } memset(samp_cache_[seg], 0, segment_cnt_ * sizeof(*samp_cache_[seg])); } init_ = true; return true; } // returns a char sample corresponding to the bitmap between 2 seg pts CharSamp *CubeSearchObject::CharSample(int start_pt, int end_pt) { // init if necessary if (!init_ && !Init()) return NULL; // validate segment range if (!IsValidSegmentRange(start_pt, end_pt)) return NULL; // look for the samp in the cache if (samp_cache_ && samp_cache_[start_pt + 1] && samp_cache_[start_pt + 1][end_pt]) { return samp_cache_[start_pt + 1][end_pt]; } // create a char samp object from the specified range of segments bool left_most; bool right_most; CharSamp *samp = CharSamp::FromConComps(segments_, start_pt + 1, end_pt - start_pt, NULL, &left_most, &right_most, hgt_); if (!samp) return NULL; if (kUseCroppedChars) { CharSamp *cropped_samp = samp->Crop(); // we no longer need the orig sample delete samp; if (!cropped_samp) return NULL; samp = cropped_samp; } // get the dimensions of the new cropped sample int char_top = samp->Top(); int char_wid = samp->Width(); int char_hgt = samp->Height(); // for cursive languages, these features correspond to whether // the charsamp is at the beginning or end of conncomp if (cntxt_->Cursive() == true) { // first and last char flags depend on reading order bool first_char = rtl_ ? right_most : left_most; bool last_char = rtl_ ? left_most : right_most; samp->SetFirstChar(first_char ? 255 : 0); samp->SetLastChar(last_char ? 255 : 0); } else { // for non cursive languages, these features correspond // to whether the charsamp is at the begining or end of the word samp->SetFirstChar((start_pt == -1) ? 255 : 0); samp->SetLastChar((end_pt == (segment_cnt_ - 1)) ? 255 : 0); } samp->SetNormTop(255 * char_top / hgt_); samp->SetNormBottom(255 * (char_top + char_hgt) / hgt_); samp->SetNormAspectRatio(255 * char_wid / (char_wid + char_hgt)); // add to cache & return samp_cache_[start_pt + 1][end_pt] = samp; return samp; } Box *CubeSearchObject::CharBox(int start_pt, int end_pt) { if (!init_ && !Init()) return NULL; if (!IsValidSegmentRange(start_pt, end_pt)) { fprintf(stderr, "Cube ERROR (CubeSearchObject::CharBox): invalid " "segment range (%d, %d)\n", start_pt, end_pt); return NULL; } // create a char samp object from the specified range of segments, // extract its dimensions into a leptonica box, and delete it bool left_most; bool right_most; CharSamp *samp = CharSamp::FromConComps(segments_, start_pt + 1, end_pt - start_pt, NULL, &left_most, &right_most, hgt_); if (!samp) return NULL; if (kUseCroppedChars) { CharSamp *cropped_samp = samp->Crop(); delete samp; if (!cropped_samp) { return NULL; } samp = cropped_samp; } Box *box = boxCreate(samp->Left(), samp->Top(), samp->Width(), samp->Height()); delete samp; return box; } // call from Beam Search to return the alt list corresponding to // recognizing the bitmap between two segmentation pts CharAltList * CubeSearchObject::RecognizeSegment(int start_pt, int end_pt) { // init if necessary if (!init_ && !Init()) { fprintf(stderr, "Cube ERROR (CubeSearchObject::RecognizeSegment): could " "not initialize CubeSearchObject\n"); return NULL; } // validate segment range if (!IsValidSegmentRange(start_pt, end_pt)) { fprintf(stderr, "Cube ERROR (CubeSearchObject::RecognizeSegment): invalid " "segment range (%d, %d)\n", start_pt, end_pt); return NULL; } // look for the recognition results in cache in the cache if (reco_cache_ && reco_cache_[start_pt + 1] && reco_cache_[start_pt + 1][end_pt]) { return reco_cache_[start_pt + 1][end_pt]; } // create the char sample corresponding to the blob CharSamp *samp = CharSample(start_pt, end_pt); if (!samp) { fprintf(stderr, "Cube ERROR (CubeSearchObject::RecognizeSegment): could " "not construct CharSamp\n"); return NULL; } // recognize the char sample CharClassifier *char_classifier = cntxt_->Classifier(); if (char_classifier) { reco_cache_[start_pt + 1][end_pt] = char_classifier->Classify(samp); } else { // no classifer: all characters are equally probable; add a penalty // that favors 2-segment characters and aspect ratios (w/h) > 1 fprintf(stderr, "Cube WARNING (CubeSearchObject::RecognizeSegment): cube " "context has no character classifier!! Inventing a probability " "distribution.\n"); int class_cnt = cntxt_->CharacterSet()->ClassCount(); CharAltList *alt_list = new CharAltList(cntxt_->CharacterSet(), class_cnt); int seg_cnt = end_pt - start_pt; double prob_val = (1.0 / class_cnt) * exp(-fabs(seg_cnt - 2.0)) * exp(-samp->Width() / static_cast<double>(samp->Height())); if (alt_list) { for (int class_idx = 0; class_idx < class_cnt; class_idx++) { alt_list->Insert(class_idx, CubeUtils::Prob2Cost(prob_val)); } reco_cache_[start_pt + 1][end_pt] = alt_list; } } return reco_cache_[start_pt + 1][end_pt]; } // Perform segmentation of the bitmap by detecting connected components, // segmenting each connected component using windowed vertical pixel density // histogram and sorting the resulting segments in reading order bool CubeSearchObject::Segment() { if (!samp_) return false; segment_cnt_ = 0; segments_ = samp_->Segment(&segment_cnt_, rtl_, cntxt_->Params()->HistWindWid(), cntxt_->Params()->MinConCompSize()); if (!segments_ || segment_cnt_ <= 0) { return false; } if (segment_cnt_ >= kMaxSegmentCnt) { return false; } return true; } // computes the space and no space costs at gaps between segments bool CubeSearchObject::ComputeSpaceCosts() { // init if necessary if (!init_ && !Init()) return false; // Already computed if (space_cost_) return true; // No segmentation points if (segment_cnt_ < 2) return false; // Compute the maximum x to the left of and minimum x to the right of each // segmentation point int *max_left_x = new int[segment_cnt_ - 1]; int *min_right_x = new int[segment_cnt_ - 1]; if (!max_left_x || !min_right_x) { delete []min_right_x; delete []max_left_x; return false; } if (rtl_) { min_right_x[0] = segments_[0]->Left(); max_left_x[segment_cnt_ - 2] = segments_[segment_cnt_ - 1]->Right(); for (int pt_idx = 1; pt_idx < (segment_cnt_ - 1); pt_idx++) { min_right_x[pt_idx] = MIN(min_right_x[pt_idx - 1], segments_[pt_idx]->Left()); max_left_x[segment_cnt_ - pt_idx - 2] = MAX(max_left_x[segment_cnt_ - pt_idx - 1], segments_[segment_cnt_ - pt_idx - 1]->Right()); } } else { min_right_x[segment_cnt_ - 2] = segments_[segment_cnt_ - 1]->Left(); max_left_x[0] = segments_[0]->Right(); for (int pt_idx = 1; pt_idx < (segment_cnt_ - 1); pt_idx++) { min_right_x[segment_cnt_ - pt_idx - 2] = MIN(min_right_x[segment_cnt_ - pt_idx - 1], segments_[segment_cnt_ - pt_idx - 1]->Left()); max_left_x[pt_idx] = MAX(max_left_x[pt_idx - 1], segments_[pt_idx]->Right()); } } // Allocate memory for space and no space costs // trivial cases space_cost_ = new int[segment_cnt_ - 1]; no_space_cost_ = new int[segment_cnt_ - 1]; if (!space_cost_ || !no_space_cost_) { delete []min_right_x; delete []max_left_x; return false; } // go through all segmentation points determining the horizontal gap between // the images on both sides of each break points. Use the gap to estimate // the probability of a space. The probability is modeled a linear function // of the gap width for (int pt_idx = 0; pt_idx < (segment_cnt_ - 1); pt_idx++) { // determine the gap at the segmentation point int gap = min_right_x[pt_idx] - max_left_x[pt_idx]; float prob = 0.0; // gap is too small => no space if (gap < min_spc_gap_) { prob = 0.0; } else if (gap > max_spc_gap_) { // gap is too big => definite space prob = 1.0; } else { // gap is somewhere in between, compute probability prob = (gap - min_spc_gap_) / static_cast<double>(max_spc_gap_ - min_spc_gap_); } // compute cost of space and non-space space_cost_[pt_idx] = CubeUtils::Prob2Cost(prob) + CubeUtils::Prob2Cost(0.1); no_space_cost_[pt_idx] = CubeUtils::Prob2Cost(1.0 - prob); } delete []min_right_x; delete []max_left_x; return true; } // Returns the cost of having a space before the specified segmentation point int CubeSearchObject::SpaceCost(int pt_idx) { if (!space_cost_ && !ComputeSpaceCosts()) { // Failed to compute costs return a zero prob return CubeUtils::Prob2Cost(0.0); } return space_cost_[pt_idx]; } // Returns the cost of not having a space before the specified // segmentation point int CubeSearchObject::NoSpaceCost(int pt_idx) { // If failed to compute costs, return a 1.0 prob if (!space_cost_ && !ComputeSpaceCosts()) return CubeUtils::Prob2Cost(0.0); return no_space_cost_[pt_idx]; } // Returns the cost of not having any spaces within the specified range // of segmentation points int CubeSearchObject::NoSpaceCost(int st_pt, int end_pt) { // If fail to compute costs, return a 1.0 prob if (!space_cost_ && !ComputeSpaceCosts()) return CubeUtils::Prob2Cost(1.0); int no_spc_cost = 0; for (int pt_idx = st_pt + 1; pt_idx < end_pt; pt_idx++) no_spc_cost += NoSpaceCost(pt_idx); return no_spc_cost; } }
C++
/********************************************************************** * File: charclassifier.cpp * Description: Implementation of Convolutional-NeuralNet Character Classifier * 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 <algorithm> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <wctype.h> #include "char_set.h" #include "classifier_base.h" #include "const.h" #include "conv_net_classifier.h" #include "cube_utils.h" #include "feature_base.h" #include "feature_bmp.h" #include "tess_lang_model.h" namespace tesseract { ConvNetCharClassifier::ConvNetCharClassifier(CharSet *char_set, TuningParams *params, FeatureBase *feat_extract) : CharClassifier(char_set, params, feat_extract) { char_net_ = NULL; net_input_ = NULL; net_output_ = NULL; } ConvNetCharClassifier::~ConvNetCharClassifier() { if (char_net_ != NULL) { delete char_net_; char_net_ = NULL; } if (net_input_ != NULL) { delete []net_input_; net_input_ = NULL; } if (net_output_ != NULL) { delete []net_output_; net_output_ = NULL; } } // The main training function. Given a sample and a class ID the classifier // updates its parameters according to its learning algorithm. This function // is currently not implemented. TODO(ahmadab): implement end-2-end training bool ConvNetCharClassifier::Train(CharSamp *char_samp, int ClassID) { return false; } // A secondary function needed for training. Allows the trainer to set the // value of any train-time paramter. This function is currently not // implemented. TODO(ahmadab): implement end-2-end training bool ConvNetCharClassifier::SetLearnParam(char *var_name, float val) { // TODO(ahmadab): implementation of parameter initializing. return false; } // Folds the output of the NeuralNet using the loaded folding sets void ConvNetCharClassifier::Fold() { // in case insensitive mode if (case_sensitive_ == false) { int class_cnt = char_set_->ClassCount(); // fold case for (int class_id = 0; class_id < class_cnt; class_id++) { // get class string const char_32 *str32 = char_set_->ClassString(class_id); // get the upper case form of the string string_32 upper_form32 = str32; for (int ch = 0; ch < upper_form32.length(); ch++) { if (iswalpha(static_cast<int>(upper_form32[ch])) != 0) { upper_form32[ch] = towupper(upper_form32[ch]); } } // find out the upperform class-id if any int upper_class_id = char_set_->ClassID(reinterpret_cast<const char_32 *>( upper_form32.c_str())); if (upper_class_id != -1 && class_id != upper_class_id) { float max_out = MAX(net_output_[class_id], net_output_[upper_class_id]); net_output_[class_id] = max_out; net_output_[upper_class_id] = max_out; } } } // The folding sets specify how groups of classes should be folded // Folding involved assigning a min-activation to all the members // of the folding set. The min-activation is a fraction of the max-activation // of the members of the folding set for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { if (fold_set_len_[fold_set] == 0) continue; float max_prob = net_output_[fold_sets_[fold_set][0]]; for (int ch = 1; ch < fold_set_len_[fold_set]; ch++) { if (net_output_[fold_sets_[fold_set][ch]] > max_prob) { max_prob = net_output_[fold_sets_[fold_set][ch]]; } } for (int ch = 0; ch < fold_set_len_[fold_set]; ch++) { net_output_[fold_sets_[fold_set][ch]] = MAX(max_prob * kFoldingRatio, net_output_[fold_sets_[fold_set][ch]]); } } } // Compute the features of specified charsamp and feedforward the // specified nets bool ConvNetCharClassifier::RunNets(CharSamp *char_samp) { if (char_net_ == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::RunNets): " "NeuralNet is NULL\n"); return false; } int feat_cnt = char_net_->in_cnt(); int class_cnt = char_set_->ClassCount(); // allocate i/p and o/p buffers if needed if (net_input_ == NULL) { net_input_ = new float[feat_cnt]; if (net_input_ == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::RunNets): " "unable to allocate memory for input nodes\n"); return false; } net_output_ = new float[class_cnt]; if (net_output_ == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::RunNets): " "unable to allocate memory for output nodes\n"); return false; } } // compute input features if (feat_extract_->ComputeFeatures(char_samp, net_input_) == false) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::RunNets): " "unable to compute features\n"); return false; } if (char_net_ != NULL) { if (char_net_->FeedForward(net_input_, net_output_) == false) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::RunNets): " "unable to run feed-forward\n"); return false; } } else { return false; } Fold(); return true; } // return the cost of being a char int ConvNetCharClassifier::CharCost(CharSamp *char_samp) { if (RunNets(char_samp) == false) { return 0; } return CubeUtils::Prob2Cost(1.0f - net_output_[0]); } // classifies a charsamp and returns an alternate list // of chars sorted by char costs CharAltList *ConvNetCharClassifier::Classify(CharSamp *char_samp) { // run the needed nets if (RunNets(char_samp) == false) { return NULL; } int class_cnt = char_set_->ClassCount(); // create an altlist CharAltList *alt_list = new CharAltList(char_set_, class_cnt); if (alt_list == NULL) { fprintf(stderr, "Cube WARNING (ConvNetCharClassifier::Classify): " "returning emtpy CharAltList\n"); return NULL; } for (int out = 1; out < class_cnt; out++) { int cost = CubeUtils::Prob2Cost(net_output_[out]); alt_list->Insert(out, cost); } return alt_list; } // Set an external net (for training purposes) void ConvNetCharClassifier::SetNet(tesseract::NeuralNet *char_net) { if (char_net_ != NULL) { delete char_net_; char_net_ = NULL; } char_net_ = char_net; } // This function will return true if the file does not exist. // But will fail if the it did not pass the sanity checks bool ConvNetCharClassifier::LoadFoldingSets(const string &data_file_path, const string &lang, LangModel *lang_mod) { fold_set_cnt_ = 0; string fold_file_name; fold_file_name = data_file_path + lang; fold_file_name += ".cube.fold"; // folding sets are optional FILE *fp = fopen(fold_file_name.c_str(), "rb"); if (fp == NULL) { return true; } fclose(fp); string fold_sets_str; if (!CubeUtils::ReadFileToString(fold_file_name, &fold_sets_str)) { return false; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(fold_sets_str, "\r\n", &str_vec); fold_set_cnt_ = str_vec.size(); fold_sets_ = new int *[fold_set_cnt_]; if (fold_sets_ == NULL) { return false; } fold_set_len_ = new int[fold_set_cnt_]; if (fold_set_len_ == NULL) { fold_set_cnt_ = 0; return false; } for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { reinterpret_cast<TessLangModel *>(lang_mod)->RemoveInvalidCharacters( &str_vec[fold_set]); // if all or all but one character are invalid, invalidate this set if (str_vec[fold_set].length() <= 1) { fprintf(stderr, "Cube WARNING (ConvNetCharClassifier::LoadFoldingSets): " "invalidating folding set %d\n", fold_set); fold_set_len_[fold_set] = 0; fold_sets_[fold_set] = NULL; continue; } string_32 str32; CubeUtils::UTF8ToUTF32(str_vec[fold_set].c_str(), &str32); fold_set_len_[fold_set] = str32.length(); fold_sets_[fold_set] = new int[fold_set_len_[fold_set]]; if (fold_sets_[fold_set] == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::LoadFoldingSets): " "could not allocate folding set\n"); fold_set_cnt_ = fold_set; return false; } for (int ch = 0; ch < fold_set_len_[fold_set]; ch++) { fold_sets_[fold_set][ch] = char_set_->ClassID(str32[ch]); } } return true; } // Init the classifier provided a data-path and a language string bool ConvNetCharClassifier::Init(const string &data_file_path, const string &lang, LangModel *lang_mod) { if (init_) { return true; } // load the nets if any. This function will return true if the net file // does not exist. But will fail if the net did not pass the sanity checks if (!LoadNets(data_file_path, lang)) { return false; } // load the folding sets if any. This function will return true if the // file does not exist. But will fail if the it did not pass the sanity checks if (!LoadFoldingSets(data_file_path, lang, lang_mod)) { return false; } init_ = true; return true; } // Load the classifier's Neural Nets // This function will return true if the net file does not exist. // But will fail if the net did not pass the sanity checks bool ConvNetCharClassifier::LoadNets(const string &data_file_path, const string &lang) { string char_net_file; // add the lang identifier char_net_file = data_file_path + lang; char_net_file += ".cube.nn"; // neural network is optional FILE *fp = fopen(char_net_file.c_str(), "rb"); if (fp == NULL) { return true; } fclose(fp); // load main net char_net_ = tesseract::NeuralNet::FromFile(char_net_file); if (char_net_ == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::LoadNets): " "could not load %s\n", char_net_file.c_str()); return false; } // validate net if (char_net_->in_cnt()!= feat_extract_->FeatureCnt()) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::LoadNets): " "could not validate net %s\n", char_net_file.c_str()); return false; } // alloc net i/o buffers int feat_cnt = char_net_->in_cnt(); int class_cnt = char_set_->ClassCount(); if (char_net_->out_cnt() != class_cnt) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::LoadNets): " "output count (%d) and class count (%d) are not equal\n", char_net_->out_cnt(), class_cnt); return false; } // allocate i/p and o/p buffers if needed if (net_input_ == NULL) { net_input_ = new float[feat_cnt]; if (net_input_ == NULL) { return false; } net_output_ = new float[class_cnt]; if (net_output_ == NULL) { return false; } } return true; } } // tesseract
C++
/********************************************************************** * 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
C++
/********************************************************************** * File: word_size_model.h * Description: Declaration of the Word Size 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. * **********************************************************************/ // The WordSizeModel class abstracts the geometrical relationships // between characters/shapes in the same word (presumeably of the same font) // A non-parametric bigram model describes the three geometrical properties of a // character pair: // 1- Normalized Width // 2- Normalized Top // 3- Normalized Height // These dimensions are computed for each character pair in a word. These are // then compared to the same information for each of the fonts that the size // model knows about. The WordSizeCost is the cost of the font that matches // best. #ifndef WORD_SIZE_MODEL_H #define WORD_SIZE_MODEL_H #include <string> #include "char_samp.h" #include "char_set.h" namespace tesseract { struct PairSizeInfo { int delta_top; int wid_0; int hgt_0; int wid_1; int hgt_1; }; struct FontPairSizeInfo { string font_name; PairSizeInfo **pair_size_info; }; class WordSizeModel { public: WordSizeModel(CharSet *, bool contextual); virtual ~WordSizeModel(); static WordSizeModel *Create(const string &data_file_path, const string &lang, CharSet *char_set, bool contextual); // Given a word and number of unichars, return the size cost, // minimized over all fonts in the size model. int Cost(CharSamp **samp_array, int samp_cnt) const; // Given dimensions of a pair of character samples and a font size // model for that character pair, return the pair's size cost for // the font. static double PairCost(int width_0, int height_0, int top_0, int width_1, int height_1, int top_1, const PairSizeInfo& pair_info); bool Save(string file_name); // Number of fonts in size model. inline int FontCount() const { return font_pair_size_models_.size(); } inline const FontPairSizeInfo *FontInfo() const { return &font_pair_size_models_[0]; } // Helper functions to convert between size codes, class id and position // codes static inline int SizeCode(int cls_id, int start, int end) { return (cls_id << 2) + (end << 1) + start; } private: // Scaling constant used to convert floating point ratios in size table // to fixed point static const int kShapeModelScale = 1000; static const int kExpectedTokenCount = 10; // Language properties bool contextual_; CharSet *char_set_; // Size ratios table vector<FontPairSizeInfo> font_pair_size_models_; // Initialize the word size model object bool Init(const string &data_file_path, const string &lang); }; } #endif // WORD_SIZE_MODEL_H
C++
/********************************************************************** * File: cube_tuning_params.cpp * Description: Implementation of the CubeTuningParameters 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 <vector> #include "cube_tuning_params.h" #include "tuning_params.h" #include "cube_utils.h" namespace tesseract { CubeTuningParams::CubeTuningParams() { reco_wgt_ = 1.0; size_wgt_ = 1.0; char_bigrams_wgt_ = 1.0; word_unigrams_wgt_ = 0.0; max_seg_per_char_ = 8; beam_width_ = 32; tp_classifier_ = NN; tp_feat_ = BMP; conv_grid_size_ = 32; hist_wind_wid_ = 0; max_word_aspect_ratio_ = 10.0; min_space_height_ratio_ = 0.2; max_space_height_ratio_ = 0.3; min_con_comp_size_ = 0; combiner_run_thresh_ = 1.0; combiner_classifier_thresh_ = 0.5; ood_wgt_ = 1.0; num_wgt_ = 1.0; } CubeTuningParams::~CubeTuningParams() { } // Create an Object given the data file path and the language by loading // the approporiate file CubeTuningParams *CubeTuningParams::Create(const string &data_file_path, const string &lang) { CubeTuningParams *obj = new CubeTuningParams(); if (!obj) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Create): unable to " "allocate new tuning params object\n"); return NULL; } string tuning_params_file; tuning_params_file = data_file_path + lang; tuning_params_file += ".cube.params"; if (!obj->Load(tuning_params_file)) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Create): unable to " "load tuning parameters from %s\n", tuning_params_file.c_str()); delete obj; obj = NULL; } return obj; } // Loads the params file bool CubeTuningParams::Load(string tuning_params_file) { // load the string into memory string param_str; if (CubeUtils::ReadFileToString(tuning_params_file, &param_str) == false) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): unable to read " "file %s\n", tuning_params_file.c_str()); return false; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(param_str, "\r\n", &str_vec); if (str_vec.size() < 8) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): number of rows " "in parameter file is too low\n"); return false; } // for all entries for (int entry = 0; entry < str_vec.size(); entry++) { // tokenize vector<string> str_tok; // should be only two tokens CubeUtils::SplitStringUsing(str_vec[entry], "=", &str_tok); if (str_tok.size() != 2) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): invalid format in " "line: %s.\n", str_vec[entry].c_str()); return false; } double val = 0; char peekchar = (str_tok[1].c_str())[0]; if ((peekchar >= '0' && peekchar <= '9') || peekchar == '-' || peekchar == '+' || peekchar == '.') { // read the value if (sscanf(str_tok[1].c_str(), "%lf", &val) != 1) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): invalid format " "in line: %s.\n", str_vec[entry].c_str()); return false; } } // token type if (str_tok[0] == "RecoWgt") { reco_wgt_ = val; } else if (str_tok[0] == "SizeWgt") { size_wgt_ = val; } else if (str_tok[0] == "CharBigramsWgt") { char_bigrams_wgt_ = val; } else if (str_tok[0] == "WordUnigramsWgt") { word_unigrams_wgt_ = val; } else if (str_tok[0] == "MaxSegPerChar") { max_seg_per_char_ = static_cast<int>(val); } else if (str_tok[0] == "BeamWidth") { beam_width_ = static_cast<int>(val); } else if (str_tok[0] == "Classifier") { if (str_tok[1] == "NN") { tp_classifier_ = TuningParams::NN; } else if (str_tok[1] == "HYBRID_NN") { tp_classifier_ = TuningParams::HYBRID_NN; } else { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): invalid " "classifier type in line: %s.\n", str_vec[entry].c_str()); return false; } } else if (str_tok[0] == "FeatureType") { if (str_tok[1] == "BMP") { tp_feat_ = TuningParams::BMP; } else if (str_tok[1] == "CHEBYSHEV") { tp_feat_ = TuningParams::CHEBYSHEV; } else if (str_tok[1] == "HYBRID") { tp_feat_ = TuningParams::HYBRID; } else { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): invalid feature " "type in line: %s.\n", str_vec[entry].c_str()); return false; } } else if (str_tok[0] == "ConvGridSize") { conv_grid_size_ = static_cast<int>(val); } else if (str_tok[0] == "HistWindWid") { hist_wind_wid_ = val; } else if (str_tok[0] == "MinConCompSize") { min_con_comp_size_ = val; } else if (str_tok[0] == "MaxWordAspectRatio") { max_word_aspect_ratio_ = val; } else if (str_tok[0] == "MinSpaceHeightRatio") { min_space_height_ratio_ = val; } else if (str_tok[0] == "MaxSpaceHeightRatio") { max_space_height_ratio_ = val; } else if (str_tok[0] == "CombinerRunThresh") { combiner_run_thresh_ = val; } else if (str_tok[0] == "CombinerClassifierThresh") { combiner_classifier_thresh_ = val; } else if (str_tok[0] == "OODWgt") { ood_wgt_ = val; } else if (str_tok[0] == "NumWgt") { num_wgt_ = val; } else { fprintf(stderr, "Cube ERROR (CubeTuningParams::Load): unknown parameter " "in line: %s.\n", str_vec[entry].c_str()); return false; } } return true; } // Save the parameters to a file bool CubeTuningParams::Save(string file_name) { FILE *params_file = fopen(file_name.c_str(), "wb"); if (params_file == NULL) { fprintf(stderr, "Cube ERROR (CubeTuningParams::Save): error opening file " "%s for write.\n", file_name.c_str()); return false; } fprintf(params_file, "RecoWgt=%.4f\n", reco_wgt_); fprintf(params_file, "SizeWgt=%.4f\n", size_wgt_); fprintf(params_file, "CharBigramsWgt=%.4f\n", char_bigrams_wgt_); fprintf(params_file, "WordUnigramsWgt=%.4f\n", word_unigrams_wgt_); fprintf(params_file, "MaxSegPerChar=%d\n", max_seg_per_char_); fprintf(params_file, "BeamWidth=%d\n", beam_width_); fprintf(params_file, "ConvGridSize=%d\n", conv_grid_size_); fprintf(params_file, "HistWindWid=%d\n", hist_wind_wid_); fprintf(params_file, "MinConCompSize=%d\n", min_con_comp_size_); fprintf(params_file, "MaxWordAspectRatio=%.4f\n", max_word_aspect_ratio_); fprintf(params_file, "MinSpaceHeightRatio=%.4f\n", min_space_height_ratio_); fprintf(params_file, "MaxSpaceHeightRatio=%.4f\n", max_space_height_ratio_); fprintf(params_file, "CombinerRunThresh=%.4f\n", combiner_run_thresh_); fprintf(params_file, "CombinerClassifierThresh=%.4f\n", combiner_classifier_thresh_); fprintf(params_file, "OODWgt=%.4f\n", ood_wgt_); fprintf(params_file, "NumWgt=%.4f\n", num_wgt_); fclose(params_file); return true; } }
C++
/********************************************************************** * File: charclassifier.cpp * Description: Implementation of Convolutional-NeuralNet Character Classifier * 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 <algorithm> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <wctype.h> #include "classifier_base.h" #include "char_set.h" #include "const.h" #include "conv_net_classifier.h" #include "cube_utils.h" #include "feature_base.h" #include "feature_bmp.h" #include "hybrid_neural_net_classifier.h" #include "tess_lang_model.h" namespace tesseract { HybridNeuralNetCharClassifier::HybridNeuralNetCharClassifier( CharSet *char_set, TuningParams *params, FeatureBase *feat_extract) : CharClassifier(char_set, params, feat_extract) { net_input_ = NULL; net_output_ = NULL; } HybridNeuralNetCharClassifier::~HybridNeuralNetCharClassifier() { for (int net_idx = 0; net_idx < nets_.size(); net_idx++) { if (nets_[net_idx] != NULL) { delete nets_[net_idx]; } } nets_.clear(); if (net_input_ != NULL) { delete []net_input_; net_input_ = NULL; } if (net_output_ != NULL) { delete []net_output_; net_output_ = NULL; } } // The main training function. Given a sample and a class ID the classifier // updates its parameters according to its learning algorithm. This function // is currently not implemented. TODO(ahmadab): implement end-2-end training bool HybridNeuralNetCharClassifier::Train(CharSamp *char_samp, int ClassID) { return false; } // A secondary function needed for training. Allows the trainer to set the // value of any train-time paramter. This function is currently not // implemented. TODO(ahmadab): implement end-2-end training bool HybridNeuralNetCharClassifier::SetLearnParam(char *var_name, float val) { // TODO(ahmadab): implementation of parameter initializing. return false; } // Folds the output of the NeuralNet using the loaded folding sets void HybridNeuralNetCharClassifier::Fold() { // in case insensitive mode if (case_sensitive_ == false) { int class_cnt = char_set_->ClassCount(); // fold case for (int class_id = 0; class_id < class_cnt; class_id++) { // get class string const char_32 *str32 = char_set_->ClassString(class_id); // get the upper case form of the string string_32 upper_form32 = str32; for (int ch = 0; ch < upper_form32.length(); ch++) { if (iswalpha(static_cast<int>(upper_form32[ch])) != 0) { upper_form32[ch] = towupper(upper_form32[ch]); } } // find out the upperform class-id if any int upper_class_id = char_set_->ClassID(reinterpret_cast<const char_32 *>( upper_form32.c_str())); if (upper_class_id != -1 && class_id != upper_class_id) { float max_out = MAX(net_output_[class_id], net_output_[upper_class_id]); net_output_[class_id] = max_out; net_output_[upper_class_id] = max_out; } } } // The folding sets specify how groups of classes should be folded // Folding involved assigning a min-activation to all the members // of the folding set. The min-activation is a fraction of the max-activation // of the members of the folding set for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { float max_prob = net_output_[fold_sets_[fold_set][0]]; for (int ch = 1; ch < fold_set_len_[fold_set]; ch++) { if (net_output_[fold_sets_[fold_set][ch]] > max_prob) { max_prob = net_output_[fold_sets_[fold_set][ch]]; } } for (int ch = 0; ch < fold_set_len_[fold_set]; ch++) { net_output_[fold_sets_[fold_set][ch]] = MAX(max_prob * kFoldingRatio, net_output_[fold_sets_[fold_set][ch]]); } } } // compute the features of specified charsamp and // feedforward the specified nets bool HybridNeuralNetCharClassifier::RunNets(CharSamp *char_samp) { int feat_cnt = feat_extract_->FeatureCnt(); int class_cnt = char_set_->ClassCount(); // allocate i/p and o/p buffers if needed if (net_input_ == NULL) { net_input_ = new float[feat_cnt]; if (net_input_ == NULL) { return false; } net_output_ = new float[class_cnt]; if (net_output_ == NULL) { return false; } } // compute input features if (feat_extract_->ComputeFeatures(char_samp, net_input_) == false) { return false; } // go thru all the nets memset(net_output_, 0, class_cnt * sizeof(*net_output_)); float *inputs = net_input_; for (int net_idx = 0; net_idx < nets_.size(); net_idx++) { // run each net vector<float> net_out(class_cnt, 0.0); if (!nets_[net_idx]->FeedForward(inputs, &net_out[0])) { return false; } // add the output values for (int class_idx = 0; class_idx < class_cnt; class_idx++) { net_output_[class_idx] += (net_out[class_idx] * net_wgts_[net_idx]); } // increment inputs pointer inputs += nets_[net_idx]->in_cnt(); } Fold(); return true; } // return the cost of being a char int HybridNeuralNetCharClassifier::CharCost(CharSamp *char_samp) { // it is by design that a character cost is equal to zero // when no nets are present. This is the case during training. if (RunNets(char_samp) == false) { return 0; } return CubeUtils::Prob2Cost(1.0f - net_output_[0]); } // classifies a charsamp and returns an alternate list // of chars sorted by char costs CharAltList *HybridNeuralNetCharClassifier::Classify(CharSamp *char_samp) { // run the needed nets if (RunNets(char_samp) == false) { return NULL; } int class_cnt = char_set_->ClassCount(); // create an altlist CharAltList *alt_list = new CharAltList(char_set_, class_cnt); if (alt_list == NULL) { return NULL; } for (int out = 1; out < class_cnt; out++) { int cost = CubeUtils::Prob2Cost(net_output_[out]); alt_list->Insert(out, cost); } return alt_list; } // set an external net (for training purposes) void HybridNeuralNetCharClassifier::SetNet(tesseract::NeuralNet *char_net) { } // Load folding sets // This function returns true on success or if the file can't be read, // returns false if an error is encountered. bool HybridNeuralNetCharClassifier::LoadFoldingSets( const string &data_file_path, const string &lang, LangModel *lang_mod) { fold_set_cnt_ = 0; string fold_file_name; fold_file_name = data_file_path + lang; fold_file_name += ".cube.fold"; // folding sets are optional FILE *fp = fopen(fold_file_name.c_str(), "rb"); if (fp == NULL) { return true; } fclose(fp); string fold_sets_str; if (!CubeUtils::ReadFileToString(fold_file_name, &fold_sets_str)) { return false; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(fold_sets_str, "\r\n", &str_vec); fold_set_cnt_ = str_vec.size(); fold_sets_ = new int *[fold_set_cnt_]; if (fold_sets_ == NULL) { return false; } fold_set_len_ = new int[fold_set_cnt_]; if (fold_set_len_ == NULL) { fold_set_cnt_ = 0; return false; } for (int fold_set = 0; fold_set < fold_set_cnt_; fold_set++) { reinterpret_cast<TessLangModel *>(lang_mod)->RemoveInvalidCharacters( &str_vec[fold_set]); // if all or all but one character are invalid, invalidate this set if (str_vec[fold_set].length() <= 1) { fprintf(stderr, "Cube WARNING (ConvNetCharClassifier::LoadFoldingSets): " "invalidating folding set %d\n", fold_set); fold_set_len_[fold_set] = 0; fold_sets_[fold_set] = NULL; continue; } string_32 str32; CubeUtils::UTF8ToUTF32(str_vec[fold_set].c_str(), &str32); fold_set_len_[fold_set] = str32.length(); fold_sets_[fold_set] = new int[fold_set_len_[fold_set]]; if (fold_sets_[fold_set] == NULL) { fprintf(stderr, "Cube ERROR (ConvNetCharClassifier::LoadFoldingSets): " "could not allocate folding set\n"); fold_set_cnt_ = fold_set; return false; } for (int ch = 0; ch < fold_set_len_[fold_set]; ch++) { fold_sets_[fold_set][ch] = char_set_->ClassID(str32[ch]); } } return true; } // Init the classifier provided a data-path and a language string bool HybridNeuralNetCharClassifier::Init(const string &data_file_path, const string &lang, LangModel *lang_mod) { if (init_ == true) { return true; } // load the nets if any. This function will return true if the net file // does not exist. But will fail if the net did not pass the sanity checks if (!LoadNets(data_file_path, lang)) { return false; } // load the folding sets if any. This function will return true if the // file does not exist. But will fail if the it did not pass the sanity checks if (!LoadFoldingSets(data_file_path, lang, lang_mod)) { return false; } init_ = true; return true; } // Load the classifier's Neural Nets // This function will return true if the net file does not exist. // But will fail if the net did not pass the sanity checks bool HybridNeuralNetCharClassifier::LoadNets(const string &data_file_path, const string &lang) { string hybrid_net_file; string junk_net_file; // add the lang identifier hybrid_net_file = data_file_path + lang; hybrid_net_file += ".cube.hybrid"; // neural network is optional FILE *fp = fopen(hybrid_net_file.c_str(), "rb"); if (fp == NULL) { return true; } fclose(fp); string str; if (!CubeUtils::ReadFileToString(hybrid_net_file, &str)) { return false; } // split into lines vector<string> str_vec; CubeUtils::SplitStringUsing(str, "\r\n", &str_vec); if (str_vec.size() <= 0) { return false; } // create and add the nets nets_.resize(str_vec.size(), NULL); net_wgts_.resize(str_vec.size(), 0); int total_input_size = 0; for (int net_idx = 0; net_idx < str_vec.size(); net_idx++) { // parse the string vector<string> tokens_vec; CubeUtils::SplitStringUsing(str_vec[net_idx], " \t", &tokens_vec); // has to be 2 tokens, net name and input size if (tokens_vec.size() != 2) { return false; } // load the net string net_file_name = data_file_path + tokens_vec[0]; nets_[net_idx] = tesseract::NeuralNet::FromFile(net_file_name); if (nets_[net_idx] == NULL) { return false; } // parse the input size and validate it net_wgts_[net_idx] = atof(tokens_vec[1].c_str()); if (net_wgts_[net_idx] < 0.0) { return false; } total_input_size += nets_[net_idx]->in_cnt(); } // validate total input count if (total_input_size != feat_extract_->FeatureCnt()) { return false; } // success return true; } } // tesseract
C++
/********************************************************************** * File: con_comp.h * Description: Declaration of a Connected Component 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. * **********************************************************************/ #ifndef CONCOMP_H #define CONCOMP_H // The ConComp class implements the functionality needed for a // Connected Component object and Connected Component (ConComp) points. // The points consituting a connected component are kept in a linked-list // The Concomp class provided methods to: // 1- Compare components in L2R and R2L reading orders. // 2- Merge ConComps // 3- Compute the windowed vertical pixel density histogram for a specific // windows size // 4- Segment a ConComp based on the local windowed vertical pixel // density histogram local minima namespace tesseract { // Implments a ConComp point in a linked list of points class ConCompPt { public: ConCompPt(int x, int y) { x_ = x; y_ = y; next_pt_ = NULL; } inline int x() { return x_; } inline int y() { return y_; } inline void Shift(int dx, int dy) { x_ += dx; y_ += dy; } inline ConCompPt * Next() { return next_pt_; } inline void SetNext(ConCompPt *pt) { next_pt_ = pt; } private: int x_; int y_; ConCompPt *next_pt_; }; class ConComp { public: ConComp(); virtual ~ConComp(); // accessors inline ConCompPt *Head() { return head_; } inline int Left() const { return left_; } inline int Top() const { return top_; } inline int Right() const { return right_; } inline int Bottom() const { return bottom_; } inline int Width() const { return right_ - left_ + 1; } inline int Height() const { return bottom_ - top_ + 1; } // Comparer used for sorting L2R reading order inline static int Left2RightComparer(const void *comp1, const void *comp2) { return (*(reinterpret_cast<ConComp * const *>(comp1)))->left_ + (*(reinterpret_cast<ConComp * const *>(comp1)))->right_ - (*(reinterpret_cast<ConComp * const *>(comp2)))->left_ - (*(reinterpret_cast<ConComp * const *>(comp2)))->right_; } // Comparer used for sorting R2L reading order inline static int Right2LeftComparer(const void *comp1, const void *comp2) { return (*(reinterpret_cast<ConComp * const *>(comp2)))->right_ - (*(reinterpret_cast<ConComp * const *>(comp1)))->right_; } // accessors for attribues of a ConComp inline bool LeftMost() const { return left_most_; } inline bool RightMost() const { return right_most_; } inline void SetLeftMost(bool left_most) { left_most_ = left_most; } inline void SetRightMost(bool right_most) { right_most_ = right_most; } inline int ID () const { return id_; } inline void SetID(int id) { id_ = id; } inline int PtCnt () const { return pt_cnt_; } // Add a new pt bool Add(int x, int y); // Merge two connected components in-place bool Merge(ConComp *con_comp); // Shifts the co-ordinates of all points by the specified x & y deltas void Shift(int dx, int dy); // segments a concomp based on pixel density histogram local minima ConComp **Segment(int max_hist_wnd, int *concomp_cnt); // creates the vertical pixel density histogram of the concomp int *CreateHistogram(int max_hist_wnd); // find out the seg pts by looking for local minima in the histogram int *SegmentHistogram(int *hist_array, int *seg_pt_cnt); private: int id_; bool left_most_; bool right_most_; int left_; int top_; int right_; int bottom_; ConCompPt *head_; ConCompPt *tail_; int pt_cnt_; }; } #endif // CONCOMP_H
C++
/********************************************************************** * File: cached_file.pp * Description: Implementation of an Cached File 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 <stdlib.h> #include <cstring> #include "cached_file.h" namespace tesseract { CachedFile::CachedFile(string file_name) { file_name_ = file_name; buff_ = NULL; buff_pos_ = 0; buff_size_ = 0; file_pos_ = 0; file_size_ = 0; fp_ = NULL; } CachedFile::~CachedFile() { if (fp_ != NULL) { fclose(fp_); fp_ = NULL; } if (buff_ != NULL) { delete []buff_; buff_ = NULL; } } // free buffers and init vars bool CachedFile::Open() { if (fp_ != NULL) { return true; } fp_ = fopen(file_name_.c_str(), "rb"); if (fp_ == NULL) { return false; } // seek to the end fseek(fp_, 0, SEEK_END); // get file size file_size_ = ftell(fp_); if (file_size_ < 1) { return false; } // rewind again rewind(fp_); // alloc memory for buffer buff_ = new unsigned char[kCacheSize]; if (buff_ == NULL) { return false; } // init counters buff_size_ = 0; buff_pos_ = 0; file_pos_ = 0; return true; } // add a new sample int CachedFile::Read(void *read_buff, int bytes) { int read_bytes = 0; unsigned char *buff = (unsigned char *)read_buff; // do we need to read beyond the buffer if ((buff_pos_ + bytes) > buff_size_) { // copy as much bytes from the current buffer if any int copy_bytes = buff_size_ - buff_pos_; if (copy_bytes > 0) { memcpy(buff, buff_ + buff_pos_, copy_bytes); buff += copy_bytes; bytes -= copy_bytes; read_bytes += copy_bytes; } // determine how much to read buff_size_ = kCacheSize; if ((file_pos_ + buff_size_) > file_size_) { buff_size_ = static_cast<int>(file_size_ - file_pos_); } // EOF ? if (buff_size_ <= 0 || bytes > buff_size_) { return read_bytes; } // read the first chunck if (fread(buff_, 1, buff_size_, fp_) != buff_size_) { return read_bytes; } buff_pos_ = 0; file_pos_ += buff_size_; } memcpy(buff, buff_ + buff_pos_, bytes); read_bytes += bytes; buff_pos_ += bytes; return read_bytes; } long CachedFile::Size() { if (fp_ == NULL && Open() == false) { return 0; } return file_size_; } long CachedFile::Tell() { if (fp_ == NULL && Open() == false) { return 0; } return file_pos_ - buff_size_ + buff_pos_; } bool CachedFile::eof() { if (fp_ == NULL && Open() == false) { return true; } return (file_pos_ - buff_size_ + buff_pos_) >= file_size_; } } // namespace tesseract
C++
/********************************************************************** * File: feature_chebyshev.cpp * Description: Implementation of the Chebyshev coefficients Feature 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. * **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string> #include <vector> #include <algorithm> #include "feature_base.h" #include "feature_chebyshev.h" #include "cube_utils.h" #include "const.h" #include "char_samp.h" namespace tesseract { FeatureChebyshev::FeatureChebyshev(TuningParams *params) : FeatureBase(params) { } FeatureChebyshev::~FeatureChebyshev() { } // Render a visualization of the features to a CharSamp. // This is mainly used by visual-debuggers CharSamp *FeatureChebyshev::ComputeFeatureBitmap(CharSamp *char_samp) { return char_samp; } // Compute Chebyshev coefficients for the specified vector void FeatureChebyshev::ChebyshevCoefficients(const vector<float> &input, int coeff_cnt, float *coeff) { // re-sample function int input_range = (input.size() - 1); vector<float> resamp(coeff_cnt); for (int samp_idx = 0; samp_idx < coeff_cnt; samp_idx++) { // compute sampling position float samp_pos = input_range * (1 + cos(M_PI * (samp_idx + 0.5) / coeff_cnt)) / 2; // interpolate int samp_start = static_cast<int>(samp_pos); int samp_end = static_cast<int>(samp_pos + 0.5); float func_delta = input[samp_end] - input[samp_start]; resamp[samp_idx] = input[samp_start] + ((samp_pos - samp_start) * func_delta); } // compute the coefficients float normalizer = 2.0 / coeff_cnt; for (int coeff_idx = 0; coeff_idx < coeff_cnt; coeff_idx++, coeff++) { double sum = 0.0; for (int samp_idx = 0; samp_idx < coeff_cnt; samp_idx++) { sum += resamp[samp_idx] * cos(M_PI * coeff_idx * (samp_idx + 0.5) / coeff_cnt); } (*coeff) = (normalizer * sum); } } // Compute the features of a given CharSamp bool FeatureChebyshev::ComputeFeatures(CharSamp *char_samp, float *features) { return ComputeChebyshevCoefficients(char_samp, features); } // Compute the Chebyshev coefficients of a given CharSamp bool FeatureChebyshev::ComputeChebyshevCoefficients(CharSamp *char_samp, float *features) { if (char_samp->NormBottom() <= 0) { return false; } unsigned char *raw_data = char_samp->RawData(); int stride = char_samp->Stride(); // compute the height of the word int word_hgt = (255 * (char_samp->Top() + char_samp->Height()) / char_samp->NormBottom()); // compute left & right profiles vector<float> left_profile(word_hgt, 0.0); vector<float> right_profile(word_hgt, 0.0); unsigned char *line_data = raw_data; for (int y = 0; y < char_samp->Height(); y++, line_data += stride) { int min_x = char_samp->Width(); int max_x = -1; for (int x = 0; x < char_samp->Width(); x++) { if (line_data[x] == 0) { UpdateRange(x, &min_x, &max_x); } } left_profile[char_samp->Top() + y] = 1.0 * (min_x == char_samp->Width() ? 0 : (min_x + 1)) / char_samp->Width(); right_profile[char_samp->Top() + y] = 1.0 * (max_x == -1 ? 0 : char_samp->Width() - max_x) / char_samp->Width(); } // compute top and bottom profiles vector<float> top_profile(char_samp->Width(), 0); vector<float> bottom_profile(char_samp->Width(), 0); for (int x = 0; x < char_samp->Width(); x++) { int min_y = word_hgt; int max_y = -1; line_data = raw_data; for (int y = 0; y < char_samp->Height(); y++, line_data += stride) { if (line_data[x] == 0) { UpdateRange(y + char_samp->Top(), &min_y, &max_y); } } top_profile[x] = 1.0 * (min_y == word_hgt ? 0 : (min_y + 1)) / word_hgt; bottom_profile[x] = 1.0 * (max_y == -1 ? 0 : (word_hgt - max_y)) / word_hgt; } // compute the chebyshev coefficients of each profile ChebyshevCoefficients(left_profile, kChebychevCoefficientCnt, features); ChebyshevCoefficients(top_profile, kChebychevCoefficientCnt, features + kChebychevCoefficientCnt); ChebyshevCoefficients(right_profile, kChebychevCoefficientCnt, features + (2 * kChebychevCoefficientCnt)); ChebyshevCoefficients(bottom_profile, kChebychevCoefficientCnt, features + (3 * kChebychevCoefficientCnt)); return true; } } // namespace tesseract
C++
/********************************************************************** * File: cube_line_object.cpp * Description: Implementation of the Cube Line Object 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 <algorithm> #include "cube_line_object.h" namespace tesseract { CubeLineObject::CubeLineObject(CubeRecoContext *cntxt, Pix *pix) { line_pix_ = pix; own_pix_ = false; processed_ = false; cntxt_ = cntxt; phrase_cnt_ = 0; phrases_ = NULL; } CubeLineObject::~CubeLineObject() { if (line_pix_ != NULL && own_pix_ == true) { pixDestroy(&line_pix_); line_pix_ = NULL; } if (phrases_ != NULL) { for (int phrase_idx = 0; phrase_idx < phrase_cnt_; phrase_idx++) { if (phrases_[phrase_idx] != NULL) { delete phrases_[phrase_idx]; } } delete []phrases_; phrases_ = NULL; } } // Recognize the specified pix as one line returning the recognized bool CubeLineObject::Process() { // do nothing if pix had already been processed if (processed_) { return true; } // validate data if (line_pix_ == NULL || cntxt_ == NULL) { return false; } // create a CharSamp CharSamp *char_samp = CubeUtils::CharSampleFromPix(line_pix_, 0, 0, line_pix_->w, line_pix_->h); if (char_samp == NULL) { return false; } // compute connected components. int con_comp_cnt = 0; ConComp **con_comps = char_samp->FindConComps(&con_comp_cnt, cntxt_->Params()->MinConCompSize()); // no longer need char_samp, delete it delete char_samp; // no connected components, bail out if (con_comp_cnt <= 0 || con_comps == NULL) { return false; } // sort connected components based on reading order bool rtl = (cntxt_->ReadingOrder() == tesseract::CubeRecoContext::R2L); qsort(con_comps, con_comp_cnt, sizeof(*con_comps), rtl ? ConComp::Right2LeftComparer : ConComp::Left2RightComparer); // compute work breaking threshold as a ratio of line height bool ret_val = false; int word_break_threshold = ComputeWordBreakThreshold(con_comp_cnt, con_comps, rtl); if (word_break_threshold > 0) { // over-allocate phrases object buffer phrases_ = new CubeObject *[con_comp_cnt]; if (phrases_ != NULL) { // create a phrase if the horizontal distance between two consecutive // concomps is higher than threshold int start_con_idx = 0; int current_phrase_limit = rtl ? con_comps[0]->Left() : con_comps[0]->Right(); for (int con_idx = 1; con_idx <= con_comp_cnt; con_idx++) { bool create_new_phrase = true; // if not at the end, compute the distance between two consecutive // concomps if (con_idx < con_comp_cnt) { int dist = 0; if (cntxt_->ReadingOrder() == tesseract::CubeRecoContext::R2L) { dist = current_phrase_limit - con_comps[con_idx]->Right(); } else { dist = con_comps[con_idx]->Left() - current_phrase_limit; } create_new_phrase = (dist > word_break_threshold); } // create a new phrase if (create_new_phrase) { // create a phrase corresponding to a range on components bool left_most; bool right_most; CharSamp *phrase_char_samp = CharSamp::FromConComps(con_comps, start_con_idx, con_idx - start_con_idx, NULL, &left_most, &right_most, line_pix_->h); if (phrase_char_samp == NULL) { break; } phrases_[phrase_cnt_] = new CubeObject(cntxt_, phrase_char_samp); if (phrases_[phrase_cnt_] == NULL) { delete phrase_char_samp; break; } // set the ownership of the charsamp to the cube object phrases_[phrase_cnt_]->SetCharSampOwnership(true); phrase_cnt_++; // advance the starting index to the current index start_con_idx = con_idx; // set the limit of the newly starting phrase (if any) if (con_idx < con_comp_cnt) { current_phrase_limit = rtl ? con_comps[con_idx]->Left() : con_comps[con_idx]->Right(); } } else { // update the limit of the current phrase if (cntxt_->ReadingOrder() == tesseract::CubeRecoContext::R2L) { current_phrase_limit = MIN(current_phrase_limit, con_comps[con_idx]->Left()); } else { current_phrase_limit = MAX(current_phrase_limit, con_comps[con_idx]->Right()); } } } ret_val = true; } } // clean-up connected comps for (int con_idx = 0; con_idx < con_comp_cnt; con_idx++) { delete con_comps[con_idx]; } delete []con_comps; // success processed_ = true; return ret_val; } // Compute the least word breaking threshold that is required to produce a // valid set of phrases. Phrases are validated using the Aspect ratio // constraints specified in the language specific Params object int CubeLineObject::ComputeWordBreakThreshold(int con_comp_cnt, ConComp **con_comps, bool rtl) { // initial estimate of word breaking threshold int word_break_threshold = static_cast<int>(line_pix_->h * cntxt_->Params()->MaxSpaceHeightRatio()); bool valid = false; // compute the resulting words and validate each's aspect ratio do { // group connected components into words based on breaking threshold int start_con_idx = 0; int current_phrase_limit = (rtl ? con_comps[0]->Left() : con_comps[0]->Right()); int min_x = con_comps[0]->Left(); int max_x = con_comps[0]->Right(); int min_y = con_comps[0]->Top(); int max_y = con_comps[0]->Bottom(); valid = true; for (int con_idx = 1; con_idx <= con_comp_cnt; con_idx++) { bool create_new_phrase = true; // if not at the end, compute the distance between two consecutive // concomps if (con_idx < con_comp_cnt) { int dist = 0; if (rtl) { dist = current_phrase_limit - con_comps[con_idx]->Right(); } else { dist = con_comps[con_idx]->Left() - current_phrase_limit; } create_new_phrase = (dist > word_break_threshold); } // create a new phrase if (create_new_phrase) { // check aspect ratio. Break if invalid if ((max_x - min_x + 1) > (cntxt_->Params()->MaxWordAspectRatio() * (max_y - min_y + 1))) { valid = false; break; } // advance the starting index to the current index start_con_idx = con_idx; // set the limit of the newly starting phrase (if any) if (con_idx < con_comp_cnt) { current_phrase_limit = rtl ? con_comps[con_idx]->Left() : con_comps[con_idx]->Right(); // re-init bounding box min_x = con_comps[con_idx]->Left(); max_x = con_comps[con_idx]->Right(); min_y = con_comps[con_idx]->Top(); max_y = con_comps[con_idx]->Bottom(); } } else { // update the limit of the current phrase if (rtl) { current_phrase_limit = MIN(current_phrase_limit, con_comps[con_idx]->Left()); } else { current_phrase_limit = MAX(current_phrase_limit, con_comps[con_idx]->Right()); } // update bounding box UpdateRange(con_comps[con_idx]->Left(), con_comps[con_idx]->Right(), &min_x, &max_x); UpdateRange(con_comps[con_idx]->Top(), con_comps[con_idx]->Bottom(), &min_y, &max_y); } } // return the breaking threshold if all broken word dimensions are valid if (valid) { return word_break_threshold; } // decrease the threshold and try again word_break_threshold--; } while (!valid && word_break_threshold > 0); // failed to find a threshold that acheives the target aspect ratio. // Just use the default threshold return static_cast<int>(line_pix_->h * cntxt_->Params()->MaxSpaceHeightRatio()); } }
C++
/********************************************************************** * File: cube_page_segmenter.cpp * Description: Implementation of the Cube Page Segmenter 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 "cube_line_segmenter.h" #include "ndminx.h" namespace tesseract { // constants that worked for Arabic page segmenter const int CubeLineSegmenter::kLineSepMorphMinHgt = 20; const int CubeLineSegmenter::kHgtBins = 20; const double CubeLineSegmenter::kMaxValidLineRatio = 3.2; const int CubeLineSegmenter::kMaxConnCompHgt = 150; const int CubeLineSegmenter::kMaxConnCompWid = 500; const int CubeLineSegmenter::kMaxHorzAspectRatio = 50; const int CubeLineSegmenter::kMaxVertAspectRatio = 20; const int CubeLineSegmenter::kMinWid = 2; const int CubeLineSegmenter::kMinHgt = 2; const float CubeLineSegmenter::kMinValidLineHgtRatio = 2.5; CubeLineSegmenter::CubeLineSegmenter(CubeRecoContext *cntxt, Pix *img) { cntxt_ = cntxt; orig_img_ = img; img_ = NULL; lines_pixa_ = NULL; init_ = false; line_cnt_ = 0; columns_ = NULL; con_comps_ = NULL; est_alef_hgt_ = 0.0; est_dot_hgt_ = 0.0; } CubeLineSegmenter::~CubeLineSegmenter() { if (img_ != NULL) { pixDestroy(&img_); img_ = NULL; } if (lines_pixa_ != NULL) { pixaDestroy(&lines_pixa_); lines_pixa_ = NULL; } if (con_comps_ != NULL) { pixaDestroy(&con_comps_); con_comps_ = NULL; } if (columns_ != NULL) { pixaaDestroy(&columns_); columns_ = NULL; } } // compute validity ratio for a line double CubeLineSegmenter::ValidityRatio(Pix *line_mask_pix, Box *line_box) { return line_box->h / est_alef_hgt_; } // validate line bool CubeLineSegmenter::ValidLine(Pix *line_mask_pix, Box *line_box) { double validity_ratio = ValidityRatio(line_mask_pix, line_box); return validity_ratio < kMaxValidLineRatio; } // perform a vertical Closing with the specified threshold // returning the resulting conn comps as a pixa Pixa *CubeLineSegmenter::VerticalClosing(Pix *pix, int threshold, Boxa **boxa) { char sequence_str[16]; // do the morphology sprintf(sequence_str, "c100.%d", threshold); Pix *morphed_pix = pixMorphCompSequence(pix, sequence_str, 0); if (morphed_pix == NULL) { return NULL; } // get the resulting lines by computing concomps Pixa *pixac; (*boxa) = pixConnComp(morphed_pix, &pixac, 8); pixDestroy(&morphed_pix); if ((*boxa) == NULL) { return NULL; } return pixac; } // Helper cleans up after CrackLine. static void CleanupCrackLine(int line_cnt, Pixa **lines_pixa, Boxa **line_con_comps, Pixa **line_con_comps_pix) { for (int line = 0; line < line_cnt; line++) { if (lines_pixa[line] != NULL) { pixaDestroy(&lines_pixa[line]); } } delete []lines_pixa; boxaDestroy(line_con_comps); pixaDestroy(line_con_comps_pix); } // do a desperate attempt at cracking lines Pixa *CubeLineSegmenter::CrackLine(Pix *cracked_line_pix, Box *cracked_line_box, int line_cnt) { // create lines pixa array Pixa **lines_pixa = new Pixa*[line_cnt]; if (lines_pixa == NULL) { return NULL; } memset(lines_pixa, 0, line_cnt * sizeof(*lines_pixa)); // compute line conn comps Pixa *line_con_comps_pix; Boxa *line_con_comps = ComputeLineConComps(cracked_line_pix, cracked_line_box, &line_con_comps_pix); if (line_con_comps == NULL) { delete []lines_pixa; return NULL; } // assign each conn comp to the a line based on its centroid for (int con = 0; con < line_con_comps->n; con++) { Box *con_box = line_con_comps->box[con]; Pix *con_pix = line_con_comps_pix->pix[con]; int mid_y = (con_box->y - cracked_line_box->y) + (con_box->h / 2), line_idx = MIN(line_cnt - 1, (mid_y * line_cnt / cracked_line_box->h)); // create the line if it has not been created? if (lines_pixa[line_idx] == NULL) { lines_pixa[line_idx] = pixaCreate(line_con_comps->n); if (lines_pixa[line_idx] == NULL) { CleanupCrackLine(line_cnt, lines_pixa, &line_con_comps, &line_con_comps_pix); return NULL; } } // add the concomp to the line if (pixaAddPix(lines_pixa[line_idx], con_pix, L_CLONE) != 0 || pixaAddBox(lines_pixa[line_idx], con_box, L_CLONE)) { CleanupCrackLine(line_cnt, lines_pixa, &line_con_comps, &line_con_comps_pix); return NULL; } } // create the lines pixa Pixa *lines = pixaCreate(line_cnt); bool success = true; // create and check the validity of the lines for (int line = 0; line < line_cnt; line++) { Pixa *line_pixa = lines_pixa[line]; // skip invalid lines if (line_pixa == NULL) { continue; } // merge the pix, check the validity of the line // and add it to the lines pixa Box *line_box; Pix *line_pix = Pixa2Pix(line_pixa, &line_box); if (line_pix == NULL || line_box == NULL || ValidLine(line_pix, line_box) == false || pixaAddPix(lines, line_pix, L_INSERT) != 0 || pixaAddBox(lines, line_box, L_INSERT) != 0) { if (line_pix != NULL) { pixDestroy(&line_pix); } if (line_box != NULL) { boxDestroy(&line_box); } success = false; break; } } // cleanup CleanupCrackLine(line_cnt, lines_pixa, &line_con_comps, &line_con_comps_pix); if (success == false) { pixaDestroy(&lines); lines = NULL; } return lines; } // do a desperate attempt at cracking lines Pixa *CubeLineSegmenter::CrackLine(Pix *cracked_line_pix, Box *cracked_line_box) { // estimate max line count int max_line_cnt = static_cast<int>((cracked_line_box->h / est_alef_hgt_) + 0.5); if (max_line_cnt < 2) { return NULL; } for (int line_cnt = 2; line_cnt < max_line_cnt; line_cnt++) { Pixa *lines = CrackLine(cracked_line_pix, cracked_line_box, line_cnt); if (lines != NULL) { return lines; } } return NULL; } // split a line continously until valid or fail Pixa *CubeLineSegmenter::SplitLine(Pix *line_mask_pix, Box *line_box) { // clone the line mask Pix *line_pix = pixClone(line_mask_pix); if (line_pix == NULL) { return NULL; } // AND with the image to get the actual line pixRasterop(line_pix, 0, 0, line_pix->w, line_pix->h, PIX_SRC & PIX_DST, img_, line_box->x, line_box->y); // continue to do rasterop morphology on the line until // it splits to valid lines or we fail int morph_hgt = kLineSepMorphMinHgt - 1, best_threshold = kLineSepMorphMinHgt - 1, max_valid_portion = 0; Boxa *boxa; Pixa *pixac; do { pixac = VerticalClosing(line_pix, morph_hgt, &boxa); // add the box offset to all the lines // and check for the validity of each int line, valid_line_cnt = 0, valid_portion = 0; for (line = 0; line < pixac->n; line++) { boxa->box[line]->x += line_box->x; boxa->box[line]->y += line_box->y; if (ValidLine(pixac->pix[line], boxa->box[line]) == true) { // count valid lines valid_line_cnt++; // and the valid portions valid_portion += boxa->box[line]->h; } } // all the lines are valid if (valid_line_cnt == pixac->n) { boxaDestroy(&boxa); pixDestroy(&line_pix); return pixac; } // a larger valid portion if (valid_portion > max_valid_portion) { max_valid_portion = valid_portion; best_threshold = morph_hgt; } boxaDestroy(&boxa); pixaDestroy(&pixac); morph_hgt--; } while (morph_hgt > 0); // failed to break into valid lines // attempt to crack the line pixac = CrackLine(line_pix, line_box); if (pixac != NULL) { pixDestroy(&line_pix); return pixac; } // try to leverage any of the lines // did the best threshold yield a non zero valid portion if (max_valid_portion > 0) { // use this threshold to break lines pixac = VerticalClosing(line_pix, best_threshold, &boxa); // add the box offset to all the lines // and check for the validity of each for (int line = 0; line < pixac->n; line++) { boxa->box[line]->x += line_box->x; boxa->box[line]->y += line_box->y; // remove invalid lines from the pixa if (ValidLine(pixac->pix[line], boxa->box[line]) == false) { pixaRemovePix(pixac, line); line--; } } boxaDestroy(&boxa); pixDestroy(&line_pix); return pixac; } // last resort: attempt to crack the line pixDestroy(&line_pix); return NULL; } // Checks of a line is too small bool CubeLineSegmenter::SmallLine(Box *line_box) { return line_box->h <= (kMinValidLineHgtRatio * est_dot_hgt_); } // Compute the connected components in a line Boxa * CubeLineSegmenter::ComputeLineConComps(Pix *line_mask_pix, Box *line_box, Pixa **con_comps_pixa) { // clone the line mask Pix *line_pix = pixClone(line_mask_pix); if (line_pix == NULL) { return NULL; } // AND with the image to get the actual line pixRasterop(line_pix, 0, 0, line_pix->w, line_pix->h, PIX_SRC & PIX_DST, img_, line_box->x, line_box->y); // compute the connected components of the line to be merged Boxa *line_con_comps = pixConnComp(line_pix, con_comps_pixa, 8); pixDestroy(&line_pix); // offset boxes by the bbox of the line for (int con = 0; con < line_con_comps->n; con++) { line_con_comps->box[con]->x += line_box->x; line_con_comps->box[con]->y += line_box->y; } return line_con_comps; } // create a union of two arbitrary pix Pix *CubeLineSegmenter::PixUnion(Pix *dest_pix, Box *dest_box, Pix *src_pix, Box *src_box) { // compute dimensions of union rect BOX *union_box = boxBoundingRegion(src_box, dest_box); // create the union pix Pix *union_pix = pixCreate(union_box->w, union_box->h, src_pix->d); if (union_pix == NULL) { return NULL; } // blt the src and dest pix pixRasterop(union_pix, src_box->x - union_box->x, src_box->y - union_box->y, src_box->w, src_box->h, PIX_SRC | PIX_DST, src_pix, 0, 0); pixRasterop(union_pix, dest_box->x - union_box->x, dest_box->y - union_box->y, dest_box->w, dest_box->h, PIX_SRC | PIX_DST, dest_pix, 0, 0); // replace the dest_box *dest_box = *union_box; boxDestroy(&union_box); return union_pix; } // create a union of a number of arbitrary pix Pix *CubeLineSegmenter::Pixa2Pix(Pixa *pixa, Box **dest_box, int start_pix, int pix_cnt) { // compute union_box int min_x = INT_MAX, max_x = INT_MIN, min_y = INT_MAX, max_y = INT_MIN; for (int pix_idx = start_pix; pix_idx < (start_pix + pix_cnt); pix_idx++) { Box *pix_box = pixa->boxa->box[pix_idx]; UpdateRange(pix_box->x, pix_box->x + pix_box->w, &min_x, &max_x); UpdateRange(pix_box->y, pix_box->y + pix_box->h, &min_y, &max_y); } (*dest_box) = boxCreate(min_x, min_y, max_x - min_x, max_y - min_y); if ((*dest_box) == NULL) { return NULL; } // create the union pix Pix *union_pix = pixCreate((*dest_box)->w, (*dest_box)->h, img_->d); if (union_pix == NULL) { boxDestroy(dest_box); return NULL; } // create a pix corresponding to the union of all pixs // blt the src and dest pix for (int pix_idx = start_pix; pix_idx < (start_pix + pix_cnt); pix_idx++) { Box *pix_box = pixa->boxa->box[pix_idx]; Pix *con_pix = pixa->pix[pix_idx]; pixRasterop(union_pix, pix_box->x - (*dest_box)->x, pix_box->y - (*dest_box)->y, pix_box->w, pix_box->h, PIX_SRC | PIX_DST, con_pix, 0, 0); } return union_pix; } // create a union of a number of arbitrary pix Pix *CubeLineSegmenter::Pixa2Pix(Pixa *pixa, Box **dest_box) { return Pixa2Pix(pixa, dest_box, 0, pixa->n); } // merges a number of lines into one line given a bounding box and a mask bool CubeLineSegmenter::MergeLine(Pix *line_mask_pix, Box *line_box, Pixa *lines, Boxaa *lines_con_comps) { // compute the connected components of the lines to be merged Pixa *small_con_comps_pix; Boxa *small_line_con_comps = ComputeLineConComps(line_mask_pix, line_box, &small_con_comps_pix); if (small_line_con_comps == NULL) { return false; } // for each connected component for (int con = 0; con < small_line_con_comps->n; con++) { Box *small_con_comp_box = small_line_con_comps->box[con]; int best_line = -1, best_dist = INT_MAX, small_box_right = small_con_comp_box->x + small_con_comp_box->w, small_box_bottom = small_con_comp_box->y + small_con_comp_box->h; // for each valid line for (int line = 0; line < lines->n; line++) { if (SmallLine(lines->boxa->box[line]) == true) { continue; } // for all the connected components in the line Boxa *line_con_comps = lines_con_comps->boxa[line]; for (int lcon = 0; lcon < line_con_comps->n; lcon++) { Box *con_comp_box = line_con_comps->box[lcon]; int xdist, ydist, box_right = con_comp_box->x + con_comp_box->w, box_bottom = con_comp_box->y + con_comp_box->h; xdist = MAX(small_con_comp_box->x, con_comp_box->x) - MIN(small_box_right, box_right); ydist = MAX(small_con_comp_box->y, con_comp_box->y) - MIN(small_box_bottom, box_bottom); // if there is an overlap in x-direction if (xdist <= 0) { if (best_line == -1 || ydist < best_dist) { best_dist = ydist; best_line = line; } } } } // if the distance is too big, do not merged if (best_line != -1 && best_dist < est_alef_hgt_) { // add the pix to the best line Pix *new_line = PixUnion(lines->pix[best_line], lines->boxa->box[best_line], small_con_comps_pix->pix[con], small_con_comp_box); if (new_line == NULL) { return false; } pixDestroy(&lines->pix[best_line]); lines->pix[best_line] = new_line; } } pixaDestroy(&small_con_comps_pix); boxaDestroy(&small_line_con_comps); return true; } // Creates new set of lines from the computed columns bool CubeLineSegmenter::AddLines(Pixa *lines) { // create an array that will hold the bounding boxes // of the concomps belonging to each line Boxaa *lines_con_comps = boxaaCreate(lines->n); if (lines_con_comps == NULL) { return false; } for (int line = 0; line < lines->n; line++) { // if the line is not valid if (ValidLine(lines->pix[line], lines->boxa->box[line]) == false) { // split it Pixa *split_lines = SplitLine(lines->pix[line], lines->boxa->box[line]); // remove the old line if (pixaRemovePix(lines, line) != 0) { return false; } line--; if (split_lines == NULL) { continue; } // add the split lines instead and move the pointer for (int s_line = 0; s_line < split_lines->n; s_line++) { Pix *sp_line = pixaGetPix(split_lines, s_line, L_CLONE); Box *sp_box = boxaGetBox(split_lines->boxa, s_line, L_CLONE); if (sp_line == NULL || sp_box == NULL) { return false; } // insert the new line if (pixaInsertPix(lines, ++line, sp_line, sp_box) != 0) { return false; } } // remove the split lines pixaDestroy(&split_lines); } } // compute the concomps bboxes of each line for (int line = 0; line < lines->n; line++) { Boxa *line_con_comps = ComputeLineConComps(lines->pix[line], lines->boxa->box[line], NULL); if (line_con_comps == NULL) { return false; } // insert it into the boxaa array if (boxaaAddBoxa(lines_con_comps, line_con_comps, L_INSERT) != 0) { return false; } } // post process the lines: // merge the contents of "small" lines info legitimate lines for (int line = 0; line < lines->n; line++) { // a small line detected if (SmallLine(lines->boxa->box[line]) == true) { // merge its components to one of the valid lines if (MergeLine(lines->pix[line], lines->boxa->box[line], lines, lines_con_comps) == true) { // remove the small line if (pixaRemovePix(lines, line) != 0) { return false; } if (boxaaRemoveBoxa(lines_con_comps, line) != 0) { return false; } line--; } } } boxaaDestroy(&lines_con_comps); // add the pix masks if (pixaaAddPixa(columns_, lines, L_INSERT) != 0) { return false; } return true; } // Index the specific pixa using RTL reading order int *CubeLineSegmenter::IndexRTL(Pixa *pixa) { int *pix_index = new int[pixa->n]; if (pix_index == NULL) { return NULL; } for (int pix = 0; pix < pixa->n; pix++) { pix_index[pix] = pix; } for (int ipix = 0; ipix < pixa->n; ipix++) { for (int jpix = ipix + 1; jpix < pixa->n; jpix++) { Box *ipix_box = pixa->boxa->box[pix_index[ipix]], *jpix_box = pixa->boxa->box[pix_index[jpix]]; // swap? if ((ipix_box->x + ipix_box->w) < (jpix_box->x + jpix_box->w)) { int temp = pix_index[ipix]; pix_index[ipix] = pix_index[jpix]; pix_index[jpix] = temp; } } } return pix_index; } // Performs line segmentation bool CubeLineSegmenter::LineSegment() { // Use full image morphology to find columns // This only works for simple layouts where each column // of text extends the full height of the input image. Pix *pix_temp1 = pixMorphCompSequence(img_, "c5.500", 0); if (pix_temp1 == NULL) { return false; } // Mask with a single component over each column Pixa *pixam; Boxa *boxa = pixConnComp(pix_temp1, &pixam, 8); if (boxa == NULL) { return false; } int init_morph_min_hgt = kLineSepMorphMinHgt; char sequence_str[16]; sprintf(sequence_str, "c100.%d", init_morph_min_hgt); // Use selective region-based morphology to get the textline mask. Pixa *pixad = pixaMorphSequenceByRegion(img_, pixam, sequence_str, 0, 0); if (pixad == NULL) { return false; } // for all columns int col_cnt = boxaGetCount(boxa); // create columns columns_ = pixaaCreate(col_cnt); if (columns_ == NULL) { return false; } // index columns based on readind order (RTL) int *col_order = IndexRTL(pixad); if (col_order == NULL) { return false; } line_cnt_ = 0; for (int col_idx = 0; col_idx < col_cnt; col_idx++) { int col = col_order[col_idx]; // get the pix and box corresponding to the column Pix *pixt3 = pixaGetPix(pixad, col, L_CLONE); if (pixt3 == NULL) { delete []col_order; return false; } Box *col_box = pixad->boxa->box[col]; Pixa *pixac; Boxa *boxa2 = pixConnComp(pixt3, &pixac, 8); if (boxa2 == NULL) { delete []col_order; return false; } // offset the boxes by the column box for (int line = 0; line < pixac->n; line++) { pixac->boxa->box[line]->x += col_box->x; pixac->boxa->box[line]->y += col_box->y; } // add the lines if (AddLines(pixac) == true) { if (pixaaAddBox(columns_, col_box, L_CLONE) != 0) { delete []col_order; return false; } } pixDestroy(&pixt3); boxaDestroy(&boxa2); line_cnt_ += columns_->pixa[col_idx]->n; } pixaDestroy(&pixam); pixaDestroy(&pixad); boxaDestroy(&boxa); delete []col_order; pixDestroy(&pix_temp1); return true; } // Estimate the paramters of the font(s) used in the page bool CubeLineSegmenter::EstimateFontParams() { int hgt_hist[kHgtBins]; int max_hgt; double mean_hgt; // init hgt histogram of concomps memset(hgt_hist, 0, sizeof(hgt_hist)); // compute max hgt max_hgt = 0; for (int con = 0; con < con_comps_->n; con++) { // skip conn comps that are too long or too wide if (con_comps_->boxa->box[con]->h > kMaxConnCompHgt || con_comps_->boxa->box[con]->w > kMaxConnCompWid) { continue; } max_hgt = MAX(max_hgt, con_comps_->boxa->box[con]->h); } if (max_hgt <= 0) { return false; } // init hgt histogram of concomps memset(hgt_hist, 0, sizeof(hgt_hist)); // compute histogram mean_hgt = 0.0; for (int con = 0; con < con_comps_->n; con++) { // skip conn comps that are too long or too wide if (con_comps_->boxa->box[con]->h > kMaxConnCompHgt || con_comps_->boxa->box[con]->w > kMaxConnCompWid) { continue; } int bin = static_cast<int>(kHgtBins * con_comps_->boxa->box[con]->h / max_hgt); bin = MIN(bin, kHgtBins - 1); hgt_hist[bin]++; mean_hgt += con_comps_->boxa->box[con]->h; } mean_hgt /= con_comps_->n; // find the top 2 bins int idx[kHgtBins]; for (int bin = 0; bin < kHgtBins; bin++) { idx[bin] = bin; } for (int ibin = 0; ibin < 2; ibin++) { for (int jbin = ibin + 1; jbin < kHgtBins; jbin++) { if (hgt_hist[idx[ibin]] < hgt_hist[idx[jbin]]) { int swap = idx[ibin]; idx[ibin] = idx[jbin]; idx[jbin] = swap; } } } // emperically, we found out that the 2 highest freq bins correspond // respectively to the dot and alef est_dot_hgt_ = (1.0 * (idx[0] + 1) * max_hgt / kHgtBins); est_alef_hgt_ = (1.0 * (idx[1] + 1) * max_hgt / kHgtBins); // as a sanity check the dot hgt must be significanly lower than alef if (est_alef_hgt_ < (est_dot_hgt_ * 2)) { // use max_hgt to estimate instead est_alef_hgt_ = mean_hgt * 1.5; est_dot_hgt_ = est_alef_hgt_ / 5.0; } est_alef_hgt_ = MAX(est_alef_hgt_, est_dot_hgt_ * 4.0); return true; } // clean up the image Pix *CubeLineSegmenter::CleanUp(Pix *orig_img) { // get rid of long horizontal lines Pix *pix_temp0 = pixMorphCompSequence(orig_img, "o300.2", 0); pixXor(pix_temp0, pix_temp0, orig_img); // get rid of long vertical lines Pix *pix_temp1 = pixMorphCompSequence(pix_temp0, "o2.300", 0); pixXor(pix_temp1, pix_temp1, pix_temp0); pixDestroy(&pix_temp0); // detect connected components Pixa *con_comps; Boxa *boxa = pixConnComp(pix_temp1, &con_comps, 8); if (boxa == NULL) { return NULL; } // detect and remove suspicious conn comps for (int con = 0; con < con_comps->n; con++) { Box *box = boxa->box[con]; // remove if suspc. conn comp if ((box->w > (box->h * kMaxHorzAspectRatio)) || (box->h > (box->w * kMaxVertAspectRatio)) || (box->w < kMinWid && box->h < kMinHgt)) { pixRasterop(pix_temp1, box->x, box->y, box->w, box->h, PIX_SRC ^ PIX_DST, con_comps->pix[con], 0, 0); } } pixaDestroy(&con_comps); boxaDestroy(&boxa); return pix_temp1; } // Init the page segmenter bool CubeLineSegmenter::Init() { if (init_ == true) { return true; } if (orig_img_ == NULL) { return false; } // call the internal line segmentation return FindLines(); } // return the pix mask and box of a specific line Pix *CubeLineSegmenter::Line(int line, Box **line_box) { if (init_ == false && Init() == false) { return NULL; } if (line < 0 || line >= line_cnt_) { return NULL; } (*line_box) = lines_pixa_->boxa->box[line]; return lines_pixa_->pix[line]; } // Implements a basic rudimentary layout analysis based on Leptonica // works OK for Arabic. For other languages, the function TesseractPageAnalysis // should be called instead. bool CubeLineSegmenter::FindLines() { // convert the image to gray scale if necessary Pix *gray_scale_img = NULL; if (orig_img_->d != 2 && orig_img_->d != 8) { gray_scale_img = pixConvertTo8(orig_img_, false); if (gray_scale_img == NULL) { return false; } } else { gray_scale_img = orig_img_; } // threshold image Pix *thresholded_img; thresholded_img = pixThresholdToBinary(gray_scale_img, 128); // free the gray scale image if necessary if (gray_scale_img != orig_img_) { pixDestroy(&gray_scale_img); } // bail-out if thresholding failed if (thresholded_img == NULL) { return false; } // deskew Pix *deskew_img = pixDeskew(thresholded_img, 2); if (deskew_img == NULL) { return false; } pixDestroy(&thresholded_img); img_ = CleanUp(deskew_img); pixDestroy(&deskew_img); if (img_ == NULL) { return false; } pixDestroy(&deskew_img); // compute connected components Boxa *boxa = pixConnComp(img_, &con_comps_, 8); if (boxa == NULL) { return false; } boxaDestroy(&boxa); // estimate dot and alef hgts if (EstimateFontParams() == false) { return false; } // perform line segmentation if (LineSegment() == false) { return false; } // success init_ = true; return true; } }
C++
/********************************************************************** * File: search_node.cpp * Description: Implementation of the Beam Search Node 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. * **********************************************************************/ #include "search_node.h" namespace tesseract { // The constructor updates the best paths and costs: // mean_char_reco_cost_ (returned by BestRecoCost()) is the mean // char_reco cost of the best_path, including this node. // best_path_reco_cost is the total char_reco_cost of the best_path, // but excludes the char_reco_cost of this node. // best_cost is the mean mixed cost, i.e., mean_char_reco_cost_ + // current language model cost, all weighted by the cube context's // RecoWgt parameter SearchNode::SearchNode(CubeRecoContext *cntxt, SearchNode *parent_node, int char_reco_cost, LangModEdge *edge, int col_idx) { // copy data members cntxt_ = cntxt; lang_mod_edge_ = edge; col_idx_ = col_idx; parent_node_ = parent_node; char_reco_cost_ = char_reco_cost; // the string of this node is the same as that of the language model edge str_ = (edge == NULL ? NULL : edge->EdgeString()); // compute best path total reco cost best_path_reco_cost_ = (parent_node_ == NULL) ? 0 : parent_node_->CharRecoCost() + parent_node_->BestPathRecoCost(); // update best path length best_path_len_ = (parent_node_ == NULL) ? 1 : parent_node_->BestPathLength() + 1; if (edge != NULL && edge->IsRoot() && parent_node_ != NULL) { best_path_len_++; } // compute best reco cost mean cost mean_char_reco_cost_ = static_cast<int>( (best_path_reco_cost_ + char_reco_cost_) / static_cast<double>(best_path_len_)); // get language model cost int lm_cost = LangModCost(lang_mod_edge_, parent_node_); // compute aggregate best cost best_cost_ = static_cast<int>(cntxt_->Params()->RecoWgt() * (best_path_reco_cost_ + char_reco_cost_) / static_cast<double>(best_path_len_) ) + lm_cost; } SearchNode::~SearchNode() { if (lang_mod_edge_ != NULL) { delete lang_mod_edge_; } } // update the parent_node node if provides a better (less) cost bool SearchNode::UpdateParent(SearchNode *new_parent, int new_reco_cost, LangModEdge *new_edge) { if (lang_mod_edge_ == NULL) { if (new_edge != NULL) { return false; } } else { // to update the parent_node, we have to have the same target // state and char if (new_edge == NULL || !lang_mod_edge_->IsIdentical(new_edge) || !SearchNode::IdenticalPath(parent_node_, new_parent)) { return false; } } // compute the path cost and combined cost of the new path int new_best_path_reco_cost; int new_cost; int new_best_path_len; new_best_path_reco_cost = (new_parent == NULL) ? 0 : new_parent->BestPathRecoCost() + new_parent->CharRecoCost(); new_best_path_len = (new_parent == NULL) ? 1 : new_parent->BestPathLength() + 1; // compute the new language model cost int new_lm_cost = LangModCost(new_edge, new_parent); new_cost = static_cast<int>(cntxt_->Params()->RecoWgt() * (new_best_path_reco_cost + new_reco_cost) / static_cast<double>(new_best_path_len) ) + new_lm_cost; // update if it is better (less) than the current one if (best_cost_ > new_cost) { parent_node_ = new_parent; char_reco_cost_ = new_reco_cost; best_path_reco_cost_ = new_best_path_reco_cost; best_path_len_ = new_best_path_len; mean_char_reco_cost_ = static_cast<int>( (best_path_reco_cost_ + char_reco_cost_) / static_cast<double>(best_path_len_)); best_cost_ = static_cast<int>(cntxt_->Params()->RecoWgt() * (best_path_reco_cost_ + char_reco_cost_) / static_cast<double>(best_path_len_) ) + new_lm_cost; return true; } return false; } char_32 *SearchNode::PathString() { SearchNode *node = this; // compute string length int len = 0; while (node != NULL) { if (node->str_ != NULL) { len += CubeUtils::StrLen(node->str_); } // if the edge is a root and does not have a NULL parent, account for space LangModEdge *lm_edge = node->LangModelEdge(); if (lm_edge != NULL && lm_edge->IsRoot() && node->ParentNode() != NULL) { len++; } node = node->parent_node_; } char_32 *char_ptr = new char_32[len + 1]; if (char_ptr == NULL) { return NULL; } int ch_idx = len; node = this; char_ptr[ch_idx--] = 0; while (node != NULL) { int str_len = ((node->str_ == NULL) ? 0 : CubeUtils::StrLen(node->str_)); while (str_len > 0) { char_ptr[ch_idx--] = node->str_[--str_len]; } // if the edge is a root and does not have a NULL parent, insert a space LangModEdge *lm_edge = node->LangModelEdge(); if (lm_edge != NULL && lm_edge->IsRoot() && node->ParentNode() != NULL) { char_ptr[ch_idx--] = (char_32)' '; } node = node->parent_node_; } return char_ptr; } // compares the path of two nodes and checks if its identical bool SearchNode::IdenticalPath(SearchNode *node1, SearchNode *node2) { if (node1 != NULL && node2 != NULL && node1->best_path_len_ != node2->best_path_len_) { return false; } // backtrack until either a root or a NULL edge is reached while (node1 != NULL && node2 != NULL) { if (node1->str_ != node2->str_) { return false; } // stop if either nodes is a root if (node1->LangModelEdge()->IsRoot() || node2->LangModelEdge()->IsRoot()) { break; } node1 = node1->parent_node_; node2 = node2->parent_node_; } return ((node1 == NULL && node2 == NULL) || (node1 != NULL && node1->LangModelEdge()->IsRoot() && node2 != NULL && node2->LangModelEdge()->IsRoot())); } // Computes the language model cost of a path int SearchNode::LangModCost(LangModEdge *current_lm_edge, SearchNode *parent_node) { int lm_cost = 0; int node_cnt = 0; do { // check if root bool is_root = ((current_lm_edge != NULL && current_lm_edge->IsRoot()) || parent_node == NULL); if (is_root) { node_cnt++; lm_cost += (current_lm_edge == NULL ? 0 : current_lm_edge->PathCost()); } // continue until we hit a null parent if (parent_node == NULL) { break; } // get the previous language model edge current_lm_edge = parent_node->LangModelEdge(); // back track parent_node = parent_node->ParentNode(); } while (true); return static_cast<int>(lm_cost / static_cast<double>(node_cnt)); } } // namespace tesseract
C++
/********************************************************************** * File: char_samp_enum.h * Description: Declaration of a Character Set 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 CharSet class encapsulates the list of 32-bit strings/characters that // Cube supports for a specific language. The char set is loaded from the // .unicharset file corresponding to a specific language // Each string has a corresponding int class-id that gets used throughout Cube // The class provides pass back and forth conversion between the class-id // and its corresponding 32-bit string. This is done using a hash table that // maps the string to the class id. #ifndef CHAR_SET_H #define CHAR_SET_H #include <string.h> #include <string> #include <algorithm> #include "string_32.h" #include "tessdatamanager.h" #include "unicharset.h" #include "cube_const.h" namespace tesseract { class CharSet { public: CharSet(); ~CharSet(); // Returns true if Cube is sharing Tesseract's unicharset. inline bool SharedUnicharset() { return (unicharset_map_ == NULL); } // Returns the class id corresponding to a 32-bit string. Returns -1 // if the string is not supported. This is done by hashing the // string and then looking up the string in the hash-bin if there // are collisions. inline int ClassID(const char_32 *str) const { int hash_val = Hash(str); if (hash_bin_size_[hash_val] == 0) return -1; for (int bin = 0; bin < hash_bin_size_[hash_val]; bin++) { if (class_strings_[hash_bins_[hash_val][bin]]->compare(str) == 0) return hash_bins_[hash_val][bin]; } return -1; } // Same as above but using a 32-bit char instead of a string inline int ClassID(char_32 ch) const { int hash_val = Hash(ch); if (hash_bin_size_[hash_val] == 0) return -1; for (int bin = 0; bin < hash_bin_size_[hash_val]; bin++) { if ((*class_strings_[hash_bins_[hash_val][bin]])[0] == ch && class_strings_[hash_bins_[hash_val][bin]]->length() == 1) { return hash_bins_[hash_val][bin]; } } return -1; } // Retrieve the unicharid in Tesseract's unicharset corresponding // to a 32-bit string. When Tesseract and Cube share the same // unicharset, this will just be the class id. inline int UnicharID(const char_32 *str) const { int class_id = ClassID(str); if (class_id == INVALID_UNICHAR_ID) return INVALID_UNICHAR_ID; int unichar_id; if (unicharset_map_) unichar_id = unicharset_map_[class_id]; else unichar_id = class_id; return unichar_id; } // Same as above but using a 32-bit char instead of a string inline int UnicharID(char_32 ch) const { int class_id = ClassID(ch); if (class_id == INVALID_UNICHAR_ID) return INVALID_UNICHAR_ID; int unichar_id; if (unicharset_map_) unichar_id = unicharset_map_[class_id]; else unichar_id = class_id; return unichar_id; } // Returns the 32-bit string corresponding to a class id inline const char_32 * ClassString(int class_id) const { if (class_id < 0 || class_id >= class_cnt_) { return NULL; } return reinterpret_cast<const char_32 *>(class_strings_[class_id]->c_str()); } // Returns the count of supported strings inline int ClassCount() const { return class_cnt_; } // Creates CharSet object by reading the unicharset from the // TessDatamanager, and mapping Cube's unicharset to Tesseract's if // they differ. static CharSet *Create(TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset); // Return the UNICHARSET cube is using for recognition internally -- // ClassId() returns unichar_id's in this unicharset. UNICHARSET *InternalUnicharset() { return unicharset_; } private: // Hash table configuration params. Determined emperically on // the supported languages so far (Eng, Ara, Hin). Might need to be // tuned for speed when more languages are supported static const int kHashBins = 3001; static const int kMaxHashSize = 16; // Using djb2 hashing function to hash a 32-bit string // introduced in http://www.cse.yorku.ca/~oz/hash.html static inline int Hash(const char_32 *str) { unsigned long hash = 5381; int c; while ((c = *str++)) hash = ((hash << 5) + hash) + c; return (hash%kHashBins); } // Same as above but for a single char static inline int Hash(char_32 ch) { char_32 b[2]; b[0] = ch; b[1] = 0; return Hash(b); } // Load the list of supported chars from the given data file // pointer. If tess_unicharset is non-NULL, mapping each Cube class // id to a tesseract unicharid. bool LoadSupportedCharList(FILE *fp, UNICHARSET *tess_unicharset); // class count int class_cnt_; // hash-bin sizes array int hash_bin_size_[kHashBins]; // hash bins int hash_bins_[kHashBins][kMaxHashSize]; // supported strings array string_32 **class_strings_; // map from class id to secondary (tesseract's) unicharset's ids int *unicharset_map_; // A unicharset which is filled in with a Tesseract-style UNICHARSET for // cube's data if our unicharset is different from tesseract's. UNICHARSET cube_unicharset_; // This points to either the tess_unicharset we're passed or cube_unicharset_, // depending upon whether we just have one unicharset or one for each // tesseract and cube, respectively. UNICHARSET *unicharset_; // has the char set been initialized flag bool init_; }; } #endif // CHAR_SET_H
C++
/********************************************************************** * File: conv_net_classifier.h * Description: Declaration of Convolutional-NeuralNet Character Classifier * 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 ConvNetCharClassifier inherits from the base classifier class: // "CharClassifierBase". It implements a Convolutional Neural Net classifier // instance of the base classifier. It uses the Tesseract Neural Net library // The Neural Net takes a scaled version of a bitmap and feeds it to a // Convolutional Neural Net as input and performs a FeedForward. Each output // of the net corresponds to class_id in the CharSet passed at construction // time. // Afterwards, the outputs of the Net are "folded" using the folding set // (if any) #ifndef CONV_NET_CLASSIFIER_H #define CONV_NET_CLASSIFIER_H #include <string> #include "char_samp.h" #include "char_altlist.h" #include "char_set.h" #include "feature_base.h" #include "classifier_base.h" #include "neural_net.h" #include "lang_model.h" #include "tuning_params.h" namespace tesseract { // Folding Ratio is the ratio of the max-activation of members of a folding // set that is used to compute the min-activation of the rest of the set static const float kFoldingRatio = 0.75; class ConvNetCharClassifier : public CharClassifier { public: ConvNetCharClassifier(CharSet *char_set, TuningParams *params, FeatureBase *feat_extract); virtual ~ConvNetCharClassifier(); // The main training function. Given a sample and a class ID the classifier // updates its parameters according to its learning algorithm. This function // is currently not implemented. TODO(ahmadab): implement end-2-end training virtual bool Train(CharSamp *char_samp, int ClassID); // A secondary function needed for training. Allows the trainer to set the // value of any train-time paramter. This function is currently not // implemented. TODO(ahmadab): implement end-2-end training virtual bool SetLearnParam(char *var_name, float val); // Externally sets the Neural Net used by the classifier. Used for training void SetNet(tesseract::NeuralNet *net); // Classifies an input charsamp and return a CharAltList object containing // the possible candidates and corresponding scores virtual CharAltList * Classify(CharSamp *char_samp); // Computes the cost of a specific charsamp being a character (versus a // non-character: part-of-a-character OR more-than-one-character) virtual int CharCost(CharSamp *char_samp); private: // Neural Net object used for classification tesseract::NeuralNet *char_net_; // data buffers used to hold Neural Net inputs and outputs float *net_input_; float *net_output_; // Init the classifier provided a data-path and a language string virtual bool Init(const string &data_file_path, const string &lang, LangModel *lang_mod); // Loads the NeuralNets needed for the classifier bool LoadNets(const string &data_file_path, const string &lang); // Loads the folding sets provided a data-path and a language string virtual bool LoadFoldingSets(const string &data_file_path, const string &lang, LangModel *lang_mod); // Folds the output of the NeuralNet using the loaded folding sets virtual void Fold(); // Scales the input char_samp and feeds it to the NeuralNet as input bool RunNets(CharSamp *char_samp); }; } #endif // CONV_NET_CLASSIFIER_H
C++
/////////////////////////////////////////////////////////////////////// // File: scrollview.cc // Description: ScrollView // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // #include <stdarg.h> #include <limits.h> #include <string.h> #include <map> #include <utility> #include <algorithm> #include <vector> #include <string> #include <cstring> #include <climits> // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "scrollview.h" #ifdef _MSC_VER #pragma warning(disable:4786) // Don't give stupid warnings for stl #pragma warning(disable:4018) // signed/unsigned warnings #pragma warning(disable:4530) // exception warnings #endif const int kSvPort = 8461; const int kMaxMsgSize = 4096; const int kMaxIntPairSize = 45; // Holds %d,%d, for upto 64 bit. #include "svutil.h" #include "allheaders.h" struct SVPolyLineBuffer { bool empty; // Independent indicator to allow SendMsg to call SendPolygon. std::vector<int> xcoords; std::vector<int> ycoords; }; // A map between the window IDs and their corresponding pointers. static std::map<int, ScrollView*> svmap; static SVMutex* svmap_mu; // A map of all semaphores waiting for a specific event on a specific window. static std::map<std::pair<ScrollView*, SVEventType>, std::pair<SVSemaphore*, SVEvent*> > waiting_for_events; static SVMutex* waiting_for_events_mu; SVEvent* SVEvent::copy() { SVEvent* any = new SVEvent; any->command_id = command_id; any->counter = counter; any->parameter = new char[strlen(parameter) + 1]; strncpy(any->parameter, parameter, strlen(parameter)); any->parameter[strlen(parameter)] = '\0'; any->type = type; any->x = x; any->y = y; any->x_size = x_size; any->y_size = y_size; any->window = window; return any; } #ifndef GRAPHICS_DISABLED /// This is the main loop which handles the ScrollView-logic from the server /// to the client. It basically loops through messages, parses them to events /// and distributes it to the waiting handlers. /// It is run from a different thread and synchronizes via SVSync. void* ScrollView::MessageReceiver(void* a) { int counter_event_id = 0; // ongoing counter char* message = NULL; // Wait until a new message appears in the input stream_. do { message = ScrollView::GetStream()->Receive(); } while (message == NULL); // This is the main loop which iterates until the server is dead (strlen = -1). // It basically parses for 3 different messagetypes and then distributes the // events accordingly. while (1) { // The new event we create. SVEvent* cur = new SVEvent; // The ID of the corresponding window. int window_id; int ev_type; int n; // Fill the new SVEvent properly. sscanf(message, "%d,%d,%d,%d,%d,%d,%d,%n", &window_id, &ev_type, &cur->x, &cur->y, &cur->x_size, &cur->y_size, &cur->command_id, &n); char* p = (message + n); svmap_mu->Lock(); cur->window = svmap[window_id]; if (cur->window != NULL) { cur->parameter = new char[strlen(p) + 1]; strncpy(cur->parameter, p, strlen(p) + 1); if (strlen(p) > 0) { // remove the last \n cur->parameter[strlen(p)] = '\0'; } cur->type = static_cast<SVEventType>(ev_type); // Correct selection coordinates so x,y is the min pt and size is +ve. if (cur->x_size > 0) cur->x -= cur->x_size; else cur->x_size = -cur->x_size; if (cur->y_size > 0) cur->y -= cur->y_size; else cur->y_size = -cur->y_size; // Returned y will be the bottom-left if y is reversed. if (cur->window->y_axis_is_reversed_) cur->y = cur->window->TranslateYCoordinate(cur->y + cur->y_size); cur->counter = counter_event_id; // Increase by 2 since we will also create an SVET_ANY event from cur, // which will have a counter_id of cur + 1 (and thus gets processed // after cur). counter_event_id += 2; // In case of an SVET_EXIT event, quit the whole application. if (ev_type == SVET_EXIT) { ScrollView::Exit(); } // Place two copies of it in the table for the window. cur->window->SetEvent(cur); // Check if any of the threads currently waiting want it. std::pair<ScrollView*, SVEventType> awaiting_list(cur->window, cur->type); std::pair<ScrollView*, SVEventType> awaiting_list_any(cur->window, SVET_ANY); std::pair<ScrollView*, SVEventType> awaiting_list_any_window((ScrollView*)0, SVET_ANY); waiting_for_events_mu->Lock(); if (waiting_for_events.count(awaiting_list) > 0) { waiting_for_events[awaiting_list].second = cur; waiting_for_events[awaiting_list].first->Signal(); } else if (waiting_for_events.count(awaiting_list_any) > 0) { waiting_for_events[awaiting_list_any].second = cur; waiting_for_events[awaiting_list_any].first->Signal(); } else if (waiting_for_events.count(awaiting_list_any_window) > 0) { waiting_for_events[awaiting_list_any_window].second = cur; waiting_for_events[awaiting_list_any_window].first->Signal(); } else { // No one wanted it, so delete it. delete cur; } waiting_for_events_mu->Unlock(); // Signal the corresponding semaphore twice (for both copies). ScrollView* sv = svmap[window_id]; if (sv != NULL) { sv->Signal(); sv->Signal(); } } else { delete cur; // Applied to no window. } svmap_mu->Unlock(); // Wait until a new message appears in the input stream_. do { message = ScrollView::GetStream()->Receive(); } while (message == NULL); } return 0; } // Table to implement the color index values in the old system. int table_colors[ScrollView::GREEN_YELLOW+1][4]= { {0, 0, 0, 0}, // NONE (transparent) {0, 0, 0, 255}, // BLACK. {255, 255, 255, 255}, // WHITE. {255, 0, 0, 255}, // RED. {255, 255, 0, 255}, // YELLOW. {0, 255, 0, 255}, // GREEN. {0, 255, 255, 255}, // CYAN. {0, 0, 255, 255}, // BLUE. {255, 0, 255, 255}, // MAGENTA. {0, 128, 255, 255}, // AQUAMARINE. {0, 0, 64, 255}, // DARK_SLATE_BLUE. {128, 128, 255, 255}, // LIGHT_BLUE. {64, 64, 255, 255}, // MEDIUM_BLUE. {0, 0, 32, 255}, // MIDNIGHT_BLUE. {0, 0, 128, 255}, // NAVY_BLUE. {192, 192, 255, 255}, // SKY_BLUE. {64, 64, 128, 255}, // SLATE_BLUE. {32, 32, 64, 255}, // STEEL_BLUE. {255, 128, 128, 255}, // CORAL. {128, 64, 0, 255}, // BROWN. {128, 128, 0, 255}, // SANDY_BROWN. {192, 192, 0, 255}, // GOLD. {192, 192, 128, 255}, // GOLDENROD. {0, 64, 0, 255}, // DARK_GREEN. {32, 64, 0, 255}, // DARK_OLIVE_GREEN. {64, 128, 0, 255}, // FOREST_GREEN. {128, 255, 0, 255}, // LIME_GREEN. {192, 255, 192, 255}, // PALE_GREEN. {192, 255, 0, 255}, // YELLOW_GREEN. {192, 192, 192, 255}, // LIGHT_GREY. {64, 64, 128, 255}, // DARK_SLATE_GREY. {64, 64, 64, 255}, // DIM_GREY. {128, 128, 128, 255}, // GREY. {64, 192, 0, 255}, // KHAKI. {255, 0, 192, 255}, // MAROON. {255, 128, 0, 255}, // ORANGE. {255, 128, 64, 255}, // ORCHID. {255, 192, 192, 255}, // PINK. {128, 0, 128, 255}, // PLUM. {255, 0, 64, 255}, // INDIAN_RED. {255, 64, 0, 255}, // ORANGE_RED. {255, 0, 192, 255}, // VIOLET_RED. {255, 192, 128, 255}, // SALMON. {128, 128, 0, 255}, // TAN. {0, 255, 255, 255}, // TURQUOISE. {0, 128, 128, 255}, // DARK_TURQUOISE. {192, 0, 255, 255}, // VIOLET. {128, 128, 0, 255}, // WHEAT. {128, 255, 0, 255} // GREEN_YELLOW }; /******************************************************************************* * Scrollview implementation. *******************************************************************************/ SVNetwork* ScrollView::stream_ = NULL; int ScrollView::nr_created_windows_ = 0; int ScrollView::image_index_ = 0; /// Calls Initialize with all arguments given. ScrollView::ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed, const char* server_name) { Initialize(name, x_pos, y_pos, x_size, y_size, x_canvas_size, y_canvas_size, y_axis_reversed, server_name);} /// Calls Initialize with default argument for server_name_. ScrollView::ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed) { Initialize(name, x_pos, y_pos, x_size, y_size, x_canvas_size, y_canvas_size, y_axis_reversed, "localhost"); } /// Calls Initialize with default argument for server_name_ & y_axis_reversed. ScrollView::ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size) { Initialize(name, x_pos, y_pos, x_size, y_size, x_canvas_size, y_canvas_size, false, "localhost"); } /// Sets up a ScrollView window, depending on the constructor variables. void ScrollView::Initialize(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed, const char* server_name) { // If this is the first ScrollView Window which gets created, there is no // network connection yet and we have to set it up in a different thread. if (stream_ == NULL) { nr_created_windows_ = 0; stream_ = new SVNetwork(server_name, kSvPort); waiting_for_events_mu = new SVMutex(); svmap_mu = new SVMutex(); SendRawMessage( "svmain = luajava.bindClass('com.google.scrollview.ScrollView')\n"); SVSync::StartThread(MessageReceiver, NULL); } // Set up the variables on the clientside. nr_created_windows_++; event_handler_ = NULL; event_handler_ended_ = false; y_axis_is_reversed_ = y_axis_reversed; y_size_ = y_canvas_size; window_name_ = name; window_id_ = nr_created_windows_; // Set up polygon buffering. points_ = new SVPolyLineBuffer; points_->empty = true; svmap_mu->Lock(); svmap[window_id_] = this; svmap_mu->Unlock(); for (int i = 0; i < SVET_COUNT; i++) { event_table_[i] = NULL; } mutex_ = new SVMutex(); semaphore_ = new SVSemaphore(); // Set up an actual Window on the client side. char message[kMaxMsgSize]; snprintf(message, sizeof(message), "w%u = luajava.newInstance('com.google.scrollview.ui" ".SVWindow','%s',%u,%u,%u,%u,%u,%u,%u)\n", window_id_, window_name_, window_id_, x_pos, y_pos, x_size, y_size, x_canvas_size, y_canvas_size); SendRawMessage(message); SVSync::StartThread(StartEventHandler, this); } /// Sits and waits for events on this window. void* ScrollView::StartEventHandler(void* a) { ScrollView* sv = reinterpret_cast<ScrollView*>(a); SVEvent* new_event; do { stream_->Flush(); sv->semaphore_->Wait(); new_event = NULL; int serial = -1; int k = -1; sv->mutex_->Lock(); // Check every table entry if he is is valid and not already processed. for (int i = 0; i < SVET_COUNT; i++) { if (sv->event_table_[i] != NULL && (serial < 0 || sv->event_table_[i]->counter < serial)) { new_event = sv->event_table_[i]; serial = sv->event_table_[i]->counter; k = i; } } // If we didnt find anything we had an old alarm and just sleep again. if (new_event != NULL) { sv->event_table_[k] = NULL; sv->mutex_->Unlock(); if (sv->event_handler_ != NULL) { sv->event_handler_->Notify(new_event); } if (new_event->type == SVET_DESTROY) { // Signal the destructor that it is safe to terminate. sv->event_handler_ended_ = true; sv = NULL; } delete new_event; // Delete the pointer after it has been processed. } else { sv->mutex_->Unlock(); } // The thread should run as long as its associated window is alive. } while (sv != NULL); return 0; } #endif // GRAPHICS_DISABLED ScrollView::~ScrollView() { #ifndef GRAPHICS_DISABLED svmap_mu->Lock(); if (svmap[window_id_] != NULL) { svmap_mu->Unlock(); // So the event handling thread can quit. SendMsg("destroy()"); SVEvent* sve = AwaitEvent(SVET_DESTROY); delete sve; svmap_mu->Lock(); svmap[window_id_] = NULL; svmap_mu->Unlock(); // The event handler thread for this window *must* receive the // destroy event and set its pointer to this to NULL before we allow // the destructor to exit. while (!event_handler_ended_) Update(); } else { svmap_mu->Unlock(); } delete mutex_; delete semaphore_; delete points_; for (int i = 0; i < SVET_COUNT; i++) { delete event_table_[i]; } #endif // GRAPHICS_DISABLED } #ifndef GRAPHICS_DISABLED /// Send a message to the server, attaching the window id. void ScrollView::SendMsg(const char* format, ...) { if (!points_->empty) SendPolygon(); va_list args; char message[kMaxMsgSize]; va_start(args, format); // variable list vsnprintf(message, kMaxMsgSize, format, args); va_end(args); char form[kMaxMsgSize]; snprintf(form, kMaxMsgSize, "w%u:%s\n", window_id_, message); stream_->Send(form); } /// Send a message to the server without a /// window id. Used for global events like exit(). void ScrollView::SendRawMessage(const char* msg) { stream_->Send(msg); } /// Add an Event Listener to this ScrollView Window void ScrollView::AddEventHandler(SVEventHandler* listener) { event_handler_ = listener; } void ScrollView::Signal() { semaphore_->Signal(); } void ScrollView::SetEvent(SVEvent* svevent) { // Copy event SVEvent* any = svevent->copy(); SVEvent* specific = svevent->copy(); any->counter = specific->counter + 1; // Place both events into the queue. mutex_->Lock(); // Delete the old objects.. if (event_table_[specific->type] != NULL) { delete event_table_[specific->type]; } if (event_table_[SVET_ANY] != NULL) { delete event_table_[SVET_ANY]; } // ...and put the new ones in the table. event_table_[specific->type] = specific; event_table_[SVET_ANY] = any; mutex_->Unlock(); } /// Block until an event of the given type is received. /// Note: The calling function is responsible for deleting the returned /// SVEvent afterwards! SVEvent* ScrollView::AwaitEvent(SVEventType type) { // Initialize the waiting semaphore. SVSemaphore* sem = new SVSemaphore(); std::pair<ScrollView*, SVEventType> ea(this, type); waiting_for_events_mu->Lock(); waiting_for_events[ea] = std::pair<SVSemaphore*, SVEvent*> (sem, (SVEvent*)0); waiting_for_events_mu->Unlock(); // Wait on it, but first flush. stream_->Flush(); sem->Wait(); // Process the event we got woken up for (its in waiting_for_events pair). waiting_for_events_mu->Lock(); SVEvent* ret = waiting_for_events[ea].second; waiting_for_events.erase(ea); delete sem; waiting_for_events_mu->Unlock(); return ret; } // Block until any event on any window is received. // No event is returned here! SVEvent* ScrollView::AwaitEventAnyWindow() { // Initialize the waiting semaphore. SVSemaphore* sem = new SVSemaphore(); std::pair<ScrollView*, SVEventType> ea((ScrollView*)0, SVET_ANY); waiting_for_events_mu->Lock(); waiting_for_events[ea] = std::pair<SVSemaphore*, SVEvent*> (sem, (SVEvent*)0); waiting_for_events_mu->Unlock(); // Wait on it. stream_->Flush(); sem->Wait(); // Process the event we got woken up for (its in waiting_for_events pair). waiting_for_events_mu->Lock(); SVEvent* ret = waiting_for_events[ea].second; waiting_for_events.erase(ea); waiting_for_events_mu->Unlock(); return ret; } // Send the current buffered polygon (if any) and clear it. void ScrollView::SendPolygon() { if (!points_->empty) { points_->empty = true; // Allows us to use SendMsg. int length = points_->xcoords.size(); // length == 1 corresponds to 2 SetCursors in a row and only the // last setCursor has any effect. if (length == 2) { // An isolated line! SendMsg("drawLine(%d,%d,%d,%d)", points_->xcoords[0], points_->ycoords[0], points_->xcoords[1], points_->ycoords[1]); } else if (length > 2) { // A polyline. SendMsg("createPolyline(%d)", length); char coordpair[kMaxIntPairSize]; std::string decimal_coords; for (int i = 0; i < length; ++i) { snprintf(coordpair, kMaxIntPairSize, "%d,%d,", points_->xcoords[i], points_->ycoords[i]); decimal_coords += coordpair; } decimal_coords += '\n'; SendRawMessage(decimal_coords.c_str()); SendMsg("drawPolyline()"); } points_->xcoords.clear(); points_->ycoords.clear(); } } /******************************************************************************* * LUA "API" functions. *******************************************************************************/ // Sets the position from which to draw to (x,y). void ScrollView::SetCursor(int x, int y) { SendPolygon(); DrawTo(x, y); } // Draws from the current position to (x,y) and sets the new position to it. void ScrollView::DrawTo(int x, int y) { points_->xcoords.push_back(x); points_->ycoords.push_back(TranslateYCoordinate(y)); points_->empty = false; } // Draw a line using the current pen color. void ScrollView::Line(int x1, int y1, int x2, int y2) { if (!points_->xcoords.empty() && x1 == points_->xcoords.back() && TranslateYCoordinate(y1) == points_->ycoords.back()) { // We are already at x1, y1, so just draw to x2, y2. DrawTo(x2, y2); } else if (!points_->xcoords.empty() && x2 == points_->xcoords.back() && TranslateYCoordinate(y2) == points_->ycoords.back()) { // We are already at x2, y2, so just draw to x1, y1. DrawTo(x1, y1); } else { // This is a new line. SetCursor(x1, y1); DrawTo(x2, y2); } } // Set the visibility of the window. void ScrollView::SetVisible(bool visible) { if (visible) { SendMsg("setVisible(true)"); } else { SendMsg("setVisible(false)"); } } // Set the alwaysOnTop flag. void ScrollView::AlwaysOnTop(bool b) { if (b) { SendMsg("setAlwaysOnTop(true)"); } else { SendMsg("setAlwaysOnTop(false)"); } } // Adds a message entry to the message box. void ScrollView::AddMessage(const char* format, ...) { va_list args; char message[kMaxMsgSize]; char form[kMaxMsgSize]; va_start(args, format); // variable list vsnprintf(message, kMaxMsgSize, format, args); va_end(args); snprintf(form, kMaxMsgSize, "w%u:%s", window_id_, message); char* esc = AddEscapeChars(form); SendMsg("addMessage(\"%s\")", esc); delete[] esc; } // Set a messagebox. void ScrollView::AddMessageBox() { SendMsg("addMessageBox()"); } // Exit the client completely (and notify the server of it). void ScrollView::Exit() { SendRawMessage("svmain:exit()"); exit(0); } // Clear the canvas. void ScrollView::Clear() { SendMsg("clear()"); } // Set the stroke width. void ScrollView::Stroke(float width) { SendMsg("setStrokeWidth(%f)", width); } // Draw a rectangle using the current pen color. // The rectangle is filled with the current brush color. void ScrollView::Rectangle(int x1, int y1, int x2, int y2) { if (x1 == x2 && y1 == y2) return; // Scrollviewer locks up. SendMsg("drawRectangle(%d,%d,%d,%d)", x1, TranslateYCoordinate(y1), x2, TranslateYCoordinate(y2)); } // Draw an ellipse using the current pen color. // The ellipse is filled with the current brush color. void ScrollView::Ellipse(int x1, int y1, int width, int height) { SendMsg("drawEllipse(%d,%d,%u,%u)", x1, TranslateYCoordinate(y1), width, height); } // Set the pen color to the given RGB values. void ScrollView::Pen(int red, int green, int blue) { SendMsg("pen(%d,%d,%d)", red, green, blue); } // Set the pen color to the given RGB values. void ScrollView::Pen(int red, int green, int blue, int alpha) { SendMsg("pen(%d,%d,%d,%d)", red, green, blue, alpha); } // Set the brush color to the given RGB values. void ScrollView::Brush(int red, int green, int blue) { SendMsg("brush(%d,%d,%d)", red, green, blue); } // Set the brush color to the given RGB values. void ScrollView::Brush(int red, int green, int blue, int alpha) { SendMsg("brush(%d,%d,%d,%d)", red, green, blue, alpha); } // Set the attributes for future Text(..) calls. void ScrollView::TextAttributes(const char* font, int pixel_size, bool bold, bool italic, bool underlined) { const char* b; const char* i; const char* u; if (bold) { b = "true"; } else { b = "false"; } if (italic) { i = "true"; } else { i = "false"; } if (underlined) { u = "true"; } else { u = "false"; } SendMsg("textAttributes('%s',%u,%s,%s,%s)", font, pixel_size, b, i, u); } // Draw text at the given coordinates. void ScrollView::Text(int x, int y, const char* mystring) { SendMsg("drawText(%d,%d,'%s')", x, TranslateYCoordinate(y), mystring); } // Open and draw an image given a name at (x,y). void ScrollView::Image(const char* image, int x_pos, int y_pos) { SendMsg("openImage('%s')", image); SendMsg("drawImage('%s',%d,%d)", image, x_pos, TranslateYCoordinate(y_pos)); } // Add new checkboxmenuentry to menubar. void ScrollView::MenuItem(const char* parent, const char* name, int cmdEvent, bool flag) { if (parent == NULL) { parent = ""; } if (flag) { SendMsg("addMenuBarItem('%s','%s',%d,true)", parent, name, cmdEvent); } else { SendMsg("addMenuBarItem('%s','%s',%d,false)", parent, name, cmdEvent); } } // Add new menuentry to menubar. void ScrollView::MenuItem(const char* parent, const char* name, int cmdEvent) { if (parent == NULL) { parent = ""; } SendMsg("addMenuBarItem('%s','%s',%d)", parent, name, cmdEvent); } // Add new submenu to menubar. void ScrollView::MenuItem(const char* parent, const char* name) { if (parent == NULL) { parent = ""; } SendMsg("addMenuBarItem('%s','%s')", parent, name); } // Add new submenu to popupmenu. void ScrollView::PopupItem(const char* parent, const char* name) { if (parent == NULL) { parent = ""; } SendMsg("addPopupMenuItem('%s','%s')", parent, name); } // Add new submenuentry to popupmenu. void ScrollView::PopupItem(const char* parent, const char* name, int cmdEvent, const char* value, const char* desc) { if (parent == NULL) { parent = ""; } char* esc = AddEscapeChars(value); char* esc2 = AddEscapeChars(desc); SendMsg("addPopupMenuItem('%s','%s',%d,'%s','%s')", parent, name, cmdEvent, esc, esc2); delete[] esc; delete[] esc2; } // Send an update message for a single window. void ScrollView::UpdateWindow() { SendMsg("update()"); } // Note: this is an update to all windows void ScrollView::Update() { svmap_mu->Lock(); for (std::map<int, ScrollView*>::iterator iter = svmap.begin(); iter != svmap.end(); ++iter) { if (iter->second != NULL) iter->second->UpdateWindow(); } svmap_mu->Unlock(); } // Set the pen color, using an enum value (e.g. ScrollView::ORANGE) void ScrollView::Pen(Color color) { Pen(table_colors[color][0], table_colors[color][1], table_colors[color][2], table_colors[color][3]); } // Set the brush color, using an enum value (e.g. ScrollView::ORANGE) void ScrollView::Brush(Color color) { Brush(table_colors[color][0], table_colors[color][1], table_colors[color][2], table_colors[color][3]); } // Shows a modal Input Dialog which can return any kind of String char* ScrollView::ShowInputDialog(const char* msg) { SendMsg("showInputDialog(\"%s\")", msg); SVEvent* ev; // wait till an input event (all others are thrown away) ev = AwaitEvent(SVET_INPUT); char* p = new char[strlen(ev->parameter) + 1]; strncpy(p, ev->parameter, strlen(ev->parameter)); p[strlen(ev->parameter)] = '\0'; delete ev; return p; } // Shows a modal Yes/No Dialog which will return 'y' or 'n' int ScrollView::ShowYesNoDialog(const char* msg) { SendMsg("showYesNoDialog(\"%s\")", msg); SVEvent* ev; // Wait till an input event (all others are thrown away) ev = AwaitEvent(SVET_INPUT); int a = ev->parameter[0]; delete ev; return a; } // Zoom the window to the rectangle given upper left corner and // lower right corner. void ScrollView::ZoomToRectangle(int x1, int y1, int x2, int y2) { y1 = TranslateYCoordinate(y1); y2 = TranslateYCoordinate(y2); SendMsg("zoomRectangle(%d,%d,%d,%d)", MIN(x1, x2), MIN(y1, y2), MAX(x1, x2), MAX(y1, y2)); } // Send an image of type Pix. void ScrollView::Image(struct Pix* image, int x_pos, int y_pos) { l_uint8* data; size_t size; pixWriteMem(&data, &size, image, IFF_PNG); int base64_len = (size + 2) / 3 * 4; y_pos = TranslateYCoordinate(y_pos); SendMsg("readImage(%d,%d,%d)", x_pos, y_pos, base64_len); // Base64 encode the data. const char kBase64Table[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; char* base64 = new char[base64_len + 1]; memset(base64, '=', base64_len); base64[base64_len] = '\0'; int remainder = 0; int bits_left = 0; int code_len = 0; for (int i = 0; i < size; ++i) { int code = (data[i] >> (bits_left + 2)) | remainder; base64[code_len++] = kBase64Table[code & 63]; bits_left += 2; remainder = data[i] << (6 - bits_left); if (bits_left == 6) { base64[code_len++] = kBase64Table[remainder & 63]; bits_left = 0; remainder = 0; } } if (bits_left > 0) base64[code_len++] = kBase64Table[remainder & 63]; SendRawMessage(base64); delete [] base64; free(data); } // Escapes the ' character with a \, so it can be processed by LUA. // Note: The caller will have to make sure he deletes the newly allocated item. char* ScrollView::AddEscapeChars(const char* input) { const char* nextptr = strchr(input, '\''); const char* lastptr = input; char* message = new char[kMaxMsgSize]; int pos = 0; while (nextptr != NULL) { strncpy(message+pos, lastptr, nextptr-lastptr); pos += nextptr - lastptr; message[pos] = '\\'; pos += 1; lastptr = nextptr; nextptr = strchr(nextptr+1, '\''); } strncpy(message+pos, lastptr, strlen(lastptr)); message[pos+strlen(lastptr)] = '\0'; return message; } // Inverse the Y axis if the coordinates are actually inversed. int ScrollView::TranslateYCoordinate(int y) { if (!y_axis_is_reversed_) { return y; } else { return y_size_ - y; } } #endif // GRAPHICS_DISABLED
C++
/////////////////////////////////////////////////////////////////////// // File: svmnode.cpp // description_: ScrollView Menu Node // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // // A SVMenuNode is an entity which contains the mapping from a menu entry on // the server side to the corresponding associated commands on the client. // It is designed to be a tree structure with a root node, which can then be // used to generate the appropriate messages to the server to display the // menu structure there. // A SVMenuNode can both be used in the context_ of popup menus as well as // menu bars. #include <string.h> #include <iostream> #include <cstring> #include "svmnode.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #ifndef GRAPHICS_DISABLED #include "scrollview.h" // Create the empty root menu node. with just a caption. All other nodes should // be added to this or one of the submenus. SVMenuNode::SVMenuNode() { cmd_event_ = -1; child_ = NULL; next_ = NULL; parent_ = NULL; toggle_value_ = false; is_check_box_entry_ = false; } SVMenuNode::~SVMenuNode() { } // Create a new sub menu node with just a caption. This is used to create // nodes which act as parent nodes to other nodes (e.g. submenus). SVMenuNode* SVMenuNode::AddChild(const char* txt) { SVMenuNode* s = new SVMenuNode(-1, txt, false, false, NULL, NULL); this->AddChild(s); return s; } // Create a "normal" menu node which is associated with a command event. void SVMenuNode::AddChild(const char* txt, int command_event) { this->AddChild(new SVMenuNode(command_event, txt, false, false, NULL, NULL)); } // Create a menu node with an associated value (which might be changed // through the gui). void SVMenuNode::AddChild(const char* txt, int command_event, const char* val) { this->AddChild(new SVMenuNode(command_event, txt, false, false, val, NULL)); } // Create a menu node with an associated value and description_. void SVMenuNode::AddChild(const char* txt, int command_event, const char* val, const char* desc) { this->AddChild(new SVMenuNode(command_event, txt, false, false, val, desc)); } // Create a flag menu node. void SVMenuNode::AddChild(const char* txt, int command_event, int tv) { this->AddChild(new SVMenuNode(command_event, txt, tv, true, NULL, NULL)); } // Convenience function called from the different constructors to initialize // the different values of the menu node. SVMenuNode::SVMenuNode(int command_event, const char* txt, int tv, bool check_box_entry, const char* val, const char* desc) : text_(txt), value_(val), description_(desc) { cmd_event_ = command_event; child_ = NULL; next_ = NULL; parent_ = NULL; toggle_value_ = tv != 0; is_check_box_entry_ = check_box_entry; } // Add a child node to this menu node. void SVMenuNode::AddChild(SVMenuNode* svmn) { svmn->parent_ = this; // No children yet. if (child_ == NULL) { child_ = svmn; } else { SVMenuNode* cur = child_; while (cur->next_ != NULL) { cur = cur->next_; } cur->next_ = svmn; } } // Build a menu structure for the server and send the necessary messages. // Should be called on the root node. If menu_bar is true, a menu_bar menu // is built (e.g. on top of the window), if it is false a popup menu is // built which gets shown by right clicking on the window. // Deletes itself afterwards. void SVMenuNode::BuildMenu(ScrollView* sv, bool menu_bar) { if ((parent_ != NULL) && (menu_bar)) { if (is_check_box_entry_) { sv->MenuItem(parent_->text_.string(), text_.string(), cmd_event_, toggle_value_); } else { sv->MenuItem(parent_->text_.string(), text_.string(), cmd_event_); } } else if ((parent_ != NULL) && (!menu_bar)) { if (description_.length() > 0) { sv->PopupItem(parent_->text_.string(), text_.string(), cmd_event_, value_.string(), description_.string()); } else { sv->PopupItem(parent_->text_.string(), text_.string()); } } if (child_ != NULL) { child_->BuildMenu(sv, menu_bar); delete child_; } if (next_ != NULL) { next_->BuildMenu(sv, menu_bar); delete next_; } } #endif // GRAPHICS_DISABLED
C++
/////////////////////////////////////////////////////////////////////// // File: svutil.h // Description: ScrollView Utilities // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // // SVUtil contains the SVSync, SVSemaphore, SVMutex and SVNetwork // classes, which are used for thread/process creation & synchronization // and network connection. #ifndef TESSERACT_VIEWER_SVUTIL_H__ #define TESSERACT_VIEWER_SVUTIL_H__ #ifdef _WIN32 #ifndef __GNUC__ #include <windows.h> #define snprintf _snprintf #if (_MSC_VER <= 1400) #define vsnprintf _vsnprintf #endif #pragma warning(disable:4786) #else #include "platform.h" #include <windows.h> #endif #else #include <pthread.h> #include <semaphore.h> #endif #include <string> #ifndef MAX #define MAX(a, b) ((a > b) ? a : b) #endif #ifndef MIN #define MIN(a, b) ((a < b) ? a : b) #endif /// The SVSync class provides functionality for Thread & Process Creation class SVSync { public: /// Create new thread. static void StartThread(void *(*func)(void*), void* arg); /// Signals a thread to exit. static void ExitThread(); /// Starts a new process. static void StartProcess(const char* executable, const char* args); }; /// A semaphore class which encapsulates the main signalling /// and wait abilities of semaphores for windows and unix. class SVSemaphore { public: /// Sets up a semaphore. SVSemaphore(); /// Signal a semaphore. void Signal(); /// Wait on a semaphore. void Wait(); private: #ifdef _WIN32 HANDLE semaphore_; #elif defined(__APPLE__) sem_t *semaphore_; #else sem_t semaphore_; #endif }; /// A mutex which encapsulates the main locking and unlocking /// abilites of mutexes for windows and unix. class SVMutex { public: /// Sets up a new mutex. SVMutex(); /// Locks on a mutex. void Lock(); /// Unlocks on a mutex. void Unlock(); private: #ifdef _WIN32 HANDLE mutex_; #else pthread_mutex_t mutex_; #endif }; /// The SVNetwork class takes care of the remote connection for ScrollView /// This means setting up and maintaining a remote connection, sending and /// receiving messages and closing the connection. /// It is designed to work on both Linux and Windows. class SVNetwork { public: /// Set up a connection to hostname on port. SVNetwork(const char* hostname, int port); /// Destructor. ~SVNetwork(); /// Put a message in the messagebuffer to the server and try to send it. void Send(const char* msg); /// Receive a message from the server. /// This will always return one line of char* (denoted by \n). char* Receive(); /// Close the connection to the server. void Close(); /// Flush the buffer. void Flush(); private: /// The mutex for access to Send() and Flush(). SVMutex* mutex_send_; /// The actual stream_ to the server. int stream_; /// Stores the last received message-chunk from the server. char* msg_buffer_in_; /// Stores the messages which are supposed to go out. std::string msg_buffer_out_; bool has_content; // Win32 (strtok) /// Where we are at in our msg_buffer_in_ char* buffer_ptr_; // Unix (strtok_r) }; #endif // TESSERACT_VIEWER_SVUTIL_H__
C++
/////////////////////////////////////////////////////////////////////// // File: scrollview.h // Description: ScrollView // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // // ScrollView is designed as an UI which can be run remotely. This is the // client code for it, the server part is written in java. The client consists // mainly of 2 parts: // The "core" ScrollView which sets up the remote connection, // takes care of event handling etc. // The other part of ScrollView consists of predefined API calls through LUA, // which can basically be used to get a zoomable canvas in which it is possible // to draw lines, text etc. // Technically, thanks to LUA, its even possible to bypass the here defined LUA // API calls at all and generate a java user interface from scratch (or // basically generate any kind of java program, possibly even dangerous ones). #ifndef TESSERACT_VIEWER_SCROLLVIEW_H__ #define TESSERACT_VIEWER_SCROLLVIEW_H__ // TODO(rays) Move ScrollView into the tesseract namespace. #ifndef OCR_SCROLLVIEW_H__ #include <stdio.h> class ScrollView; class SVNetwork; class SVMutex; class SVSemaphore; struct SVPolyLineBuffer; 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, // Left button pressed. SVET_SELECTION, // Left button selection. SVET_INPUT, // There is some input (single key or a whole string). 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. SVET_ANY, // Any of the above. SVET_COUNT // Array sizing. }; struct SVEvent { ~SVEvent() { delete [] parameter; } SVEvent* copy(); SVEventType type; // What kind of event. ScrollView* window; // Window event relates to. int x; // Coords of click or selection. int y; int x_size; // Size of selection. int y_size; int command_id; // The ID of the possibly associated event (e.g. MENU) char* parameter; // Any string that might have been passed as argument. int counter; // Used to detect which kind of event to process next. SVEvent() { window = NULL; parameter = NULL; } SVEvent(const SVEvent&); SVEvent& operator=(const SVEvent&); }; // The SVEventHandler class is used for Event handling: If you register your // class as SVEventHandler to a ScrollView Window, the SVEventHandler will be // called whenever an appropriate event occurs. class SVEventHandler { public: virtual ~SVEventHandler() {} // Gets called by the SV Window. Does nothing on default, overwrite this // to implement the desired behaviour virtual void Notify(const SVEvent* sve) { } }; // The ScrollView class provides the expernal API to the scrollviewer process. // The scrollviewer process manages windows and displays images, graphics and // text while allowing the user to zoom and scroll the windows arbitrarily. // Each ScrollView class instance represents one window, and stuff is drawn in // the window through method calls on the class. The constructor is used to // create the class instance (and the window). class ScrollView { public: // Color enum for pens and brushes. enum Color { NONE, BLACK, WHITE, RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA, AQUAMARINE, DARK_SLATE_BLUE, LIGHT_BLUE, MEDIUM_BLUE, MIDNIGHT_BLUE, NAVY_BLUE, SKY_BLUE, SLATE_BLUE, STEEL_BLUE, CORAL, BROWN, SANDY_BROWN, GOLD, GOLDENROD, DARK_GREEN, DARK_OLIVE_GREEN, FOREST_GREEN, LIME_GREEN, PALE_GREEN, YELLOW_GREEN, LIGHT_GREY, DARK_SLATE_GREY, DIM_GREY, GREY, KHAKI, MAROON, ORANGE, ORCHID, PINK, PLUM, INDIAN_RED, ORANGE_RED, VIOLET_RED, SALMON, TAN, TURQUOISE, DARK_TURQUOISE, VIOLET, WHEAT, GREEN_YELLOW // Make sure this one is last. }; ~ScrollView(); #ifndef GRAPHICS_DISABLED // Create a window. The pixel size of the window may be 0,0, in which case // a default size is selected based on the size of your canvas. // The canvas may not be 0,0 in size! ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size); // With a flag whether the x axis is reversed. ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed); // Connect to a server other than localhost. ScrollView(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed, const char* server_name); /******************************************************************************* * Event handling * To register as listener, the class has to derive from the SVEventHandler * class, which consists of a notifyMe(SVEvent*) function that should be * overwritten to process the event the way you want. *******************************************************************************/ // Add an Event Listener to this ScrollView Window. void AddEventHandler(SVEventHandler* listener); // Block until an event of the given type is received. SVEvent* AwaitEvent(SVEventType type); // Block until any event on any window is received. SVEvent* AwaitEventAnyWindow(); /******************************************************************************* * Getters and Setters *******************************************************************************/ // Returns the title of the window. const char* GetName() { return window_name_; } // Returns the unique ID of the window. int GetId() { return window_id_; } /******************************************************************************* * API functions for LUA calls * the implementations for these can be found in svapi.cc * (keep in mind that the window is actually created through the ScrollView * constructor, so this is not listed here) *******************************************************************************/ // Draw a Pix on (x,y). void Image(struct Pix* image, int x_pos, int y_pos); // Flush buffers and update display. static void Update(); // Exit the program. static void Exit(); // Update the contents of a specific window. void UpdateWindow(); // Erase all content from the window, but do not destroy it. void Clear(); // Set pen color with an enum. void Pen(Color color); // Set pen color to RGB (0-255). void Pen(int red, int green, int blue); // Set pen color to RGBA (0-255). void Pen(int red, int green, int blue, int alpha); // Set brush color with an enum. void Brush(Color color); // Set brush color to RGB (0-255). void Brush(int red, int green, int blue); // Set brush color to RGBA (0-255). void Brush(int red, int green, int blue, int alpha); // Set attributes for future text, like font name (e.g. // "Times New Roman"), font size etc.. // Note: The underlined flag is currently not supported void TextAttributes(const char* font, int pixel_size, bool bold, bool italic, bool underlined); // Draw line from (x1,y1) to (x2,y2) with the current pencolor. void Line(int x1, int y1, int x2, int y2); // Set the stroke width of the pen. void Stroke(float width); // Draw a rectangle given upper left corner and lower right corner. // The current pencolor is used as outline, the brushcolor to fill the shape. void Rectangle(int x1, int y1, int x2, int y2); // Draw an ellipse centered on (x,y). // The current pencolor is used as outline, the brushcolor to fill the shape. void Ellipse(int x, int y, int width, int height); // Draw text with the current pencolor void Text(int x, int y, const char* mystring); // Draw an image from a local filename. This should be faster than createImage. // WARNING: This only works on a local machine. This also only works image // types supported by java (like bmp,jpeg,gif,png) since the image is opened by // the server. void Image(const char* image, int x_pos, int y_pos); // Set the current position to draw from (x,y). In conjunction with... void SetCursor(int x, int y); // ...this function, which draws a line from the current to (x,y) and then // sets the new position to the new (x,y), this can be used to easily draw // polygons using vertices void DrawTo(int x, int y); // Set the SVWindow visible/invisible. void SetVisible(bool visible); // Set the SVWindow always on top or not always on top. void AlwaysOnTop(bool b); // Shows a modal dialog with "msg" as question and returns 'y' or 'n'. int ShowYesNoDialog(const char* msg); // Shows a modal dialog with "msg" as question and returns a char* string. // Constraint: As return, only words (e.g. no whitespaces etc.) are allowed. char* ShowInputDialog(const char* msg); // Adds a messagebox to the SVWindow. This way, it can show the messages... void AddMessageBox(); // ...which can be added by this command. // This is intended as an "debug" output window. void AddMessage(const char* format, ...); // Zoom the window to the rectangle given upper left corner and // lower right corner. void ZoomToRectangle(int x1, int y1, int x2, int y2); // Custom messages (manipulating java code directly) can be send through this. // Send a message to the server and attach the Id of the corresponding window. // Note: This should only be called if you are know what you are doing, since // you are fiddling with the Java objects on the server directly. Calling // this just for fun will likely break your application! // It is public so you can actually take use of the LUA functionalities, but // be careful! void SendMsg(const char* msg, ...); // Custom messages (manipulating java code directly) can be send through this. // Send a message to the server without adding the // window id. Used for global events like Exit(). // Note: This should only be called if you are know what you are doing, since // you are fiddling with the Java objects on the server directly. Calling // this just for fun will likely break your application! // It is public so you can actually take use of the LUA functionalities, but // be careful! static void SendRawMessage(const char* msg); /******************************************************************************* * Add new menu entries to parent. If parent is "", the entry gets added to the * main menubar (toplevel). *******************************************************************************/ // This adds a new submenu to the menubar. void MenuItem(const char* parent, const char* name); // This adds a new (normal) menu entry with an associated eventID, which should // be unique among menubar eventIDs. void MenuItem(const char* parent, const char* name, int cmdEvent); // This adds a new checkbox entry, which might initally be flagged. void MenuItem(const char* parent, const char* name, int cmdEvent, bool flagged); // This adds a new popup submenu to the popup menu. If parent is "", the entry // gets added at "toplevel" popupmenu. void PopupItem(const char* parent, const char* name); // This adds a new popup entry with the associated eventID, which should be // unique among popup eventIDs. // If value and desc are given, on a click the server will ask you to modify // the value and return the new value. void PopupItem(const char* parent, const char* name, int cmdEvent, const char* value, const char* desc); // Returns the correct Y coordinate for a window, depending on whether it might // have to be flipped (by ySize). int TranslateYCoordinate(int y); private: // Transfers a binary Image. void TransferBinaryImage(struct Pix* image); // Transfers a gray scale Image. void TransferGrayImage(struct Pix* image); // Transfers a 32-Bit Image. void Transfer32bppImage(struct Pix* image); // Sets up ScrollView, depending on the variables from the constructor. void Initialize(const char* name, int x_pos, int y_pos, int x_size, int y_size, int x_canvas_size, int y_canvas_size, bool y_axis_reversed, const char* server_name); // Send the current buffered polygon (if any) and clear it. void SendPolygon(); // Start the message receiving thread. static void* MessageReceiver(void* a); // Place an event into the event_table (synchronized). void SetEvent(SVEvent* svevent); // Wake up the semaphore. void Signal(); // Returns the unique, shared network stream. static SVNetwork* GetStream() { return stream_; } // Starts a new event handler. Called whenever a new window is created. static void* StartEventHandler(void* sv); // Escapes the ' character with a \, so it can be processed by LUA. char* AddEscapeChars(const char* input); // The event handler for this window. SVEventHandler* event_handler_; // The name of the window. const char* window_name_; // The id of the window. int window_id_; // The points of the currently under-construction polyline. SVPolyLineBuffer* points_; // Whether the axis is reversed. bool y_axis_is_reversed_; // Set to true only after the event handler has terminated. bool event_handler_ended_; // If the y axis is reversed, flip all y values by ySize. int y_size_; // # of created windows (used to assign an id to each ScrollView* for svmap). static int nr_created_windows_; // Serial number of sent images to ensure that the viewer knows they // are distinct. static int image_index_; // The stream through which the c++ client is connected to the server. static SVNetwork* stream_; // Table of all the currently queued events. SVEvent* event_table_[SVET_COUNT]; // Mutex to access the event_table_ in a synchronized fashion. SVMutex* mutex_; // Semaphore to the thread belonging to this window. SVSemaphore* semaphore_; #endif // GRAPHICS_DISABLED }; #endif // OCR_SCROLLVIEW_H__ #endif // TESSERACT_VIEWER_SCROLLVIEW_H__
C++
// Copyright 2007 Google Inc. All Rights Reserved. // // Author: Joern Wanke // // Simple drawing program to illustrate ScrollView capabilities. // // Functionality: // - The menubar is used to select from different sample styles of input. // - With the RMB it is possible to change the RGB values in different // popup menus. // - A LMB click either draws point-to-point, point or text. // - A LMB dragging either draws a line, a rectangle or ellipse. // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #ifndef GRAPHICS_DISABLED #include "scrollview.h" #include "svmnode.h" #include <stdlib.h> #include <iostream> // The current color values we use, initially white (== ScrollView::WHITE). int rgb[3] = { 255, 255, 255 }; class SVPaint : public SVEventHandler { public: explicit SVPaint(const char* server_name); // This is the main event handling function that we need to overwrite, defined // in SVEventHandler. void Notify(const SVEvent* sv_event); private: // The Handler take care of the SVET_POPUP, SVET_MENU, SVET_CLICK and // SVET_SELECTION events. void PopupHandler(const SVEvent* sv_event); void MenuBarHandler(const SVEvent* sv_event); void ClickHandler(const SVEvent* sv_event); void SelectionHandler(const SVEvent* sv_event); // Convenience functions to build little menus. SVMenuNode* BuildPopupMenu(); SVMenuNode* BuildMenuBar(); // Our window. ScrollView* window_; // The mode we are in when an SVET_CLICK or an SVET_SELECTION event occurs. int click_mode_; int drag_mode_; // In the point-to-point drawing mode, we need to set a start-point the first // time we call it (e.g. call SetCursor). bool has_start_point_; }; // Build a sample popup menu. SVMenuNode* SVPaint::BuildPopupMenu() { SVMenuNode* root = new SVMenuNode(); // Empty root node // Initial color is white, so we all values to 255. root->AddChild("R", // Shown caption. 1, // assoc. command_id. "255", // initial value. "Red Color Value?"); // Shown description. root->AddChild("G", 2, "255", "Green Color Value?"); root->AddChild("B", 3, "255", "Blue Color Value?"); return root; } // Build a sample menu bar. SVMenuNode* SVPaint::BuildMenuBar() { SVMenuNode* root = new SVMenuNode(); // Empty root node // Create some submenus and add them to the root. SVMenuNode* click = root->AddChild("Clicking"); SVMenuNode* drag = root->AddChild("Dragging"); // Put some nodes into the submenus. click->AddChild("Point to Point Drawing", // Caption. 1); // command_id. click->AddChild("Point Drawing", 2); click->AddChild("Text Drawing", 3); drag->AddChild("Line Drawing", 4); drag->AddChild("Rectangle Drawing", 5); drag->AddChild("Ellipse Drawing", 6); return root; } // Takes care of the SVET_POPUP events. // In our case, SVET_POPUP is used to set RGB values. void SVPaint::PopupHandler(const SVEvent* sv_event) { // Since we only have the RGB values as popup items, // we take a shortcut to not bloat up code: rgb[sv_event->command_id - 1] = atoi(sv_event->parameter); window_->Pen(rgb[0], rgb[1], rgb[2]); } // Takes care of the SVET_MENU events. // In our case, we change either the click_mode_ (commands 1-3) // or the drag_mode_ (commands 4-6). void SVPaint::MenuBarHandler(const SVEvent* sv_event) { if ((sv_event->command_id > 0) && (sv_event->command_id < 4)) { click_mode_ = sv_event->command_id; has_start_point_ = false; } else { drag_mode_ = sv_event->command_id; } } // Takes care of the SVET_CLICK events. // Depending on the click_mode_ we are in, either do Point-to-Point drawing, // point drawing, or draw text. void SVPaint::ClickHandler(const SVEvent* sv_event) { switch (click_mode_) { case 1: //Point to Point if (has_start_point_) { window_->DrawTo(sv_event->x, sv_event->y); } else { has_start_point_ = true; window_->SetCursor(sv_event->x, sv_event->y); } break; case 2: //Point Drawing..simulated by drawing a 1 pixel line. window_->Line(sv_event->x, sv_event->y, sv_event->x, sv_event->y); break; case 3: //Text // We show a modal input dialog on our window, then draw the input and // finally delete the input pointer. char* p = window_->ShowInputDialog("Text:"); window_->Text(sv_event->x, sv_event->y, p); delete [] p; break; } } // Takes care of the SVET_SELECTION events. // Depending on the drag_mode_ we are in, either draw a line, a rectangle or // an ellipse. void SVPaint::SelectionHandler(const SVEvent* sv_event) { switch (drag_mode_) { //FIXME inversed x_size, y_size case 4: //Line window_->Line(sv_event->x, sv_event->y, sv_event->x - sv_event->x_size, sv_event->y - sv_event->y_size); break; case 5: //Rectangle window_->Rectangle(sv_event->x, sv_event->y, sv_event->x - sv_event->x_size, sv_event->y - sv_event->y_size); break; case 6: //Ellipse window_->Ellipse(sv_event->x - sv_event->x_size, sv_event->y - sv_event->y_size, sv_event->x_size, sv_event->y_size); break; } } // The event handling function from ScrollView which we have to overwrite. // We handle CLICK, SELECTION, MENU and POPUP and throw away all other events. void SVPaint::Notify(const SVEvent* sv_event) { if (sv_event->type == SVET_CLICK) { ClickHandler(sv_event); } else if (sv_event->type == SVET_SELECTION) { SelectionHandler(sv_event); } else if (sv_event->type == SVET_MENU) { MenuBarHandler(sv_event); } else if (sv_event->type == SVET_POPUP) { PopupHandler(sv_event); } else {} //throw other events away } // Builds a new window, initializes the variables and event handler and builds // the menu. SVPaint::SVPaint(const char *server_name) { window_ = new ScrollView("ScrollView Paint Example", // window caption 0, 0, // x,y window position 500, 500, // window size 500, 500, // canvas size false, // whether the Y axis is inversed. // this is included due to legacy // reasons for tesseract and enables // us to have (0,0) as the LOWER left // of the coordinate system. server_name); // the server address. // Set the start modes to point-to-point and line drawing. click_mode_ = 1; drag_mode_ = 4; has_start_point_ = false; // Bild our menus and add them to the window. The flag illustrates whether // this is a menu bar. SVMenuNode* popup_menu = BuildPopupMenu(); popup_menu->BuildMenu(window_,false); SVMenuNode* bar_menu = BuildMenuBar(); bar_menu->BuildMenu(window_,true); // Set the initial color values to White (could also be done by // passing (rgb[0], rgb[1], rgb[2]). window_->Pen(ScrollView::WHITE); window_->Brush(ScrollView::WHITE); // Adds the event handler to the window. This actually ensures that Notify // gets called when events occur. window_->AddEventHandler(this); // Set the window visible (calling this is important to actually render // everything. Without this call, the window would also be drawn, but the // menu bars would be missing. window_->SetVisible(true); // Rest this thread until its window is destroyed. // Note that a special eventhandling thread was created when constructing // the window. Due to this, the application will not deadlock here. window_->AwaitEvent(SVET_DESTROY); // We now have 3 Threads running: // (1) The MessageReceiver thread which fetches messages and distributes them // (2) The EventHandler thread which handles all events for window_ // (3) The main thread which waits on window_ for a DESTROY event (blocked) } // If a parameter is given, we try to connect to the given server. // This enables us to test the remote capabilites of ScrollView. int main(int argc, char** argv) { const char* server_name; if (argc > 1) { server_name = argv[1]; } else { server_name = "localhost"; } SVPaint svp(server_name); } #endif // GRAPHICS_DISABLED
C++
/////////////////////////////////////////////////////////////////////// // File: svmnode.h // description_: ScrollView Menu Node // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // // A SVMenuNode is an entity which contains the mapping from a menu entry on // the server side to the corresponding associated commands on the client. // It is designed to be a tree structure with a root node, which can then be // used to generate the appropriate messages to the server to display the // menu structure there. // A SVMenuNode can both be used in the context_ of popup menus as well as // menu bars. #ifndef TESSERACT_VIEWER_SVMNODE_H__ #define TESSERACT_VIEWER_SVMNODE_H__ #include "strngs.h" class ScrollView; class SVMenuNode { public: // Creating the (empty) root menu node. SVMenuNode(); // Destructor for every node. ~SVMenuNode(); // Create a new sub menu node with just a caption. This is used to create // nodes which act as parent nodes to other nodes (e.g. submenus). SVMenuNode* AddChild(const char* txt); // Create a "normal" menu node which is associated with a command event. void AddChild(const char* txt, int command_event); // Create a flag menu node. void AddChild(const char* txt, int command_event, int tv); // Create a menu node with an associated value (which might be changed // through the gui). void AddChild(const char* txt, int command_event, const char* val); // Create a menu node with an associated value and description_. void AddChild(const char* txt, int command_event, const char* val, const char* desc); // Build a menu structure for the server and send the necessary messages. // Should be called on the root node. If menu_bar is true, a menu_bar menu // is built (e.g. on top of the window), if it is false a popup menu is // built which gets shown by right clicking on the window. void BuildMenu(ScrollView *sv, bool menu_bar = true); private: // Constructor holding the actual node data. SVMenuNode(int command_event, const char* txt, int tv, bool check_box_entry, const char* val, const char* desc); // Adds a new menu node to the current node. void AddChild(SVMenuNode* svmn); // The parent node of this node. SVMenuNode* parent_; // The first child of this node. SVMenuNode* child_; // The next "sibling" of this node (e.g. same parent). SVMenuNode* next_; // Whether this menu node actually is a flag. bool is_check_box_entry_; // The command event associated with a specific menu node. Should be unique. int cmd_event_; // The caption associated with a specific menu node. STRING text_; // The value of the flag (if this menu node is a flag). bool toggle_value_; // The value of the menu node. (optional) STRING value_; // A description_ of the value. (optional) STRING description_; }; #endif // TESSERACT_VIEWER_SVMNODE_H__
C++
/////////////////////////////////////////////////////////////////////// // File: svutil.cpp // Description: ScrollView Utilities // Author: Joern Wanke // Created: Thu Nov 29 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. // /////////////////////////////////////////////////////////////////////// // // SVUtil contains the SVSync and SVNetwork classes, which are used for // thread/process creation & synchronization and network connection. #include <stdio.h> #ifdef _WIN32 struct addrinfo { struct sockaddr* ai_addr; int ai_addrlen; int ai_family; int ai_socktype; int ai_protocol; }; #else #include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #ifdef __linux__ #include <sys/prctl.h> #endif #include <unistd.h> #endif #include <cstdlib> #include <cstring> #include <iostream> #include <string> // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #ifndef GRAPHICS_DISABLED #include "svutil.h" const int kBufferSize = 65536; const int kMaxMsgSize = 4096; // Signals a thread to exit. void SVSync::ExitThread() { #ifdef _WIN32 // ExitThread(0); #else pthread_exit(0); #endif } // Starts a new process. void SVSync::StartProcess(const char* executable, const char* args) { std::string proc; proc.append(executable); proc.append(" "); proc.append(args); std::cout << "Starting " << proc << std::endl; #ifdef _WIN32 STARTUPINFO start_info; PROCESS_INFORMATION proc_info; GetStartupInfo(&start_info); if (!CreateProcess(NULL, const_cast<char*>(proc.c_str()), NULL, NULL, FALSE, CREATE_NO_WINDOW | DETACHED_PROCESS, NULL, NULL, &start_info, &proc_info)) return; #else int pid = fork(); if (pid != 0) { // The father process returns } else { #ifdef __linux__ // Make sure the java process terminates on exit, since its // broken socket detection seems to be useless. prctl(PR_SET_PDEATHSIG, 2, 0, 0, 0); #endif char* mutable_args = strdup(args); int argc = 1; for (int i = 0; mutable_args[i]; ++i) { if (mutable_args[i] == ' ') { ++argc; } } char** argv = new char*[argc + 2]; argv[0] = strdup(executable); argv[1] = mutable_args; argc = 2; bool inquote = false; for (int i = 0; mutable_args[i]; ++i) { if (!inquote && mutable_args[i] == ' ') { mutable_args[i] = '\0'; argv[argc++] = mutable_args + i + 1; } else if (mutable_args[i] == '"') { inquote = !inquote; mutable_args[i] = ' '; } } argv[argc] = NULL; execvp(executable, argv); } #endif } SVSemaphore::SVSemaphore() { #ifdef _WIN32 semaphore_ = CreateSemaphore(0, 0, 10, 0); #elif defined(__APPLE__) char name[50]; snprintf(name, sizeof(name), "%d", random()); sem_unlink(name); semaphore_ = sem_open(name, O_CREAT , S_IWUSR, 0); if (semaphore_ == SEM_FAILED) { perror("sem_open"); } #else sem_init(&semaphore_, 0, 0); #endif } void SVSemaphore::Signal() { #ifdef _WIN32 ReleaseSemaphore(semaphore_, 1, NULL); #elif defined(__APPLE__) sem_post(semaphore_); #else sem_post(&semaphore_); #endif } void SVSemaphore::Wait() { #ifdef _WIN32 WaitForSingleObject(semaphore_, INFINITE); #elif defined(__APPLE__) sem_wait(semaphore_); #else sem_wait(&semaphore_); #endif } SVMutex::SVMutex() { #ifdef _WIN32 mutex_ = CreateMutex(0, FALSE, 0); #else pthread_mutex_init(&mutex_, NULL); #endif } void SVMutex::Lock() { #ifdef _WIN32 WaitForSingleObject(mutex_, INFINITE); #else pthread_mutex_lock(&mutex_); #endif } void SVMutex::Unlock() { #ifdef _WIN32 ReleaseMutex(mutex_); #else pthread_mutex_unlock(&mutex_); #endif } // Create new thread. void SVSync::StartThread(void *(*func)(void*), void* arg) { #ifdef _WIN32 LPTHREAD_START_ROUTINE f = (LPTHREAD_START_ROUTINE) func; DWORD threadid; HANDLE newthread = CreateThread( NULL, // default security attributes 0, // use default stack size f, // thread function arg, // argument to thread function 0, // use default creation flags &threadid); // returns the thread identifier #else pthread_t helper; pthread_create(&helper, NULL, func, arg); #endif } // Place a message in the message buffer (and flush it). void SVNetwork::Send(const char* msg) { mutex_send_->Lock(); msg_buffer_out_.append(msg); mutex_send_->Unlock(); } // Send the whole buffer. void SVNetwork::Flush() { mutex_send_->Lock(); while (msg_buffer_out_.size() > 0) { int i = send(stream_, msg_buffer_out_.c_str(), msg_buffer_out_.length(), 0); msg_buffer_out_.erase(0, i); } mutex_send_->Unlock(); } // Receive a message from the server. // This will always return one line of char* (denoted by \n). char* SVNetwork::Receive() { char* result = NULL; #if defined(_WIN32) || defined(__CYGWIN__) if (has_content) { result = strtok (NULL, "\n"); } #else if (buffer_ptr_ != NULL) { result = strtok_r(NULL, "\n", &buffer_ptr_); } #endif // This means there is something left in the buffer and we return it. if (result != NULL) { return result; // Otherwise, we read from the stream_. } else { buffer_ptr_ = NULL; has_content = false; // The timeout length is not really important since we are looping anyway // until a new message is delivered. struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; // Set the flags to return when the stream_ is ready to be read. fd_set readfds; FD_ZERO(&readfds); FD_SET(stream_, &readfds); int i = select(stream_+1, &readfds, NULL, NULL, &tv); // The stream_ died. if (i == 0) { return NULL; } // Read the message buffer. i = recv(stream_, msg_buffer_in_, kMaxMsgSize, 0); // Server quit (0) or error (-1). if (i <= 0) { return NULL; } msg_buffer_in_[i] = '\0'; has_content = true; #ifdef _WIN32 return strtok(msg_buffer_in_, "\n"); #else // Setup a new string tokenizer. return strtok_r(msg_buffer_in_, "\n", &buffer_ptr_); #endif } } // Close the connection to the server. void SVNetwork::Close() { #ifdef _WIN32 closesocket(stream_); #else close(stream_); #endif } // The program to invoke to start ScrollView static const char* ScrollViewProg() { #ifdef _WIN32 const char* prog = "java -Xms512m -Xmx1024m"; #else const char* prog = "sh"; #endif return prog; } // The arguments to the program to invoke to start ScrollView static std::string ScrollViewCommand(std::string scrollview_path) { // The following ugly ifdef is to enable the output of the java runtime // to be sent down a black hole on non-windows to ignore all the // exceptions in piccolo. Ideally piccolo would be debugged to make // this unnecessary. // Also the path has to be separated by ; on windows and : otherwise. #ifdef _WIN32 const char* cmd_template = "-Djava.library.path=%s -cp %s/ScrollView.jar;" "%s/piccolo2d-core-3.0.jar:%s/piccolo2d-extras-3.0.jar" " com.google.scrollview.ScrollView"; #else const char* cmd_template = "-c \"trap 'kill %%1' 0 1 2 ; java " "-Xms1024m -Xmx2048m -Djava.library.path=%s -cp %s/ScrollView.jar:" "%s/piccolo2d-core-3.0.jar:%s/piccolo2d-extras-3.0.jar" " com.google.scrollview.ScrollView" " & wait\""; #endif int cmdlen = strlen(cmd_template) + 4*strlen(scrollview_path.c_str()) + 1; char* cmd = new char[cmdlen]; const char* sv_path = scrollview_path.c_str(); snprintf(cmd, cmdlen, cmd_template, sv_path, sv_path, sv_path, sv_path); std::string command(cmd); delete [] cmd; return command; } // Platform-independent freeaddrinfo() static void FreeAddrInfo(struct addrinfo* addr_info) { #if defined(__linux__) freeaddrinfo(addr_info); #else delete addr_info->ai_addr; delete addr_info; #endif } // Non-linux version of getaddrinfo() #if !defined(__linux__) static int GetAddrInfoNonLinux(const char* hostname, int port, struct addrinfo** addr_info) { // Get the host data depending on the OS. struct sockaddr_in* address; *addr_info = new struct addrinfo; memset(*addr_info, 0, sizeof(struct addrinfo)); address = new struct sockaddr_in; memset(address, 0, sizeof(struct sockaddr_in)); (*addr_info)->ai_addr = (struct sockaddr*) address; (*addr_info)->ai_addrlen = sizeof(struct sockaddr); (*addr_info)->ai_family = AF_INET; (*addr_info)->ai_socktype = SOCK_STREAM; struct hostent *name; #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); name = gethostbyname(hostname); #else name = gethostbyname(hostname); #endif if (name == NULL) { FreeAddrInfo(*addr_info); *addr_info = NULL; return -1; } // Fill in the appropriate variables to be able to connect to the server. address->sin_family = name->h_addrtype; memcpy((char *) &address->sin_addr.s_addr, name->h_addr_list[0], name->h_length); address->sin_port = htons(port); return 0; } #endif // Platform independent version of getaddrinfo() // Given a hostname:port, produce an addrinfo struct static int GetAddrInfo(const char* hostname, int port, struct addrinfo** address) { #if defined(__linux__) char port_str[40]; snprintf(port_str, 40, "%d", port); return getaddrinfo(hostname, port_str, NULL, address); #else return GetAddrInfoNonLinux(hostname, port, address); #endif } // Set up a connection to a ScrollView on hostname:port. SVNetwork::SVNetwork(const char* hostname, int port) { mutex_send_ = new SVMutex(); msg_buffer_in_ = new char[kMaxMsgSize + 1]; msg_buffer_in_[0] = '\0'; has_content = false; buffer_ptr_ = NULL; struct addrinfo *addr_info = NULL; if (GetAddrInfo(hostname, port, &addr_info) != 0) { std::cerr << "Error resolving name for ScrollView host " << std::string(hostname) << ":" << port << std::endl; } stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); // If server is not there, we will start a new server as local child process. if (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) < 0) { const char* scrollview_path = getenv("SCROLLVIEW_PATH"); if (scrollview_path == NULL) { #ifdef SCROLLVIEW_PATH #define _STR(a) #a #define _XSTR(a) _STR(a) scrollview_path = _XSTR(SCROLLVIEW_PATH); #undef _XSTR #undef _STR #else scrollview_path = "."; #endif } const char *prog = ScrollViewProg(); std::string command = ScrollViewCommand(scrollview_path); SVSync::StartProcess(prog, command.c_str()); // Wait for server to show up. // Note: There is no exception handling in case the server never turns up. stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); while (connect(stream_, addr_info->ai_addr, addr_info->ai_addrlen) < 0) { std::cout << "ScrollView: Waiting for server...\n"; #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif stream_ = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); } } FreeAddrInfo(addr_info); } SVNetwork::~SVNetwork() { delete[] msg_buffer_in_; delete mutex_send_; } #endif // GRAPHICS_DISABLED
C++
/* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies of the Software and its Copyright notices. In addition publicly documented acknowledgment must be given that this software has been used if no source code of this software is made available publicly. Making the source available publicly means including the source for this software with the distribution, or a method to get this software via some reasonable mechanism (electronic transfer via a network or media) as well as making an offer to supply the source on request. This Copyright notice serves as an offer to supply the source on on request as well. Instead of this, supplying acknowledgments of use of this software in either Copyright notices, Manuals, Publicity and Marketing documents or any documentation provided with any product containing this software. This License does not apply to any software that links to the libraries provided by this software (statically or dynamically), but only to the software provided. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Source: Evil 1.7.4 The Evil library tried to port some convenient Unix functions to the Windows (XP or CE) platform. They are planned to be used http://git.enlightenment.org/legacy/evil.git/tree/src/lib/evil_string.c?id=eeaddf80d0d547d4c216974038c0599b34359695 */ #include <stdlib.h> #include <string.h> #include <ctype.h> char *strcasestr(const char *haystack, const char *needle) { size_t length_needle; size_t length_haystack; size_t i; if (!haystack || !needle) return NULL; length_needle = strlen(needle); length_haystack = strlen(haystack) - length_needle + 1; for (i = 0; i < length_haystack; i++) { size_t j; for (j = 0; j < length_needle; j++) { unsigned char c1; unsigned char c2; c1 = haystack[i+j]; c2 = needle[j]; if (toupper(c1) != toupper(c2)) goto next; } return (char *) haystack + i; next: ; } return NULL; }
C++
/* * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // source: https://github.com/heimdal/heimdal/blob/master/lib/roken/strtok_r.c #include <string.h> char *strtok_r(char *s1, const char *s2, char **lasts) { char *ret; if (s1 == NULL) s1 = *lasts; while (*s1 && strchr(s2, *s1)) ++s1; if (*s1 == '\0') return NULL; ret = s1; while (*s1 && !strchr(s2, *s1)) ++s1; if (*s1) *s1++ = '\0'; *lasts = s1; return ret; }
C++
/////////////////////////////////////////////////////////////////////// // File: gettimeofday.cpp // Description: Implementation of gettimeofday based on leptonica // Author: tomp2010, zdenop // Created: Tue Feb 21 21:38:00 CET 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 <allheaders.h> #include "gettimeofday.h" int gettimeofday(struct timeval *tp, struct timezone *tzp) { l_int32 sec, usec; if (tp == NULL) return -1; l_getCurrentTime(&sec, &usec); tp->tv_sec = sec; tp->tv_usec = usec; return 0; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" #include "glyphy-geometry.hh" #include "glyphy-arc-bezier.hh" using namespace GLyphy::Geometry; using namespace GLyphy::ArcBezier; /* * Circular arcs */ /* Build from a conventional arc representation */ void glyphy_arc_from_conventional (const glyphy_point_t *center, double radius, double angle0, double angle1, glyphy_bool_t negative, glyphy_arc_t *arc) { *arc = Arc (*center, radius, angle0, angle1, negative); }; /* Convert to a conventional arc representation */ void glyphy_arc_to_conventional (glyphy_arc_t arc, glyphy_point_t *center /* may be NULL */, double *radius /* may be NULL */, double *angle0 /* may be NULL */, double *angle1 /* may be NULL */, glyphy_bool_t *negative /* may be NULL */) { Arc a (arc); if (radius) *radius = a.radius (); if (center || angle0 || angle1) { Point c = a.center (); if (center) *center = c; if (angle0) *angle0 = (a.p0 - c).angle (); if (angle1) *angle1 = (a.p1 - c).angle (); if (negative) *negative = a.d < 0; } } glyphy_bool_t glyphy_arc_is_a_line (glyphy_arc_t arc) { return arc.d == 0; } void glyphy_arc_extents (glyphy_arc_t arc, glyphy_extents_t *extents) { Arc(arc).extents (*extents); } /* * Approximate single pieces of geometry to/from one arc */ void glyphy_arc_from_line (const glyphy_point_t *p0, const glyphy_point_t *p1, glyphy_arc_t *arc) { *arc = Arc (*p0, *p1, 0); } void glyphy_arc_from_conic (const glyphy_point_t *p0, const glyphy_point_t *p1, const glyphy_point_t *p2, glyphy_arc_t *arc, double *error) { Point p1_ (Point (*p0).lerp (2/3., *p1)); Point p2_ (Point (*p2).lerp (2/3., *p1)); glyphy_arc_from_cubic (p0, &p1_, &p2_, p2, arc, error); } void glyphy_arc_from_cubic (const glyphy_point_t *p0, const glyphy_point_t *p1, const glyphy_point_t *p2, const glyphy_point_t *p3, glyphy_arc_t *arc, double *error) { *arc = ArcBezierApproximatorDefault::approximate_bezier_with_arc (Bezier (*p0, *p1, *p2, *p3), error); } void glyphy_arc_to_cubic (const glyphy_arc_t *arc, glyphy_point_t *p0, glyphy_point_t *p1, glyphy_point_t *p2, glyphy_point_t *p3, double *error) { Bezier b = Arc (*arc).approximate_bezier (error); *p0 = arc->p0; *p1 = b.p1; *p2 = b.p2; *p3 = arc->p1; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" void glyphy_extents_clear (glyphy_extents_t *extents) { extents->min_x = GLYPHY_INFINITY; extents->min_y = GLYPHY_INFINITY; extents->max_x = -GLYPHY_INFINITY; extents->max_y = -GLYPHY_INFINITY; } glyphy_bool_t glyphy_extents_is_empty (const glyphy_extents_t *extents) { return isinf (extents->min_x); } void glyphy_extents_add (glyphy_extents_t *extents, const glyphy_point_t *p) { if (glyphy_extents_is_empty (extents)) { extents->min_x = extents->max_x = p->x; extents->min_y = extents->max_y = p->y; return; } extents->min_x = std::min (extents->min_x, p->x); extents->min_y = std::min (extents->min_y, p->y); extents->max_x = std::max (extents->max_x, p->x); extents->max_y = std::max (extents->max_y, p->y); } void glyphy_extents_extend (glyphy_extents_t *extents, const glyphy_extents_t *other) { if (glyphy_extents_is_empty (other)) return; if (glyphy_extents_is_empty (extents)) { *extents = *other; return; } extents->min_x = std::min (extents->min_x, other->min_x); extents->min_y = std::min (extents->min_y, other->min_y); extents->max_x = std::max (extents->max_x, other->max_x); extents->max_y = std::max (extents->max_y, other->max_y); } glyphy_bool_t glyphy_extents_includes (const glyphy_extents_t *extents, const glyphy_point_t *p) { return extents->min_x <= p->x && p->x <= extents->max_x && extents->min_y <= p->y && p->y <= extents->max_y; } void glyphy_extents_scale (glyphy_extents_t *extents, double x_scale, double y_scale) { extents->min_x *= x_scale; extents->max_x *= x_scale; extents->min_y *= y_scale; extents->max_y *= y_scale; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju */ #ifndef GLYPHY_ARCS_BEZIER_HH #define GLYPHY_ARCS_BEZIER_HH #include "glyphy-common.hh" #include "glyphy-geometry.hh" #include "glyphy-arc-bezier.hh" namespace GLyphy { namespace ArcsBezier { using namespace Geometry; using namespace ArcBezier; template <class ArcBezierApproximator> class ArcsBezierApproximatorSpringSystem { static inline void calc_arcs (const Bezier &b, const std::vector<double> &t, const ArcBezierApproximator &appx, std::vector<double> &e, std::vector<Arc > &arcs, double &max_e, double &min_e) { unsigned int n = t.size () - 1; e.resize (n); arcs.clear (); max_e = 0; min_e = GLYPHY_INFINITY; for (unsigned int i = 0; i < n; i++) { Bezier segment = b.segment (t[i], t[i + 1]); arcs.push_back (appx.approximate_bezier_with_arc (segment, &e[i])); max_e = std::max (max_e, e[i]); min_e = std::min (min_e, e[i]); } } static inline void jiggle (const Bezier &b, const ArcBezierApproximator &appx, std::vector<double> &t, std::vector<double> &e, std::vector<Arc > &arcs, double &max_e, double &min_e, double tolerance, unsigned int &n_jiggle) { unsigned int n = t.size () - 1; //fprintf (stderr, "candidate n %d max_e %g min_e %g\n", n, max_e, min_e); unsigned int max_jiggle = log2 (n) + 1; unsigned int s; for (s = 0; s < max_jiggle; s++) { double total = 0; for (unsigned int i = 0; i < n; i++) { double l = t[i + 1] - t[i]; double k_inv = l * pow (e[i], -.3); total += k_inv; e[i] = k_inv; } for (unsigned int i = 0; i < n; i++) { double k_inv = e[i]; double l = k_inv / total; t[i + 1] = t[i] + l; } t[n] = 1.0; // Do this to get real 1.0, not .9999999999999998! calc_arcs (b, t, appx, e, arcs, max_e, min_e); //fprintf (stderr, "n %d jiggle %d max_e %g min_e %g\n", n, s, max_e, min_e); n_jiggle++; if (max_e < tolerance || (2 * min_e - max_e > tolerance)) break; } //if (s == max_jiggle) fprintf (stderr, "JIGGLE OVERFLOW n %d s %d\n", n, s); } public: static void approximate_bezier_with_arcs (const Bezier &b, double tolerance, const ArcBezierApproximator &appx, std::vector<Arc> &arcs, double *perror, unsigned int max_segments = 100) { std::vector<double> t; std::vector<double> e; double max_e, min_e; unsigned int n_jiggle = 0; /* Technically speaking we can bsearch for n. */ for (unsigned int n = 1; n <= max_segments; n++) { t.resize (n + 1); for (unsigned int i = 0; i < n; i++) t[i] = double (i) / n; t[n] = 1.0; // Do this out of the loop to get real 1.0, not .9999999999999998! calc_arcs (b, t, appx, e, arcs, max_e, min_e); for (unsigned int i = 0; i < n; i++) if (e[i] <= tolerance) { jiggle (b, appx, t, e, arcs, max_e, min_e, tolerance, n_jiggle); break; } if (max_e <= tolerance) break; } if (perror) *perror = max_e; //fprintf (stderr, "n_jiggle %d\n", n_jiggle); } }; } /* namespace ArcsBezier */ } /* namespace GLyphy */ #endif /* GLYPHY_ARCS_BEZIER_HH */
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" #include "glyphy-geometry.hh" #define GRID_SIZE 24 using namespace GLyphy::Geometry; #define UPPER_BITS(v,bits,total_bits) ((v) >> ((total_bits) - (bits))) #define LOWER_BITS(v,bits,total_bits) ((v) & ((1 << (bits)) - 1)) #define MAX_X 4095 #define MAX_Y 4095 static inline glyphy_rgba_t arc_endpoint_encode (unsigned int ix, unsigned int iy, double d) { glyphy_rgba_t v; /* 12 bits for each of x and y, 8 bits for d */ assert (ix <= MAX_X); assert (iy <= MAX_Y); unsigned int id; if (isinf (d)) id = 0; else { assert (fabs (d) <= GLYPHY_MAX_D); id = 128 + lround (d * 127 / GLYPHY_MAX_D); } assert (id < 256); v.r = id; v.g = LOWER_BITS (ix, 8, 12); v.b = LOWER_BITS (iy, 8, 12); v.a = ((ix >> 8) << 4) | (iy >> 8); return v; } static inline glyphy_rgba_t arc_list_encode (unsigned int offset, unsigned int num_points, int side) { glyphy_rgba_t v; v.r = 0; // unused for arc-list encoding v.g = UPPER_BITS (offset, 8, 16); v.b = LOWER_BITS (offset, 8, 16); v.a = LOWER_BITS (num_points, 8, 8); if (side < 0 && !num_points) v.a = 255; return v; } static inline glyphy_rgba_t line_encode (const Line &line) { Line l = line.normalized (); double angle = l.n.angle (); double distance = l.c; int ia = lround (-angle / M_PI * 0x7FFF); unsigned int ua = ia + 0x8000; assert (0 == (ua & ~0xFFFF)); int id = lround (distance * 0x1FFF); unsigned int ud = id + 0x4000; assert (0 == (ud & ~0x7FFF)); /* Marker for line-encoded */ ud |= 0x8000; glyphy_rgba_t v; v.r = ud >> 8; v.g = ud & 0xFF; v.b = ua >> 8; v.a = ua & 0xFF; return v; } /* Given a cell, fills the vector closest_arcs with arcs that may be closest to some point in the cell. * Uses idea that all close arcs to cell must be ~close to center of cell. */ static void closest_arcs_to_cell (Point c0, Point c1, /* corners */ double faraway, const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, std::vector<glyphy_arc_endpoint_t> &near_endpoints, int *side) { // Find distance between cell center Point c = c0.midpoint (c1); double min_dist = glyphy_sdf_from_arc_list (endpoints, num_endpoints, &c, NULL); *side = min_dist >= 0 ? +1 : -1; min_dist = fabs (min_dist); std::vector<Arc> near_arcs; // If d is the distance from the center of the square to the nearest arc, then // all nearest arcs to the square must be at most almost [d + half_diagonal] from the center. double half_diagonal = (c - c0).len (); double radius_squared = pow (min_dist + half_diagonal, 2); if (min_dist - half_diagonal <= faraway) { Point p0 (0, 0); for (unsigned int i = 0; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY) { p0 = endpoint.p; continue; } Arc arc (p0, endpoint.p, endpoint.d); p0 = endpoint.p; if (arc.squared_distance_to_point (c) <= radius_squared) near_arcs.push_back (arc); } } Point p1 = Point (0, 0); for (unsigned i = 0; i < near_arcs.size (); i++) { Arc arc = near_arcs[i]; if (i == 0 || p1 != arc.p0) { glyphy_arc_endpoint_t endpoint = {arc.p0, GLYPHY_INFINITY}; near_endpoints.push_back (endpoint); p1 = arc.p0; } glyphy_arc_endpoint_t endpoint = {arc.p1, arc.d}; near_endpoints.push_back (endpoint); p1 = arc.p1; } } glyphy_bool_t glyphy_arc_list_encode_blob (const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, glyphy_rgba_t *blob, unsigned int blob_size, double faraway, double avg_fetch_desired, double *avg_fetch_achieved, unsigned int *output_len, unsigned int *nominal_width, /* 8bit */ unsigned int *nominal_height, /* 8bit */ glyphy_extents_t *pextents) { glyphy_extents_t extents; glyphy_extents_clear (&extents); glyphy_arc_list_extents (endpoints, num_endpoints, &extents); if (glyphy_extents_is_empty (&extents)) { *pextents = extents; if (!blob_size) return false; *blob = arc_list_encode (0, 0, +1); *avg_fetch_achieved = 1; *output_len = 1; *nominal_width = *nominal_height = 1; return true; } /* Add antialiasing padding */ extents.min_x -= faraway; extents.min_y -= faraway; extents.max_x += faraway; extents.max_y += faraway; double glyph_width = extents.max_x - extents.min_x; double glyph_height = extents.max_y - extents.min_y; double unit = std::max (glyph_width, glyph_height); unsigned int grid_w = GRID_SIZE; unsigned int grid_h = GRID_SIZE; if (glyph_width > glyph_height) { while ((grid_h - 1) * unit / grid_w > glyph_height) grid_h--; glyph_height = grid_h * unit / grid_w; extents.max_y = extents.min_y + glyph_height; } else { while ((grid_w - 1) * unit / grid_h > glyph_width) grid_w--; glyph_width = grid_w * unit / grid_h; extents.max_x = extents.min_x + glyph_width; } double cell_unit = unit / std::max (grid_w, grid_h); std::vector<glyphy_rgba_t> tex_data; std::vector<glyphy_arc_endpoint_t> near_endpoints; unsigned int header_length = grid_w * grid_h; unsigned int offset = header_length; tex_data.resize (header_length); Point origin = Point (extents.min_x, extents.min_y); unsigned int total_arcs = 0; for (unsigned int row = 0; row < grid_h; row++) for (unsigned int col = 0; col < grid_w; col++) { Point cp0 = origin + Vector ((col + 0) * cell_unit, (row + 0) * cell_unit); Point cp1 = origin + Vector ((col + 1) * cell_unit, (row + 1) * cell_unit); near_endpoints.clear (); int side; closest_arcs_to_cell (cp0, cp1, faraway, endpoints, num_endpoints, near_endpoints, &side); #define QUANTIZE_X(X) (lround (MAX_X * ((X - extents.min_x) / glyph_width ))) #define QUANTIZE_Y(Y) (lround (MAX_Y * ((Y - extents.min_y) / glyph_height))) #define DEQUANTIZE_X(X) (double (X) / MAX_X * glyph_width + extents.min_x) #define DEQUANTIZE_Y(Y) (double (Y) / MAX_Y * glyph_height + extents.min_y) #define SNAP(P) (Point (DEQUANTIZE_X (QUANTIZE_X ((P).x)), DEQUANTIZE_Y (QUANTIZE_Y ((P).y)))) if (near_endpoints.size () == 2 && near_endpoints[1].d == 0) { Point c (extents.min_x + glyph_width * .5, extents.min_y + glyph_height * .5); Line line (SNAP (near_endpoints[0].p), SNAP (near_endpoints[1].p)); line.c -= line.n * Vector (c); line.c /= unit; tex_data[row * grid_w + col] = line_encode (line); continue; } /* If the arclist is two arcs that can be combined in encoding if reordered, * do that. */ if (near_endpoints.size () == 4 && isinf (near_endpoints[2].d) && near_endpoints[0].p.x == near_endpoints[3].p.x && near_endpoints[0].p.y == near_endpoints[3].p.y) { glyphy_arc_endpoint_t e0, e1, e2; e0 = near_endpoints[2]; e1 = near_endpoints[3]; e2 = near_endpoints[1]; near_endpoints.resize (0); near_endpoints.push_back (e0); near_endpoints.push_back (e1); near_endpoints.push_back (e2); } for (unsigned i = 0; i < near_endpoints.size (); i++) { glyphy_arc_endpoint_t &endpoint = near_endpoints[i]; tex_data.push_back (arc_endpoint_encode (QUANTIZE_X(endpoint.p.x), QUANTIZE_Y(endpoint.p.y), endpoint.d)); } unsigned int current_endpoints = tex_data.size () - offset; /* See if we can fulfill this cell by using already-encoded arcs */ const glyphy_rgba_t *needle = &tex_data[offset]; unsigned int needle_len = current_endpoints; const glyphy_rgba_t *haystack = &tex_data[header_length]; unsigned int haystack_len = offset - header_length; bool found = false; if (needle_len) while (haystack_len >= needle_len) { /* Trick: we don't care about first endpoint's d value, so skip one * byte in comparison. This works because arc_encode() packs the * d value in the first byte. */ if (0 == memcmp (1 + (const char *) needle, 1 + (const char *) haystack, needle_len * sizeof (*needle) - 1)) { found = true; break; } haystack++; haystack_len--; } if (found) { tex_data.resize (offset); offset = haystack - &tex_data[0]; } tex_data[row * grid_w + col] = arc_list_encode (offset, current_endpoints, side); offset = tex_data.size (); total_arcs += current_endpoints; } if (avg_fetch_achieved) *avg_fetch_achieved = 1 + double (total_arcs) / (grid_w * grid_h); *pextents = extents; if (tex_data.size () > blob_size) return false; memcpy (blob, &tex_data[0], tex_data.size () * sizeof(tex_data[0])); *output_len = tex_data.size (); *nominal_width = grid_w; *nominal_height = grid_h; return true; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" #include "glyphy-geometry.hh" using namespace GLyphy::Geometry; /* * TODO * * Sync this with the shader sdf */ double glyphy_sdf_from_arc_list (const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, const glyphy_point_t *p, glyphy_point_t *closest_p /* may be NULL; TBD not implemented yet */) { Point c = *p; Point p0 (0, 0); Arc closest_arc (p0, p0, 0); double min_dist = GLYPHY_INFINITY; int side = 0; for (unsigned int i = 0; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY) { p0 = endpoint.p; continue; } Arc arc (p0, endpoint.p, endpoint.d); p0 = endpoint.p; if (arc.wedge_contains_point (c)) { double sdist = arc.distance_to_point (c); /* TODO This distance has the wrong sign. Fix */ double udist = fabs (sdist) * (1 - GLYPHY_EPSILON); if (udist <= min_dist) { min_dist = udist; side = sdist >= 0 ? -1 : +1; } } else { double udist = std::min ((arc.p0 - c).len (), (arc.p1 - c).len ()); if (udist < min_dist) { min_dist = udist; side = 0; /* unsure */ closest_arc = arc; } else if (side == 0 && udist == min_dist) { /* If this new distance is the same as the current minimum, * compare extended distances. Take the sign from the arc * with larger extended distance. */ double old_ext_dist = closest_arc.extended_dist (c); double new_ext_dist = arc.extended_dist (c); double ext_dist = fabs (new_ext_dist) <= fabs (old_ext_dist) ? old_ext_dist : new_ext_dist; /* For emboldening and stuff: */ // min_dist = fabs (ext_dist); side = ext_dist >= 0 ? +1 : -1; } } } if (side == 0) { // Technically speaking this should not happen, but it does. So try to fix it. double ext_dist = closest_arc.extended_dist (c); side = ext_dist >= 0 ? +1 : -1; } return side * min_dist; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" #include "glyphy-geometry.hh" using namespace GLyphy::Geometry; void glyphy_outline_reverse (glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints) { if (!num_endpoints) return; // Shift the d's first double d0 = endpoints[0].d; for (unsigned int i = 0; i < num_endpoints - 1; i++) endpoints[i].d = endpoints[i + 1].d == GLYPHY_INFINITY ? GLYPHY_INFINITY : -endpoints[i + 1].d; endpoints[num_endpoints - 1].d = d0; // Reverse for (unsigned int i = 0, j = num_endpoints - 1; i < j; i++, j--) { glyphy_arc_endpoint_t t = endpoints[i]; endpoints[i] = endpoints[j]; endpoints[j] = t; } } static bool winding (const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints) { /* * Algorithm: * * - Find the lowest-x part of the contour, * - If the point is an endpoint: * o compare the angle of the incoming and outgoing edges of that point * to find out whether it's CW or CCW, * - Otherwise, compare the y of the two endpoints of the arc with lowest-x point. * * Note: * * We can use a simpler algorithm here: Act as if arcs are lines, then use the * triangle method to calculate the signed area of the contour and get the sign. * It should work for all cases we care about. The only case failing would be * that of two endpoints and two arcs. But we can even special-case that. */ unsigned int corner = 1; for (unsigned int i = 2; i < num_endpoints; i++) if (endpoints[i].p.x < endpoints[corner].p.x || (endpoints[i].p.x == endpoints[corner].p.x && endpoints[i].p.y < endpoints[corner].p.y)) corner = i; double min_x = endpoints[corner].p.x; int winner = -1; Point p0 (0, 0); for (unsigned int i = 0; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY || endpoint.d == 0 /* arcs only, not lines */) { p0 = endpoint.p; continue; } Arc arc (p0, endpoint.p, endpoint.d); p0 = endpoint.p; Point c = arc.center (); double r = arc.radius (); if (c.x - r < min_x && arc.wedge_contains_point (c - Vector (r, 0))) { min_x = c.x - r; winner = i; } } if (winner == -1) { // Corner is lowest-x. Find the tangents of the two arcs connected to the // corner and compare the tangent angles to get contour direction. const glyphy_arc_endpoint_t ethis = endpoints[corner]; const glyphy_arc_endpoint_t eprev = endpoints[corner - 1]; const glyphy_arc_endpoint_t enext = endpoints[corner < num_endpoints - 1 ? corner + 1 : 1]; double in = (-Arc (eprev.p, ethis.p, ethis.d).tangents ().second).angle (); double out = (+Arc (ethis.p, enext.p, enext.d).tangents ().first ).angle (); return out > in; } else { // Easy. return endpoints[winner].d < 0; } return false; } static int categorize (double v, double ref) { return v < ref - GLYPHY_EPSILON ? -1 : v > ref + GLYPHY_EPSILON ? +1 : 0; } static bool is_zero (double v) { return fabs (v) < GLYPHY_EPSILON; } static bool even_odd (const glyphy_arc_endpoint_t *c_endpoints, unsigned int num_c_endpoints, const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints) { /* * Algorithm: * * - For a point on the contour, draw a halfline in a direction * (eg. decreasing x) to infinity, * - Count how many times it crosses all other contours, * - Pay special attention to points falling exactly on the halfline, * specifically, they count as +.5 or -.5, depending the direction * of crossing. * * All this counting is extremely tricky: * * - Floating point equality cannot be relied on here, * - Lots of arc analysis needed, * - Without having a point that we know falls /inside/ the contour, * there are legitimate cases that we simply cannot handle using * this algorithm. For example, imagine the following glyph shape: * * +---------+ * | +-----+ | * | \ / | * | \ / | * +----o----+ * * If the glyph is defined as two outlines, and when analysing the * inner outline we happen to pick the point denoted by 'o' for * analysis, there simply is no way to differentiate this case from * the following case: * * +---------+ * | | * | | * | | * +----o----+ * / \ * / \ * +-----+ * * However, in one, the triangle should be filled in, and in the other * filled out. * * One way to work around this may be to do the analysis for all endpoints * on the outline and take majority. But even that can fail in more * extreme yet legitimate cases, such as this one: * * +--+--+ * | / \ | * |/ \| * + + * |\ /| * | \ / | * +--o--+ * * The only correct algorithm I can think of requires a point that falls * fully inside the outline. While we can try finding such a point (not * dissimilar to the winding algorithm), it's beyond what I'm willing to * implement right now. */ const Point p = c_endpoints[0].p; double count = 0; Point p0 (0, 0); for (unsigned int i = 0; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY) { p0 = endpoint.p; continue; } Arc arc (p0, endpoint.p, endpoint.d); p0 = endpoint.p; /* * Skip our own contour */ if (&endpoint >= c_endpoints && &endpoint < c_endpoints + num_c_endpoints) continue; /* End-point y's compared to the ref point; lt, eq, or gt */ unsigned s0 = categorize (arc.p0.y, p.y); unsigned s1 = categorize (arc.p1.y, p.y); if (is_zero (arc.d)) { /* Line */ if (!s0 || !s1) { /* * Add +.5 / -.5 for each endpoint on the halfline, depending on * crossing direction. */ Pair<Vector> t = arc.tangents (); if (!s0 && arc.p0.x < p.x + GLYPHY_EPSILON) count += .5 * categorize (t.first.dy, 0); if (!s1 && arc.p1.x < p.x + GLYPHY_EPSILON) count += .5 * categorize (t.second.dy, 0); continue; } if (s0 == s1) continue; // Segment fully above or below the halfline // Find x pos that the line segment would intersect the half-line. double x = arc.p0.x + (arc.p1.x - arc.p0.x) * ((p.y - arc.p0.y) / (arc.p1.y - arc.p0.y)); if (x >= p.x - GLYPHY_EPSILON) continue; // Does not intersect halfline count++; // Add one for full crossing continue; } else { /* Arc */ if (!s0 || !s1) { /* * Add +.5 / -.5 for each endpoint on the halfline, depending on * crossing direction. */ Pair<Vector> t = arc.tangents (); /* Arc-specific logic: * If the tangent has dy==0, use the other endpoint's * y value to decide which way the arc will be heading. */ if (is_zero (t.first.dy)) t.first.dy = +categorize (arc.p1.y, p.y); if (is_zero (t.second.dy)) t.second.dy = -categorize (arc.p0.y, p.y); if (!s0 && arc.p0.x < p.x + GLYPHY_EPSILON) count += .5 * categorize (t.first.dy, 0); if (!s1 && arc.p1.x < p.x + GLYPHY_EPSILON) count += .5 * categorize (t.second.dy, 0); } Point c = arc.center (); double r = arc.radius (); if (c.x - r >= p.x) continue; // No chance /* Solve for arc crossing line with y = p.y */ double dy = p.y - c.y; double x2 = r * r - dy * dy; if (x2 <= GLYPHY_EPSILON) continue; // Negative delta, no crossing double dx = sqrt (x2); /* There's two candidate points on the arc with the same y as the * ref point. */ Point pp[2] = { Point (c.x - dx, p.y), Point (c.x + dx, p.y) }; #define POINTS_EQ(a,b) (is_zero (a.x - b.x) && is_zero (a.y - b.y)) for (unsigned int i = 0; i < ARRAY_LENGTH (pp); i++) { /* Make sure we don't double-count endpoints that fall on the * halfline as we already accounted for those above */ if (!POINTS_EQ (pp[i], arc.p0) && !POINTS_EQ (pp[i], arc.p1) && pp[i].x < p.x - GLYPHY_EPSILON && arc.wedge_contains_point (pp[i])) count++; // Add one for full crossing } #undef POINTS_EQ } } return !(int (floor (count)) & 1); } static bool process_contour (glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, const glyphy_arc_endpoint_t *all_endpoints, unsigned int num_all_endpoints, bool inverse) { /* * Algorithm: * * - Find the winding direction and even-odd number, * - If the two disagree, reverse the contour, inplace. */ if (!num_endpoints) return false; if (num_endpoints < 3) { abort (); // Don't expect this return false; // Need at least two arcs } if (Point (endpoints[0].p) != Point (endpoints[num_endpoints-1].p)) { abort (); // Don't expect this return false; // Need a closed contour } if (inverse ^ winding (endpoints, num_endpoints) ^ even_odd (endpoints, num_endpoints, all_endpoints, num_all_endpoints)) { glyphy_outline_reverse (endpoints, num_endpoints); return true; } return false; } /* Returns true if outline was modified */ glyphy_bool_t glyphy_outline_winding_from_even_odd (glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, glyphy_bool_t inverse) { /* * Algorithm: * * - Process one contour at a time. */ unsigned int start = 0; bool ret = false; for (unsigned int i = 1; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY) { ret = ret | process_contour (endpoints + start, i - start, endpoints, num_endpoints, bool (inverse)); start = i; } } ret = ret | process_contour (endpoints + start, num_endpoints - start, endpoints, num_endpoints, bool (inverse)); return ret; }
C++
/* * Copyright 2012,2013 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju */ #ifndef GLYPHY_ARC_BEZIER_HH #define GLYPHY_ARC_BEZIER_HH #include "glyphy-common.hh" #include "glyphy-geometry.hh" namespace GLyphy { namespace ArcBezier { using namespace Geometry; class MaxDeviationApproximatorExact { public: /* Returns 3 max(abs(d₀ t (1-t)² + d₁ t² (1-t)) for 0≤t≤1. */ static double approximate_deviation (double d0, double d1) { double candidates[4] = {0,1}; unsigned int num_candidates = 2; if (d0 == d1) candidates[num_candidates++] = .5; else { double delta = d0*d0 - d0*d1 + d1*d1; double t2 = 1. / (3 * (d0 - d1)); double t0 = (2 * d0 - d1) * t2; if (delta == 0) candidates[num_candidates++] = t0; else if (delta > 0) { /* This code can be optimized to avoid the sqrt if the solution * is not feasible (ie. lies outside (0,1)). I have implemented * that in cairo-spline.c:_cairo_spline_bound(). Can be reused * here. */ double t1 = sqrt (delta) * t2; candidates[num_candidates++] = t0 - t1; candidates[num_candidates++] = t0 + t1; } } double e = 0; for (unsigned int i = 0; i < num_candidates; i++) { double t = candidates[i]; double ee; if (t < 0. || t > 1.) continue; ee = fabs (3 * t * (1-t) * (d0 * (1 - t) + d1 * t)); e = std::max (e, ee); } return e; } }; template <class MaxDeviationApproximator> class ArcBezierErrorApproximatorBehdad { public: static double approximate_bezier_arc_error (const Bezier &b0, const Arc &a) { assert (b0.p0 == a.p0); assert (b0.p3 == a.p1); double ea; Bezier b1 = a.approximate_bezier (&ea); assert (b0.p0 == b1.p0); assert (b0.p3 == b1.p3); Vector v0 = b1.p1 - b0.p1; Vector v1 = b1.p2 - b0.p2; Vector b = (b0.p3 - b0.p0).normalized (); v0 = v0.rebase (b); v1 = v1.rebase (b); Vector v (MaxDeviationApproximator::approximate_deviation (v0.dx, v1.dx), MaxDeviationApproximator::approximate_deviation (v0.dy, v1.dy)); /* Edge cases: If d*d is too close too large default to a weak bound. */ if (a.d * a.d > 1. - 1e-4) return ea + v.len (); /* If the wedge doesn't contain control points, default to weak bound. */ if (!a.wedge_contains_point (b0.p1) || !a.wedge_contains_point (b0.p2)) return ea + v.len (); /* If straight line, return the max ortho deviation. */ if (fabs (a.d) < 1e-6) return ea + v.dy; /* We made sure that fabs(a.d) < 1 */ double tan_half_alpha = fabs (tan2atan (a.d)); double tan_v = v.dx / v.dy; double eb; if (fabs (tan_v) <= tan_half_alpha) return ea + v.len (); double c2 = (a.p1 - a.p0).len () * .5; double r = a.radius (); eb = Vector (c2 + v.dx, c2 / tan_half_alpha + v.dy).len () - r; assert (eb >= 0); return ea + eb; } }; template <class ArcBezierErrorApproximator> class ArcBezierApproximatorMidpointSimple { public: static const Arc approximate_bezier_with_arc (const Bezier &b, double *error) { Arc a (b.p0, b.p3, b.midpoint (), false); *error = ArcBezierErrorApproximator::approximate_bezier_arc_error (b, a); return a; } }; template <class ArcBezierErrorApproximator> class ArcBezierApproximatorMidpointTwoPart { public: static const Arc approximate_bezier_with_arc (const Bezier &b, double *error, double mid_t = .5) { Pair<Bezier > pair = b.split (mid_t); Point m = pair.second.p0; Arc a0 (b.p0, m, b.p3, true); Arc a1 (m, b.p3, b.p0, true); double e0 = ArcBezierErrorApproximator::approximate_bezier_arc_error (pair.first, a0); double e1 = ArcBezierErrorApproximator::approximate_bezier_arc_error (pair.second, a1); *error = std::max (e0, e1); return Arc (b.p0, b.p3, m, false); } }; template <class ArcBezierErrorApproximator> class ArcBezierApproximatorQuantized { public: ArcBezierApproximatorQuantized (double _max_d = GLYPHY_INFINITY, unsigned int _d_bits = 0) : max_d (_max_d), d_bits (_d_bits) {}; protected: double max_d; unsigned int d_bits; public: const Arc approximate_bezier_with_arc (const Bezier &b, double *error) const { double mid_t = .5; Arc a (b.p0, b.p3, b.point (mid_t), false); Arc orig_a = a; if (isfinite (max_d)) { assert (max_d >= 0); if (fabs (a.d) > max_d) a.d = a.d < 0 ? -max_d : max_d; } if (d_bits && max_d != 0) { assert (isfinite (max_d)); assert (fabs (a.d) <= max_d); int mult = (1 << (d_bits - 1)) - 1; int id = round (a.d / max_d * mult); assert (-mult <= id && id <= mult); a.d = id * max_d / mult; assert (fabs (a.d) <= max_d); } /* Error introduced by arc quantization */ double ed = fabs (a.d - orig_a.d) * (a.p1 - a.p0).len () * .5; ArcBezierApproximatorMidpointTwoPart<ArcBezierErrorApproximator> ::approximate_bezier_with_arc (b, error, mid_t); if (ed) { *error += ed; /* Try a simple one-arc approx which works with the quantized arc. * May produce smaller error bound. */ double e = ArcBezierErrorApproximator::approximate_bezier_arc_error (b, a); if (e < *error) *error = e; } return a; } }; typedef MaxDeviationApproximatorExact MaxDeviationApproximatorDefault; typedef ArcBezierErrorApproximatorBehdad<MaxDeviationApproximatorDefault> ArcBezierErrorApproximatorDefault; typedef ArcBezierApproximatorMidpointTwoPart<ArcBezierErrorApproximatorDefault> ArcBezierApproximatorDefault; typedef ArcBezierApproximatorQuantized<ArcBezierErrorApproximatorDefault> ArcBezierApproximatorQuantizedDefault; } /* namespace ArcBezier */ } /* namespace GLyphy */ #endif /* GLYPHY_ARC_BEZIER_HH */
C++
/* * Copyright 2012,2013 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju */ #ifndef GLYPHY_GEOMETRY_HH #define GLYPHY_GEOMETRY_HH #include "glyphy-common.hh" namespace GLyphy { namespace Geometry { template <typename Type> struct Pair; struct Vector; struct SignedVector; struct Point; struct Line; struct Segment; struct Arc; struct Bezier; /* returns tan (2 * atan (d)) */ inline double tan2atan (double d) { return 2 * d / (1 - d*d); } /* returns sin (2 * atan (d)) */ inline double sin2atan (double d) { return 2 * d / (1 + d*d); } /* returns cos (2 * atan (d)) */ inline double cos2atan (double d) { return (1 - d*d) / (1 + d*d); } template <typename Type> struct Pair { typedef Type ElementType; inline Pair (const Type &first_, const Type &second_) : first (first_), second (second_) {} Type first, second; }; struct Point : glyphy_point_t { inline Point (double x_, double y_) { x = x_; y = y_; } inline explicit Point (const Vector &v); inline Point (const glyphy_point_t &p) { *(glyphy_point_t *)this = p; } inline bool operator == (const Point &p) const; inline bool operator != (const Point &p) const; inline Point& operator+= (const Vector &v); inline Point& operator-= (const Vector &v); inline const Point operator+ (const Vector &v) const; inline const Point operator- (const Vector &v) const; inline const Vector operator- (const Point &p) const; inline const Point midpoint (const Point &p) const; inline const Line bisector (const Point &p) const; inline double distance_to_point (const Point &p) const; /* distance to point! */ inline double squared_distance_to_point (const Point &p) const; /* square of distance to point! */ inline bool is_finite (void) const; inline const Point lerp (const double &a, const Point &p) const; }; struct Vector { inline Vector (double dx_, double dy_) : dx (dx_), dy (dy_) {} inline explicit Vector (const Point &p) : dx (p.x), dy (p.y) {} inline bool operator == (const Vector &v) const; inline bool operator != (const Vector &v) const; inline const Vector operator+ (void) const; inline const Vector operator- (void) const; inline Vector& operator+= (const Vector &v); inline Vector& operator-= (const Vector &v); inline Vector& operator*= (const double &s); inline Vector& operator/= (const double &s); inline const Vector operator+ (const Vector &v) const; inline const Vector operator- (const Vector &v) const; inline const Vector operator* (const double &s) const; inline const Vector operator/ (const double &s) const; inline double operator* (const Vector &v) const; /* dot product */ inline const Point operator+ (const Point &p) const; inline bool is_nonzero (void) const; inline double len (void) const; inline double len2 (void) const; inline const Vector normalized (void) const; inline const Vector ortho (void) const; inline const Vector normal (void) const; /* ortho().normalized() */ inline double angle (void) const; inline const Vector rebase (const Vector &bx, const Vector &by) const; inline const Vector rebase (const Vector &bx) const; double dx, dy; }; struct SignedVector : Vector { inline SignedVector (const Vector &v, bool negative_) : Vector (v), negative (negative_) {} inline bool operator == (const SignedVector &v) const; inline bool operator != (const SignedVector &v) const; inline const SignedVector operator- (void) const; bool negative; }; struct Line { inline Line (double a_, double b_, double c_) : n (a_, b_), c (c_) {} inline Line (Vector n_, double c_) : n (n_), c (c_) {} inline Line (const Point &p0, const Point &p1) : n ((p1 - p0).ortho ()), c (n * Vector (p0)) {} inline const Point operator+ (const Line &l) const; /* line intersection! */ inline const SignedVector operator- (const Point &p) const; /* shortest vector from point to line */ inline const Line normalized (void) const; inline const Vector normal (void) const; Vector n; /* line normal */ double c; /* n.dx*x + n.dy*y = c */ }; struct Segment { inline Segment (const Point &p0_, const Point &p1_) : p0 (p0_), p1 (p1_) {} inline const SignedVector operator- (const Point &p) const; /* shortest vector from point to ***line*** */ inline double distance_to_point (const Point &p) const; /* shortest distance from point to segment */ inline double squared_distance_to_point (const Point &p) const; /* shortest distance squared from point to segment */ inline bool contains_in_span (const Point &p) const; /* is p in the stripe formed by sliding this segment? */ inline double max_distance_to_arc (const Arc &a) const; Point p0; Point p1; }; struct Arc { inline Arc (const Point &p0_, const Point &p1_, const Point &pm, bool complement) : p0 (p0_), p1 (p1_), d (p0_ == pm || p1_ == pm ? 0 : tan (((p1_-pm).angle () - (p0_-pm).angle ()) / 2 - (complement ? 0 : M_PI_2))) {} inline Arc (const Point &p0_, const Point &p1_, const double &d_) : p0 (p0_), p1 (p1_), d (d_) {} inline Arc (const Point &center, double radius, const double &a0, const double &a1, bool complement) : p0 (center + Vector (cos(a0),sin(a0)) * radius), p1 (center + Vector (cos(a1),sin(a1)) * radius), d (tan ((a1 - a0) / 4 - (complement ? 0 : M_PI_2))) {} inline Arc (const glyphy_arc_t &a) : p0 (a.p0), p1 (a.p1), d (a.d) {} inline operator glyphy_arc_t (void) const { glyphy_arc_t a = {p0, p1, d}; return a; } inline bool operator == (const Arc &a) const; inline bool operator != (const Arc &a) const; inline const SignedVector operator- (const Point &p) const; /* shortest vector from point to arc */ inline double radius (void) const; inline const Point center (void) const; inline const Pair<Vector> tangents (void) const; inline Bezier approximate_bezier (double *error) const; inline bool wedge_contains_point (const Point &p) const; inline double distance_to_point (const Point &p) const; inline double squared_distance_to_point (const Point &p) const; inline double extended_dist (const Point &p) const; inline void extents (glyphy_extents_t &extents) const; Point p0, p1; double d; /* Depth */ }; struct Bezier { inline Bezier (const Point &p0_, const Point &p1_, const Point &p2_, const Point &p3_) : p0 (p0_), p1 (p1_), p2 (p2_), p3 (p3_) {} inline const Point point (const double &t) const; inline const Point midpoint (void) const; inline const Vector tangent (const double &t) const; inline const Vector d_tangent (const double &t) const; inline double curvature (const double &t) const; inline const Pair<Bezier> split (const double &t) const; inline const Pair<Bezier> halve (void) const; inline const Bezier segment (const double &t0, const double &t1) const; Point p0, p1, p2, p3; }; /* Implementations */ /* Point */ inline Point::Point (const Vector &v) { x = v.dx; y = v.dy; } inline bool Point::operator == (const Point &p) const { return x == p.x && y == p.y; } inline bool Point::operator != (const Point &p) const { return !(*this == p); } inline Point& Point::operator+= (const Vector &v) { x += v.dx; y += v.dy; return *this; } inline Point& Point::operator-= (const Vector &v) { x -= v.dx; y -= v.dy; return *this; } inline const Point Point::operator+ (const Vector &v) const { return Point (*this) += v; } inline const Point Point::operator- (const Vector &v) const { return Point (*this) -= v; } inline const Vector Point::operator- (const Point &p) const { return Vector (x - p.x, y - p.y); } inline const Point Point::midpoint (const Point &p) const { return *this + (p - *this) / 2; } inline const Line Point::bisector (const Point &p) const { Vector d = p - *this; return Line (d.dx * 2, d.dy * 2, d * Vector (p) + d * Vector (*this)); } inline double Point::distance_to_point (const Point &p) const { return ((*this) - p).len (); } inline double Point::squared_distance_to_point (const Point &p) const { return ((*this) - p).len2 (); } inline bool Point::is_finite (void) const { return isfinite (x) && isfinite (y); } inline const Point Point::lerp (const double &a, const Point &p) const { /* The following two cases are special-cased to get better floating * point stability. We require that points that are the same be * bit-equal. */ if (a == 0) return *this; if (a == 1.0) return p; return Point ((1-a) * x + a * p.x, (1-a) * y + a * p.y); } /* Vector */ inline bool Vector::operator == (const Vector &v) const { return dx == v.dx && dy == v.dy; } inline bool Vector::operator != (const Vector &v) const { return !(*this == v); } inline const Vector Vector::operator+ (void) const { return *this; } inline const Vector Vector::operator- (void) const { return Vector (-dx, -dy); } inline Vector& Vector::operator+= (const Vector &v) { dx += v.dx; dy += v.dy; return *this; } inline Vector& Vector::operator-= (const Vector &v) { dx -= v.dx; dy -= v.dy; return *this; } inline Vector& Vector::operator*= (const double &s) { dx *= s; dy *= s; return *this; } inline Vector& Vector::operator/= (const double &s) { dx /= s; dy /= s; return *this; } inline const Vector Vector::operator+ (const Vector &v) const { return Vector (*this) += v; } inline const Vector Vector::operator- (const Vector &v) const { return Vector (*this) -= v; } inline const Vector Vector::operator* (const double &s) const { return Vector (*this) *= s; } inline const Vector operator* (const double &s, const Vector &v) { return v * s; } inline const Vector Vector::operator/ (const double &s) const { return Vector (*this) /= s; } inline double Vector::operator* (const Vector &v) const { /* dot product */ return dx * v.dx + dy * v.dy; } inline const Point Vector::operator+ (const Point &p) const { return p + *this; } inline bool Vector::is_nonzero (void) const { return dx || dy; } inline double Vector::len (void) const { return hypot (dx, dy); } inline double Vector::len2 (void) const { return dx * dx + dy * dy; } inline const Vector Vector::normalized (void) const { double d = len (); return d ? *this / d : *this; } inline const Vector Vector::ortho (void) const { return Vector (-dy, dx); } inline const Vector Vector::normal (void) const { return ortho ().normalized (); } inline double Vector::angle (void) const { return atan2 (dy, dx); } inline const Vector Vector::rebase (const Vector &bx, const Vector &by) const { return Vector (*this * bx, *this * by); } inline const Vector Vector::rebase (const Vector &bx) const { return rebase (bx, bx.ortho ()); } /* SignedVector */ inline bool SignedVector::operator == (const SignedVector &v) const { return (const Vector &)(*this) == (const Vector &)(v) && negative == v.negative; } inline bool SignedVector::operator != (const SignedVector &v) const { return !(*this == v); } inline const SignedVector SignedVector::operator- (void) const { return SignedVector (-(const Vector &)(*this), !negative); } /* Line */ inline const Point Line::operator+ (const Line &l) const { double det = n.dx * l.n.dy - n.dy * l.n.dx; if (!det) return Point (GLYPHY_INFINITY, GLYPHY_INFINITY); return Point ((c * l.n.dy - n.dy * l.c) / det, (n.dx * l.c - c * l.n.dx) / det); } inline const SignedVector Line::operator- (const Point &p) const { double mag = -(n * Vector (p) - c) / n.len (); return SignedVector (n.normalized () * mag, mag < 0); /******************************************************************************************* FIX. *************************************/ } inline const SignedVector operator- (const Point &p, const Line &l) { return -(l - p); } inline const Line Line::normalized (void) const { double d = n.len (); return d ? Line (n / d, c / d) : *this; } inline const Vector Line::normal (void) const { return n; } /* Segment */ inline const SignedVector Segment::operator- (const Point &p) const { /* shortest vector from point to line */ return p - Line (p1, p0); /************************************************************************************************** Should the order (p1, p0) depend on d?? ***********************/ } /* Segment */ inline bool Segment::contains_in_span (const Point &p) const { if (p0 == p1) return false; /* shortest vector from point to line */ Line temp (p0, p1); double mag = -(temp.n * Vector (p) - temp.c) / temp.n.len (); Vector y (temp.n.normalized () * mag); Point z = y + p; // Check if z is between p0 and p1. if (fabs (p1.y - p0.y) > fabs (p1.x - p0.x)) { return ((z.y - p0.y > 0 && p1.y - p0.y > z.y - p0.y) || (z.y - p0.y < 0 && p1.y - p0.y < z.y - p0.y)); } else { return ((0 < z.x - p0.x && z.x - p0.x < p1.x - p0.x) || (0 > z.x - p0.x && z.x - p0.x > p1.x - p0.x)); } } inline double Segment::distance_to_point (const Point &p) const { if (p0 == p1) return 0; // Check if z is between p0 and p1. Line temp (p0, p1); if (contains_in_span (p)) return -(temp.n * Vector (p) - temp.c) / temp.n.len (); double dist_p_p0 = p.distance_to_point (p0); double dist_p_p1 = p.distance_to_point (p1); return (dist_p_p0 < dist_p_p1 ? dist_p_p0 : dist_p_p1) * (-(temp.n * Vector (p) - temp.c) < 0 ? -1 : 1); } inline double Segment::squared_distance_to_point (const Point &p) const { if (p0 == p1) return 0; // Check if z is between p0 and p1. Line temp (p0, p1); if (contains_in_span (p)) return (temp.n * Vector (p) - temp.c) * (temp.n * Vector (p) - temp.c) / (temp.n * temp.n); double dist_p_p0 = p.squared_distance_to_point (p0); double dist_p_p1 = p.squared_distance_to_point (p1); return (dist_p_p0 < dist_p_p1 ? dist_p_p0 : dist_p_p1); } inline double Segment::max_distance_to_arc (const Arc &a) const { double max_distance = fabs(a.distance_to_point(p0)) ; return max_distance > fabs(a.distance_to_point(p1)) ? max_distance : fabs(a.distance_to_point(p1)) ; } /* Arc */ inline bool Arc::operator == (const Arc &a) const { return p0 == a.p0 && p1 == a.p1 && d == a.d; } inline bool Arc::operator != (const Arc &a) const { return !(*this == a); } inline const SignedVector Arc::operator- (const Point &p) const { if (fabs(d) < 1e-5) { Segment arc_segment (p0, p1); return arc_segment - p; } if (wedge_contains_point (p)){ Vector difference = (center () - p).normalized () * fabs (p.distance_to_point (center ()) - radius ()); return SignedVector (difference, ((p - center ()).len () < radius ()) ^ (d < 0)); } double d0 = p.squared_distance_to_point (p0); double d1 = p.squared_distance_to_point (p1); Arc other_arc (p0, p1, (1.0 + d) / (1.0 - d)); /********************************* NOT Robust. But works? *****************/ Vector normal = center () - (d0 < d1 ? p0 : p1) ; if (normal.len() == 0) return SignedVector (Vector (0, 0), true); /************************************ Check sign of this S.D. *************/ return SignedVector (Line (normal.dx, normal.dy, normal * Vector ((d0 < d1 ? p0 : p1))) - p, !other_arc.wedge_contains_point(p)); } inline const SignedVector operator- (const Point &p, const Arc &a) { return -(a - p); } inline double Arc::radius (void) const { return fabs ((p1 - p0).len () / (2 * sin2atan (d))); } inline const Point Arc::center (void) const { return (p0.midpoint (p1)) + (p1 - p0).ortho () / (2 * tan2atan (d)); } inline const Pair<Vector> Arc::tangents (void) const { Vector dp = (p1 - p0) * .5; Vector pp = dp.ortho () * -sin2atan (d); dp = dp * cos2atan (d); return Pair<Vector> (dp + pp, dp - pp); } inline Bezier Arc::approximate_bezier (double *error) const { Vector dp = p1 - p0; Vector pp = dp.ortho (); if (error) *error = dp.len () * pow (fabs (d), 5) / (54 * (1 + d*d)); dp *= ((1 - d*d) / 3); pp *= (2 * d / 3); Point p0s = p0 + dp - pp; Point p1s = p1 - dp - pp; return Bezier (p0, p0s, p1s, p1); } inline bool Arc::wedge_contains_point (const Point &p) const { Pair<Vector> t = tangents (); if (fabs (d) <= 1) return (p - p0) * t.first >= 0 && (p - p1) * t.second <= 0; else return (p - p0) * t.first >= 0 || (p - p1) * t.second <= 0; } /* Distance may not always be positive, but will be to an endpoint whenever necessary. */ inline double Arc::distance_to_point (const Point &p) const { if (fabs(d) < 1e-5) { Segment arc_segment (p0, p1); return arc_segment.distance_to_point (p); } SignedVector difference = *this - p; if (wedge_contains_point (p) && fabs(d) > 1e-5) return fabs (p.distance_to_point (center ()) - radius ()) * (difference.negative ? -1 : 1); double d1 = p.squared_distance_to_point (p0); double d2 = p.squared_distance_to_point (p1); return (d1 < d2 ? sqrt(d1) : sqrt(d2)) * (difference.negative ? -1 : 1); } /* Distance will be to an endpoint whenever necessary. */ inline double Arc::squared_distance_to_point (const Point &p) const { if (fabs(d) < 1e-5) { Segment arc_segment (p0, p1); return arc_segment.squared_distance_to_point (p); } //SignedVector difference = *this - p; if (wedge_contains_point (p) && fabs(d) > 1e-5) { double answer = p.distance_to_point (center ()) - radius (); return answer * answer; } double d1 = p.squared_distance_to_point (p0); double d2 = p.squared_distance_to_point (p1); return (d1 < d2 ? d1 : d2); } inline double Arc::extended_dist (const Point &p) const { Point m = p0.lerp (.5, p1); Vector dp = p1 - p0; Vector pp = dp.ortho (); float d2 = tan2atan (d); if ((p - m) * (p1 - m) < 0) return (p - p0) * (pp + dp * d2).normalized (); else return (p - p1) * (pp - dp * d2).normalized (); } inline void Arc::extents (glyphy_extents_t &extents) const { glyphy_extents_clear (&extents); glyphy_extents_add (&extents, &p0); glyphy_extents_add (&extents, &p1); Point c = center (); double r = radius (); Point p[4] = {c + r * Vector (-1, 0), c + r * Vector (+1, 0), c + r * Vector ( 0, -1), c + r * Vector ( 0, +1)}; for (unsigned int i = 0; i < 4; i++) if (wedge_contains_point (p[i])) glyphy_extents_add (&extents, &p[i]); } /* Bezier */ inline const Point Bezier::point (const double &t) const { Point p01 = p0.lerp (t, p1); Point p12 = p1.lerp (t, p2); Point p23 = p2.lerp (t, p3); Point p012 = p01.lerp (t, p12); Point p123 = p12.lerp (t, p23); Point p0123 = p012.lerp (t, p123); return p0123; } inline const Point Bezier::midpoint (void) const { Point p01 = p0.midpoint (p1); Point p12 = p1.midpoint (p2); Point p23 = p2.midpoint (p3); Point p012 = p01.midpoint (p12); Point p123 = p12.midpoint (p23); Point p0123 = p012.midpoint (p123); return p0123; } inline const Vector Bezier::tangent (const double &t) const { double t_2_0 = t * t; double t_0_2 = (1 - t) * (1 - t); double _1__4t_1_0_3t_2_0 = 1 - 4 * t + 3 * t_2_0; double _2t_1_0_3t_2_0 = 2 * t - 3 * t_2_0; return Vector (-3 * p0.x * t_0_2 +3 * p1.x * _1__4t_1_0_3t_2_0 +3 * p2.x * _2t_1_0_3t_2_0 +3 * p3.x * t_2_0, -3 * p0.y * t_0_2 +3 * p1.y * _1__4t_1_0_3t_2_0 +3 * p2.y * _2t_1_0_3t_2_0 +3 * p3.y * t_2_0); } inline const Vector Bezier::d_tangent (const double &t) const { return Vector (6 * ((-p0.x + 3*p1.x - 3*p2.x + p3.x) * t + (p0.x - 2*p1.x + p2.x)), 6 * ((-p0.y + 3*p1.y - 3*p2.y + p3.y) * t + (p0.y - 2*p1.y + p2.y))); } inline double Bezier::curvature (const double &t) const { Vector dpp = tangent (t).ortho (); Vector ddp = d_tangent (t); /* normal vector len squared */ double len = dpp.len (); double curvature = (dpp * ddp) / (len * len * len); return curvature; } inline const Pair<Bezier > Bezier::split (const double &t) const { Point p01 = p0.lerp (t, p1); Point p12 = p1.lerp (t, p2); Point p23 = p2.lerp (t, p3); Point p012 = p01.lerp (t, p12); Point p123 = p12.lerp (t, p23); Point p0123 = p012.lerp (t, p123); return Pair<Bezier> (Bezier (p0, p01, p012, p0123), Bezier (p0123, p123, p23, p3)); } inline const Pair<Bezier > Bezier::halve (void) const { Point p01 = p0.midpoint (p1); Point p12 = p1.midpoint (p2); Point p23 = p2.midpoint (p3); Point p012 = p01.midpoint (p12); Point p123 = p12.midpoint (p23); Point p0123 = p012.midpoint (p123); return Pair<Bezier> (Bezier (p0, p01, p012, p0123), Bezier (p0123, p123, p23, p3)); } inline const Bezier Bezier::segment (const double &t0, const double &t1) const { Point p01 = p0.lerp (t0, p1); Point p12 = p1.lerp (t0, p2); Point p23 = p2.lerp (t0, p3); Point p012 = p01.lerp (t0, p12); Point p123 = p12.lerp (t0, p23); Point p0123 = p012.lerp (t0, p123); Point q01 = p0.lerp (t1, p1); Point q12 = p1.lerp (t1, p2); Point q23 = p2.lerp (t1, p3); Point q012 = q01.lerp (t1, q12); Point q123 = q12.lerp (t1, q23); Point q0123 = q012.lerp (t1, q123); return Bezier (p0123, p0123 + (p123 - p0123) * ((t1 - t0) / (1 - t0)), q0123 + (q012 - q0123) * ((t1 - t0) / t1), q0123); } } /* namespace Geometry */ } /* namespace GLyphy */ #endif /* GLYPHY_GEOMETRY_HH */
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" /* * Shader source code */ /* TODO path separator */ #define SHADER_PATH(File) PKGDATADIR "/" File #include "glyphy-common-glsl.h" #include "glyphy-sdf-glsl.h" const char * glyphy_common_shader_source (void) { return glyphy_common_glsl; } const char * glyphy_sdf_shader_source (void) { return glyphy_sdf_glsl; } const char * glyphy_common_shader_source_path (void) { return SHADER_PATH ("glyphy-common.glsl"); } const char * glyphy_sdf_shader_source_path (void) { return SHADER_PATH ("glyphy-sdf.glsl"); }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju */ #ifndef GLYPHY_COMMON_HH #define GLYPHY_COMMON_HH #include <glyphy.h> #include <math.h> #include <string.h> #include <assert.h> #include <stdio.h> #include <vector> #include <algorithm> #ifndef GLYPHY_EPSILON # define GLYPHY_EPSILON 1e-5 #endif #ifndef GLYPHY_INFINITY # define GLYPHY_INFINITY INFINITY #endif static inline bool iszero (double v) { return fabs (v) < 2 * GLYPHY_EPSILON; } #define GLYPHY_MAX_D .5 #undef ARRAY_LENGTH #define ARRAY_LENGTH(__array) ((signed int) (sizeof (__array) / sizeof (__array[0]))) #define _ASSERT_STATIC1(_line, _cond) typedef int _static_assert_on_line_##_line##_failed[(_cond)?1:-1] #define _ASSERT_STATIC0(_line, _cond) _ASSERT_STATIC1 (_line, (_cond)) #define ASSERT_STATIC(_cond) _ASSERT_STATIC0 (__LINE__, (_cond)) #ifdef __ANDROID__ #define log2(x) (log(x) / log(2.0)) #endif #endif /* GLYPHY_COMMON_HH */
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glyphy-common.hh" #include "glyphy-geometry.hh" #include "glyphy-arcs-bezier.hh" using namespace GLyphy::Geometry; using namespace GLyphy::ArcsBezier; /* * Approximate outlines with multiple arcs */ struct glyphy_arc_accumulator_t { unsigned int refcount; double tolerance; double max_d; unsigned int d_bits; glyphy_arc_endpoint_accumulator_callback_t callback; void *user_data; glyphy_point_t start_point; glyphy_point_t current_point; bool need_moveto; unsigned int num_endpoints; double max_error; glyphy_bool_t success; }; glyphy_arc_accumulator_t * glyphy_arc_accumulator_create (void) { glyphy_arc_accumulator_t *acc = (glyphy_arc_accumulator_t *) calloc (1, sizeof (glyphy_arc_accumulator_t)); acc->refcount = 1; acc->tolerance = 5e-4; acc->max_d = GLYPHY_MAX_D; acc->d_bits = 8; acc->callback = NULL; acc->user_data = NULL; glyphy_arc_accumulator_reset (acc); return acc; } void glyphy_arc_accumulator_reset (glyphy_arc_accumulator_t *acc) { acc->start_point = acc->current_point = Point (0, 0); acc->need_moveto = true; acc->num_endpoints = 0; acc->max_error = 0; acc->success = true; } void glyphy_arc_accumulator_destroy (glyphy_arc_accumulator_t *acc) { if (!acc || --acc->refcount) return; free (acc); } glyphy_arc_accumulator_t * glyphy_arc_accumulator_reference (glyphy_arc_accumulator_t *acc) { if (acc) acc->refcount++; return acc; } /* Configure acc */ void glyphy_arc_accumulator_set_tolerance (glyphy_arc_accumulator_t *acc, double tolerance) { acc->tolerance = tolerance; } double glyphy_arc_accumulator_get_tolerance (glyphy_arc_accumulator_t *acc) { return acc->tolerance; } void glyphy_arc_accumulator_set_callback (glyphy_arc_accumulator_t *acc, glyphy_arc_endpoint_accumulator_callback_t callback, void *user_data) { acc->callback = callback; acc->user_data = user_data; } void glyphy_arc_accumulator_get_callback (glyphy_arc_accumulator_t *acc, glyphy_arc_endpoint_accumulator_callback_t *callback, void **user_data) { *callback = acc->callback; *user_data = acc->user_data; } void glyphy_arc_accumulator_set_d_metrics (glyphy_arc_accumulator_t *acc, double max_d, double d_bits) { acc->max_d = max_d; acc->d_bits = d_bits; } void glyphy_arc_accumulator_get_d_metrics (glyphy_arc_accumulator_t *acc, double *max_d, double *d_bits) { *max_d = acc->max_d; *d_bits = acc->d_bits; } /* Accumulation results */ unsigned int glyphy_arc_accumulator_get_num_endpoints (glyphy_arc_accumulator_t *acc) { return acc->num_endpoints; } double glyphy_arc_accumulator_get_error (glyphy_arc_accumulator_t *acc) { return acc->max_error; } glyphy_bool_t glyphy_arc_accumulator_successful (glyphy_arc_accumulator_t *acc) { return acc->success; } /* Accumulate */ static void emit (glyphy_arc_accumulator_t *acc, const Point &p, double d) { glyphy_arc_endpoint_t endpoint = {p, d}; acc->success = acc->success && acc->callback (&endpoint, acc->user_data); if (acc->success) { acc->num_endpoints++; acc->current_point = p; } } static void accumulate (glyphy_arc_accumulator_t *acc, const Point &p, double d) { if (Point (acc->current_point) == p) return; if (d == GLYPHY_INFINITY) { /* Emit moveto lazily, for cleaner outlines */ acc->need_moveto = true; acc->current_point = p; return; } if (acc->need_moveto) { emit (acc, acc->current_point, GLYPHY_INFINITY); if (acc->success) { acc->start_point = acc->current_point; acc->need_moveto = false; } } emit (acc, p, d); } static void move_to (glyphy_arc_accumulator_t *acc, const Point &p) { if (!acc->num_endpoints || p != acc->current_point) accumulate (acc, p, GLYPHY_INFINITY); } static void arc_to (glyphy_arc_accumulator_t *acc, const Point &p1, double d) { accumulate (acc, p1, d); } static void bezier (glyphy_arc_accumulator_t *acc, const Bezier &b) { double e; std::vector<Arc> arcs; typedef ArcBezierApproximatorQuantizedDefault _ArcBezierApproximator; _ArcBezierApproximator appx (acc->max_d, acc->d_bits); ArcsBezierApproximatorSpringSystem<_ArcBezierApproximator> ::approximate_bezier_with_arcs (b, acc->tolerance, appx, arcs, &e); acc->max_error = std::max (acc->max_error, e); move_to (acc, b.p0); for (unsigned int i = 0; i < arcs.size (); i++) arc_to (acc, arcs[i].p1, arcs[i].d); } static void close_path (glyphy_arc_accumulator_t *acc) { if (!acc->need_moveto && Point (acc->current_point) != Point (acc->start_point)) arc_to (acc, acc->start_point, 0); } void glyphy_arc_accumulator_move_to (glyphy_arc_accumulator_t *acc, const glyphy_point_t *p0) { move_to (acc, *p0); } void glyphy_arc_accumulator_line_to (glyphy_arc_accumulator_t *acc, const glyphy_point_t *p1) { arc_to (acc, *p1, 0); } void glyphy_arc_accumulator_conic_to (glyphy_arc_accumulator_t *acc, const glyphy_point_t *p1, const glyphy_point_t *p2) { bezier (acc, Bezier (acc->current_point, Point (acc->current_point).lerp (2/3., *p1), Point (*p2).lerp (2/3., *p1), *p2)); } void glyphy_arc_accumulator_cubic_to (glyphy_arc_accumulator_t *acc, const glyphy_point_t *p1, const glyphy_point_t *p2, const glyphy_point_t *p3) { bezier (acc, Bezier (acc->current_point, *p1, *p2, *p3)); } void glyphy_arc_accumulator_arc_to (glyphy_arc_accumulator_t *acc, const glyphy_point_t *p1, double d) { arc_to (acc, *p1, d); } void glyphy_arc_accumulator_close_path (glyphy_arc_accumulator_t *acc) { close_path (acc); } /* * Outline extents from arc list */ void glyphy_arc_list_extents (const glyphy_arc_endpoint_t *endpoints, unsigned int num_endpoints, glyphy_extents_t *extents) { Point p0 (0, 0); glyphy_extents_clear (extents); for (unsigned int i = 0; i < num_endpoints; i++) { const glyphy_arc_endpoint_t &endpoint = endpoints[i]; if (endpoint.d == GLYPHY_INFINITY) { p0 = endpoint.p; continue; } Arc arc (p0, endpoint.p, endpoint.d); p0 = endpoint.p; glyphy_extents_t arc_extents; arc.extents (arc_extents); glyphy_extents_extend (extents, &arc_extents); } }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-buffer.h" struct demo_buffer_t { unsigned int refcount; glyphy_point_t cursor; std::vector<glyph_vertex_t> *vertices; glyphy_extents_t ink_extents; glyphy_extents_t logical_extents; bool dirty; GLuint buf_name; }; demo_buffer_t * demo_buffer_create (void) { demo_buffer_t *buffer = (demo_buffer_t *) calloc (1, sizeof (demo_buffer_t)); buffer->refcount = 1; buffer->vertices = new std::vector<glyph_vertex_t>; glGenBuffers (1, &buffer->buf_name); demo_buffer_clear (buffer); return buffer; } demo_buffer_t * demo_buffer_reference (demo_buffer_t *buffer) { if (buffer) buffer->refcount++; return buffer; } void demo_buffer_destroy (demo_buffer_t *buffer) { if (!buffer || --buffer->refcount) return; glDeleteBuffers (1, &buffer->buf_name); delete buffer->vertices; free (buffer); } void demo_buffer_clear (demo_buffer_t *buffer) { buffer->vertices->clear (); glyphy_extents_clear (&buffer->ink_extents); glyphy_extents_clear (&buffer->logical_extents); buffer->dirty = true; } void demo_buffer_extents (demo_buffer_t *buffer, glyphy_extents_t *ink_extents, glyphy_extents_t *logical_extents) { if (ink_extents) *ink_extents = buffer->ink_extents; if (logical_extents) *logical_extents = buffer->logical_extents; } void demo_buffer_move_to (demo_buffer_t *buffer, const glyphy_point_t *p) { buffer->cursor = *p; } void demo_buffer_current_point (demo_buffer_t *buffer, glyphy_point_t *p) { *p = buffer->cursor; } void demo_buffer_add_text (demo_buffer_t *buffer, const char *utf8, demo_font_t *font, double font_size) { FT_Face face = demo_font_get_face (font); glyphy_point_t top_left = buffer->cursor; buffer->cursor.y += font_size /* * font->ascent */; unsigned int unicode; for (const unsigned char *p = (const unsigned char *) utf8; *p; p++) { if (*p < 128) { unicode = *p; } else { unsigned int j; if (*p < 0xE0) { unicode = *p & ~0xE0; j = 1; } else if (*p < 0xF0) { unicode = *p & ~0xF0; j = 2; } else { unicode = *p & ~0xF8; j = 3; continue; } p++; for (; j && *p; j--, p++) unicode = (unicode << 6) | (*p & ~0xC0); p--; } if (unicode == '\n') { buffer->cursor.y += font_size; buffer->cursor.x = top_left.x; continue; } unsigned int glyph_index = FT_Get_Char_Index (face, unicode); glyph_info_t gi; demo_font_lookup_glyph (font, glyph_index, &gi); /* Update ink extents */ glyphy_extents_t ink_extents; demo_shader_add_glyph_vertices (buffer->cursor, font_size, &gi, buffer->vertices, &ink_extents); glyphy_extents_extend (&buffer->ink_extents, &ink_extents); /* Update logical extents */ glyphy_point_t corner; corner.x = buffer->cursor.x; corner.y = buffer->cursor.y - font_size; glyphy_extents_add (&buffer->logical_extents, &corner); corner.x = buffer->cursor.x + font_size * gi.advance; corner.y = buffer->cursor.y; glyphy_extents_add (&buffer->logical_extents, &corner); buffer->cursor.x += font_size * gi.advance; } buffer->dirty = true; } void demo_buffer_draw (demo_buffer_t *buffer) { GLint program; glGetIntegerv (GL_CURRENT_PROGRAM, &program); GLuint a_glyph_vertex_loc = glGetAttribLocation (program, "a_glyph_vertex"); glBindBuffer (GL_ARRAY_BUFFER, buffer->buf_name); if (buffer->dirty) { glBufferData (GL_ARRAY_BUFFER, sizeof (glyph_vertex_t) * buffer->vertices->size (), (const char *) &(*buffer->vertices)[0], GL_STATIC_DRAW); buffer->dirty = false; } glEnableVertexAttribArray (a_glyph_vertex_loc); glVertexAttribPointer (a_glyph_vertex_loc, 4, GL_FLOAT, GL_FALSE, sizeof (glyph_vertex_t), 0); glDrawArrays (GL_TRIANGLES, 0, buffer->vertices->size ()); glDisableVertexAttribArray (a_glyph_vertex_loc); }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-font.h" #include <glyphy-freetype.h> #include <ext/hash_map> using namespace __gnu_cxx; /* This is ridiculous */ typedef hash_map<unsigned int, glyph_info_t> glyph_cache_t; struct demo_font_t { unsigned int refcount; FT_Face face; glyph_cache_t *glyph_cache; demo_atlas_t *atlas; glyphy_arc_accumulator_t *acc; /* stats */ unsigned int num_glyphs; double sum_error; unsigned int sum_endpoints; double sum_fetch; unsigned int sum_bytes; }; demo_font_t * demo_font_create (FT_Face face, demo_atlas_t *atlas) { demo_font_t *font = (demo_font_t *) calloc (1, sizeof (demo_font_t)); font->refcount = 1; font->face = face; font->glyph_cache = new glyph_cache_t (); font->atlas = demo_atlas_reference (atlas); font->acc = glyphy_arc_accumulator_create (); font->num_glyphs = 0; font->sum_error = 0; font->sum_endpoints = 0; font->sum_fetch = 0; font->sum_bytes = 0; return font; } demo_font_t * demo_font_reference (demo_font_t *font) { if (font) font->refcount++; return font; } void demo_font_destroy (demo_font_t *font) { if (!font || --font->refcount) return; glyphy_arc_accumulator_destroy (font->acc); demo_atlas_destroy (font->atlas); delete font->glyph_cache; free (font); } FT_Face demo_font_get_face (demo_font_t *font) { return font->face; } demo_atlas_t * demo_font_get_atlas (demo_font_t *font) { return font->atlas; } static glyphy_bool_t accumulate_endpoint (glyphy_arc_endpoint_t *endpoint, vector<glyphy_arc_endpoint_t> *endpoints) { endpoints->push_back (*endpoint); return true; } static void encode_ft_glyph (demo_font_t *font, unsigned int glyph_index, double tolerance_per_em, glyphy_rgba_t *buffer, unsigned int buffer_len, unsigned int *output_len, unsigned int *nominal_width, unsigned int *nominal_height, glyphy_extents_t *extents, double *advance) { /* Used for testing only */ #define SCALE (1. * (1 << 0)) FT_Face face = font->face; if (FT_Err_Ok != FT_Load_Glyph (face, glyph_index, FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT | FT_LOAD_NO_SCALE | FT_LOAD_LINEAR_DESIGN | FT_LOAD_IGNORE_TRANSFORM)) die ("Failed loading FreeType glyph"); if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) die ("FreeType loaded glyph format is not outline"); unsigned int upem = face->units_per_EM; double tolerance = upem * tolerance_per_em; /* in font design units */ double faraway = double (upem) / (MIN_FONT_SIZE * M_SQRT2); vector<glyphy_arc_endpoint_t> endpoints; glyphy_arc_accumulator_reset (font->acc); glyphy_arc_accumulator_set_tolerance (font->acc, tolerance); glyphy_arc_accumulator_set_callback (font->acc, (glyphy_arc_endpoint_accumulator_callback_t) accumulate_endpoint, &endpoints); if (FT_Err_Ok != glyphy_freetype(outline_decompose) (&face->glyph->outline, font->acc)) die ("Failed converting glyph outline to arcs"); assert (glyphy_arc_accumulator_get_error (font->acc) <= tolerance); #if 0 /* Technically speaking, we want the following code, * however, crappy fonts have crappy flags. So we just * fixup unconditionally... */ if (face->glyph->outline.flags & FT_OUTLINE_EVEN_ODD_FILL) glyphy_outline_winding_from_even_odd (&endpoints[0], endpoints.size (), false); else if (face->glyph->outline.flags & FT_OUTLINE_REVERSE_FILL) glyphy_outline_reverse (&endpoints[0], endpoints.size ()); #else glyphy_outline_winding_from_even_odd (&endpoints[0], endpoints.size (), false); #endif if (SCALE != 1.) for (unsigned int i = 0; i < endpoints.size (); i++) { endpoints[i].p.x /= SCALE; endpoints[i].p.y /= SCALE; } double avg_fetch_achieved; if (!glyphy_arc_list_encode_blob (&endpoints[0], endpoints.size (), buffer, buffer_len, faraway / SCALE, 4, /* UNUSED */ &avg_fetch_achieved, output_len, nominal_width, nominal_height, extents)) die ("Failed encoding arcs"); glyphy_extents_scale (extents, 1. / upem, 1. / upem); glyphy_extents_scale (extents, SCALE, SCALE); *advance = face->glyph->metrics.horiAdvance / (double) upem; if (0) LOGI ("gid%3u: endpoints%3d; err%3g%%; tex fetch%4.1f; mem%4.1fkb\n", glyph_index, (unsigned int) glyphy_arc_accumulator_get_num_endpoints (font->acc), round (100 * glyphy_arc_accumulator_get_error (font->acc) / tolerance), avg_fetch_achieved, (*output_len * sizeof (glyphy_rgba_t)) / 1024.); font->num_glyphs++; font->sum_error += glyphy_arc_accumulator_get_error (font->acc) / tolerance; font->sum_endpoints += glyphy_arc_accumulator_get_num_endpoints (font->acc); font->sum_fetch += avg_fetch_achieved; font->sum_bytes += (*output_len * sizeof (glyphy_rgba_t)); } static void _demo_font_upload_glyph (demo_font_t *font, unsigned int glyph_index, glyph_info_t *glyph_info) { glyphy_rgba_t buffer[4096 * 16]; unsigned int output_len; encode_ft_glyph (font, glyph_index, TOLERANCE, buffer, ARRAY_LEN (buffer), &output_len, &glyph_info->nominal_w, &glyph_info->nominal_h, &glyph_info->extents, &glyph_info->advance); glyph_info->is_empty = glyphy_extents_is_empty (&glyph_info->extents); if (!glyph_info->is_empty) demo_atlas_alloc (font->atlas, buffer, output_len, &glyph_info->atlas_x, &glyph_info->atlas_y); } void demo_font_lookup_glyph (demo_font_t *font, unsigned int glyph_index, glyph_info_t *glyph_info) { if (font->glyph_cache->find (glyph_index) == font->glyph_cache->end ()) { _demo_font_upload_glyph (font, glyph_index, glyph_info); (*font->glyph_cache)[glyph_index] = *glyph_info; } else *glyph_info = (*font->glyph_cache)[glyph_index]; } void demo_font_print_stats (demo_font_t *font) { LOGI ("%3d glyphs; avg num endpoints%6.2f; avg error%5.1f%%; avg tex fetch%5.2f; avg %5.2fkb per glyph\n", font->num_glyphs, (double) font->sum_endpoints / font->num_glyphs, 100. * font->sum_error / font->num_glyphs, font->sum_fetch / font->num_glyphs, font->sum_bytes / 1024. / font->num_glyphs); }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-atlas.h" struct demo_atlas_t { unsigned int refcount; GLuint tex_unit; GLuint tex_name; GLuint tex_w; GLuint tex_h; GLuint item_w; GLuint item_h_q; /* height quantum */ GLuint cursor_x; GLuint cursor_y; }; demo_atlas_t * demo_atlas_create (unsigned int w, unsigned int h, unsigned int item_w, unsigned int item_h_quantum) { TRACE(); demo_atlas_t *at = (demo_atlas_t *) calloc (1, sizeof (demo_atlas_t)); at->refcount = 1; glGetIntegerv (GL_ACTIVE_TEXTURE, (GLint *) &at->tex_unit); glGenTextures (1, &at->tex_name); at->tex_w = w; at->tex_h = h; at->item_w = item_w; at->item_h_q = item_h_quantum; at->cursor_x = 0; at->cursor_y = 0; demo_atlas_bind_texture (at); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl(TexImage2D) (GL_TEXTURE_2D, 0, GL_RGBA, at->tex_w, at->tex_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); return at; } demo_atlas_t * demo_atlas_reference (demo_atlas_t *at) { if (at) at->refcount++; return at; } void demo_atlas_destroy (demo_atlas_t *at) { if (!at || --at->refcount) return; glDeleteTextures (1, &at->tex_name); free (at); } void demo_atlas_bind_texture (demo_atlas_t *at) { glActiveTexture (at->tex_unit); glBindTexture (GL_TEXTURE_2D, at->tex_name); } void demo_atlas_set_uniforms (demo_atlas_t *at) { GLuint program; glGetIntegerv (GL_CURRENT_PROGRAM, (GLint *) &program); glUniform4i (glGetUniformLocation (program, "u_atlas_info"), at->tex_w, at->tex_h, at->item_w, at->item_h_q); glUniform1i (glGetUniformLocation (program, "u_atlas_tex"), at->tex_unit - GL_TEXTURE0); } void demo_atlas_alloc (demo_atlas_t *at, glyphy_rgba_t *data, unsigned int len, unsigned int *px, unsigned int *py) { GLuint w, h, x, y; w = at->item_w; h = (len + w - 1) / w; if (at->cursor_y + h > at->tex_h) { /* Go to next column */ at->cursor_x += at->item_w; at->cursor_y = 0; } if (at->cursor_x + w <= at->tex_w && at->cursor_y + h <= at->tex_h) { x = at->cursor_x; y = at->cursor_y; at->cursor_y += (h + at->item_h_q - 1) & ~(at->item_h_q - 1); } else die ("Ran out of atlas memory"); demo_atlas_bind_texture (at); if (w * h == len) gl(TexSubImage2D) (GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data); else { gl(TexSubImage2D) (GL_TEXTURE_2D, 0, x, y, w, h - 1, GL_RGBA, GL_UNSIGNED_BYTE, data); /* Upload the last row separately */ gl(TexSubImage2D) (GL_TEXTURE_2D, 0, x, y + h - 1, len - (w * (h - 1)), 1, GL_RGBA, GL_UNSIGNED_BYTE, data + w * (h - 1)); } *px = x / at->item_w; *py = y / at->item_h_q; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifndef DEMO_SHADERS_H #define DEMO_SHADERS_H #include "demo-common.h" #include "demo-font.h" struct glyph_vertex_t { /* Position */ GLfloat x; GLfloat y; /* Glyph info */ GLfloat g16hi; GLfloat g16lo; }; void demo_shader_add_glyph_vertices (const glyphy_point_t &p, double font_size, glyph_info_t *gi, std::vector<glyph_vertex_t> *vertices, glyphy_extents_t *extents); GLuint demo_shader_create_program (void); #endif /* DEMO_SHADERS_H */
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju */ #ifndef DEMO_COMMON_H #define DEMO_COMMON_H #include <glyphy.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <algorithm> #include <vector> /* Tailor config for various platforms. */ #ifdef EMSCRIPTEN /* https://github.com/kripken/emscripten/issues/340 */ # undef HAVE_GLEW /* WebGL shaders are ES2 */ # define GL_ES_VERSION_2_0 1 #endif #if defined(__ANDROID__) # define HAVE_GLES2 1 # define HAVE_GLUT 1 #endif /* Get Glew out of the way. */ #ifdef HAVE_GLEW # include <GL/glew.h> #else # define GLEW_OK 0 static inline int glewInit (void) { return GLEW_OK; } static inline int glewIsSupported (const char *s) { return 0 == strcmp ("GL_VERSION_2_0", s); } #endif /* HAVE_GLEW */ /* WTF this block?! */ #if defined(HAVE_GLES2) # include <GLES2/gl2.h> #elif defined(HAVE_GL) # ifndef HAVE_GLEW # define GL_GLEXT_PROTOTYPES 1 # if defined(__APPLE__) # include <OpenGL/gl.h> # else # include <GL/gl.h> # endif # endif # if defined(__APPLE__) # include <OpenGL/OpenGL.h> # else # ifdef HAVE_GLEW # ifdef _WIN32 # include <GL/wglew.h> # else # include <GL/glxew.h> # endif # endif # endif #endif /* HAVE_GL */ /* Finally, Glut. */ #ifdef HAVE_GLUT # if defined(__APPLE__) # include <GLUT/glut.h> # else # include <GL/glut.h> # endif #endif /* Logging. */ #ifdef __ANDROID__ # include <android/log.h> # define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "glyphy-demo", __VA_ARGS__)) # define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "glyphy-demo", __VA_ARGS__)) # define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "glyphy-demo", __VA_ARGS__)) #else /* !__ANDROID__ */ # define LOGI(...) ((void) fprintf (stdout, __VA_ARGS__)) # define LOGW(...) ((void) fprintf (stderr, __VA_ARGS__)) # define LOGE(...) ((void) fprintf (stderr, __VA_ARGS__), abort ()) #endif #define STRINGIZE1(Src) #Src #define STRINGIZE(Src) STRINGIZE1(Src) #define ARRAY_LEN(Array) (sizeof (Array) / sizeof (*Array)) #define MIN_FONT_SIZE 10 #define TOLERANCE (1./2048) #define gl(name) \ for (GLint __ee, __ii = 0; \ __ii < 1; \ (__ii++, \ (__ee = glGetError()) && \ (fprintf (stderr, "gl" #name " failed with error %04X on line %d\n", __ee, __LINE__), abort (), 0))) \ gl##name static inline void die (const char *msg) { fprintf (stderr, "%s\n", msg); exit (1); } template <typename T> T clamp (T v, T m, T M) { return v < m ? m : v > M ? M : v; } #if defined(_MSC_VER) #define DEMO_FUNC __FUNCSIG__ #else #define DEMO_FUNC __func__ #endif struct auto_trace_t { auto_trace_t (const char *func_) : func (func_) { printf ("Enter: %s\n", func); } ~auto_trace_t (void) { printf ("Leave: %s\n", func); } private: const char * const func; }; #define TRACE() auto_trace_t trace(DEMO_FUNC) #endif /* DEMO_COMMON_H */
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-shader.h" #include "demo-atlas-glsl.h" #include "demo-vshader-glsl.h" #include "demo-fshader-glsl.h" static unsigned int glyph_encode (unsigned int atlas_x , /* 7 bits */ unsigned int atlas_y, /* 7 bits */ unsigned int corner_x, /* 1 bit */ unsigned int corner_y, /* 1 bit */ unsigned int nominal_w, /* 6 bits */ unsigned int nominal_h /* 6 bits */) { assert (0 == (atlas_x & ~0x7F)); assert (0 == (atlas_y & ~0x7F)); assert (0 == (corner_x & ~1)); assert (0 == (corner_y & ~1)); assert (0 == (nominal_w & ~0x3F)); assert (0 == (nominal_h & ~0x3F)); unsigned int x = (((atlas_x << 6) | nominal_w) << 1) | corner_x; unsigned int y = (((atlas_y << 6) | nominal_h) << 1) | corner_y; return (x << 16) | y; } static void glyph_vertex_encode (double x, double y, unsigned int corner_x, unsigned int corner_y, const glyph_info_t *gi, glyph_vertex_t *v) { unsigned int encoded = glyph_encode (gi->atlas_x, gi->atlas_y, corner_x, corner_y, gi->nominal_w, gi->nominal_h); v->x = x; v->y = y; v->g16hi = encoded >> 16; v->g16lo = encoded & 0xFFFF; } void demo_shader_add_glyph_vertices (const glyphy_point_t &p, double font_size, glyph_info_t *gi, std::vector<glyph_vertex_t> *vertices, glyphy_extents_t *extents) { if (gi->is_empty) return; glyph_vertex_t v[4]; #define ENCODE_CORNER(_cx, _cy) \ do { \ double _vx = p.x + font_size * ((1-_cx) * gi->extents.min_x + _cx * gi->extents.max_x); \ double _vy = p.y - font_size * ((1-_cy) * gi->extents.min_y + _cy * gi->extents.max_y); \ glyph_vertex_encode (_vx, _vy, _cx, _cy, gi, &v[_cx * 2 + _cy]); \ } while (0) ENCODE_CORNER (0, 0); ENCODE_CORNER (0, 1); ENCODE_CORNER (1, 0); ENCODE_CORNER (1, 1); #undef ENCODE_CORNER vertices->push_back (v[0]); vertices->push_back (v[1]); vertices->push_back (v[2]); vertices->push_back (v[1]); vertices->push_back (v[2]); vertices->push_back (v[3]); if (extents) { glyphy_extents_clear (extents); for (unsigned int i = 0; i < 4; i++) { glyphy_point_t p = {v[i].x, v[i].y}; glyphy_extents_add (extents, &p); } } } static GLuint compile_shader (GLenum type, GLsizei count, const GLchar** sources) { TRACE(); GLuint shader; GLint compiled; if (!(shader = glCreateShader (type))) return shader; glShaderSource (shader, count, sources, 0); glCompileShader (shader); glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint info_len = 0; LOGW ("%s shader failed to compile\n", type == GL_VERTEX_SHADER ? "Vertex" : "Fragment"); glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &info_len); if (info_len > 0) { char *info_log = (char*) malloc (info_len); glGetShaderInfoLog (shader, info_len, NULL, info_log); LOGW ("%s\n", info_log); free (info_log); } abort (); } return shader; } static GLuint link_program (GLuint vshader, GLuint fshader) { TRACE(); GLuint program; GLint linked; program = glCreateProgram (); glAttachShader (program, vshader); glAttachShader (program, fshader); glLinkProgram (program); glDeleteShader (vshader); glDeleteShader (fshader); glGetProgramiv (program, GL_LINK_STATUS, &linked); if (!linked) { GLint info_len = 0; LOGW ("Program failed to link\n"); glGetProgramiv (program, GL_INFO_LOG_LENGTH, &info_len); if (info_len > 0) { char *info_log = (char*) malloc (info_len); glGetProgramInfoLog (program, info_len, NULL, info_log); LOGW ("%s\n", info_log); free (info_log); } abort (); } return program; } #ifdef GL_ES_VERSION_2_0 # define GLSL_HEADER_STRING \ "#extension GL_OES_standard_derivatives : enable\n" \ "precision highp float;\n" \ "precision highp int;\n" #else # define GLSL_HEADER_STRING \ "#version 110\n" #endif GLuint demo_shader_create_program (void) { TRACE(); GLuint vshader, fshader, program; const GLchar *vshader_sources[] = {GLSL_HEADER_STRING, demo_vshader_glsl}; vshader = compile_shader (GL_VERTEX_SHADER, ARRAY_LEN (vshader_sources), vshader_sources); const GLchar *fshader_sources[] = {GLSL_HEADER_STRING, demo_atlas_glsl, glyphy_common_shader_source (), "#define GLYPHY_SDF_PSEUDO_DISTANCE 1\n", glyphy_sdf_shader_source (), demo_fshader_glsl}; fshader = compile_shader (GL_FRAGMENT_SHADER, ARRAY_LEN (fshader_sources), fshader_sources); program = link_program (vshader, fshader); return program; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <stdio.h> #include <assert.h> #define TOLERANCE (1./2048) #include <glyphy-freetype.h> #include <vector> using namespace std; static inline void die (const char *msg) { fprintf (stderr, "%s\n", msg); exit (1); } static glyphy_bool_t accumulate_endpoint (glyphy_arc_endpoint_t *endpoint, vector<glyphy_arc_endpoint_t> *endpoints) { endpoints->push_back (*endpoint); return true; } int main (int argc, char** argv) { bool verbose = false; if (argc > 1 && 0 == strcmp (argv[1], "--verbose")) { verbose = true; argc--; argv++; } if (argc == 1) { fprintf (stderr, "Usage: %s FONT_FILE...\n", argv[0]); exit (1); } FT_Library ft_library; FT_Init_FreeType (&ft_library); glyphy_arc_accumulator_t *acc = glyphy_arc_accumulator_create (); for (unsigned int arg = 1; (int) arg < argc; arg++) { const char *font_path = argv[arg]; unsigned int num_faces = 1; for (unsigned int face_index = 0; face_index < num_faces; face_index++) { FT_Face ft_face = NULL; FT_New_Face (ft_library, font_path, face_index, &ft_face); if (!ft_face) die ("Failed to open font file"); /* FreeType's absurd. You have to open a ft_face to get the number of * faces in the font file. */ num_faces = ft_face->num_faces; printf ("Opened %s face index %d. Has %d glyphs\n", font_path, face_index, (int) ft_face->num_glyphs); for (unsigned int glyph_index = 0; glyph_index < ft_face->num_glyphs; glyph_index++) { char glyph_name[30]; if (FT_Get_Glyph_Name (ft_face, glyph_index, glyph_name, sizeof (glyph_name))) sprintf (glyph_name, "gid%u", glyph_index); printf ("Processing glyph %d (%s)\n", glyph_index, glyph_name); if (FT_Err_Ok != FT_Load_Glyph (ft_face, glyph_index, FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT | FT_LOAD_NO_SCALE | FT_LOAD_LINEAR_DESIGN | FT_LOAD_IGNORE_TRANSFORM)) die ("Failed loading FreeType glyph"); if (ft_face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) die ("FreeType loaded glyph format is not outline"); unsigned int upem = ft_face->units_per_EM; double tolerance = upem * TOLERANCE; /* in font design units */ vector<glyphy_arc_endpoint_t> endpoints; glyphy_arc_accumulator_reset (acc); glyphy_arc_accumulator_set_tolerance (acc, tolerance); glyphy_arc_accumulator_set_callback (acc, (glyphy_arc_endpoint_accumulator_callback_t) accumulate_endpoint, &endpoints); if (FT_Err_Ok != glyphy_freetype(outline_decompose) (&ft_face->glyph->outline, acc)) die ("Failed converting glyph outline to arcs"); if (verbose) { printf ("Arc list has %d endpoints\n", (int) endpoints.size ()); for (unsigned int i = 0; i < endpoints.size (); i++) printf ("Endpoint %d: p=(%g,%g),d=%g\n", i, endpoints[i].p.x, endpoints[i].p.y, endpoints[i].d); } assert (glyphy_arc_accumulator_get_error (acc) <= tolerance); #if 0 if (ft_face->glyph->outline.flags & FT_OUTLINE_EVEN_ODD_FILL) glyphy_outline_winding_from_even_odd (&endpoints[0], endpoints.size (), false); #endif if (ft_face->glyph->outline.flags & FT_OUTLINE_REVERSE_FILL) glyphy_outline_reverse (&endpoints[0], endpoints.size ()); if (glyphy_outline_winding_from_even_odd (&endpoints[0], endpoints.size (), false)) { fprintf (stderr, "ERROR: %s:%d: Glyph %d (%s) has contours with wrong direction\n", font_path, face_index, glyph_index, glyph_name); } } FT_Done_Face (ft_face); } } glyphy_arc_accumulator_destroy (acc); FT_Done_FreeType (ft_library); return 0; }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-view.h" extern "C" { #include "trackball.h" #include "matrix4x4.h" } #include <sys/time.h> struct demo_view_t { unsigned int refcount; demo_glstate_t *st; /* Output */ GLint vsync; glyphy_bool_t srgb; glyphy_bool_t fullscreen; /* Mouse handling */ int buttons; int modifiers; bool dragged; bool click_handled; double beginx, beginy; double lastx, lasty, lastt; double dx,dy, dt; /* Transformation */ float quat[4]; double scale; glyphy_point_t translate; double perspective; /* Animation */ float rot_axis[3]; float rot_speed; bool animate; int num_frames; long fps_start_time; long last_frame_time; bool has_fps_timer; /* Window geometry just before going fullscreen */ int x; int y; int width; int height; }; demo_view_t *static_vu; demo_view_t * demo_view_create (demo_glstate_t *st) { TRACE(); demo_view_t *vu = (demo_view_t *) calloc (1, sizeof (demo_view_t)); vu->refcount = 1; vu->st = st; demo_view_reset (vu); assert (!static_vu); static_vu = vu; return vu; } demo_view_t * demo_view_reference (demo_view_t *vu) { if (vu) vu->refcount++; return vu; } void demo_view_destroy (demo_view_t *vu) { if (!vu || --vu->refcount) return; assert (static_vu == vu); static_vu = NULL; free (vu); } #define ANIMATION_SPEED 1. /* Default speed, in radians second. */ void demo_view_reset (demo_view_t *vu) { vu->perspective = 4; vu->scale = 1; vu->translate.x = vu->translate.y = 0; trackball (vu->quat , 0.0, 0.0, 0.0, 0.0); vset (vu->rot_axis, 0., 0., 1.); vu->rot_speed = ANIMATION_SPEED / 1000.; } static void demo_view_scale_gamma_adjust (demo_view_t *vu, double factor) { demo_glstate_scale_gamma_adjust (vu->st, factor); } static void demo_view_scale_contrast (demo_view_t *vu, double factor) { demo_glstate_scale_contrast (vu->st, factor); } static void demo_view_scale_perspective (demo_view_t *vu, double factor) { vu->perspective = clamp (vu->perspective * factor, .01, 100.); } static void demo_view_toggle_outline (demo_view_t *vu) { demo_glstate_toggle_outline (vu->st); } static void demo_view_scale_outline_thickness (demo_view_t *vu, double factor) { demo_glstate_scale_outline_thickness (vu->st, factor); } static void demo_view_adjust_boldness (demo_view_t *vu, double factor) { demo_glstate_adjust_boldness (vu->st, factor); } static void demo_view_scale (demo_view_t *vu, double factor) { vu->scale *= factor; } static void demo_view_translate (demo_view_t *vu, double dx, double dy) { vu->translate.x += dx / vu->scale; vu->translate.y += dy / vu->scale; } static void demo_view_apply_transform (demo_view_t *vu, float *mat) { int viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); GLint width = viewport[2]; GLint height = viewport[3]; // View transform m4Scale (mat, vu->scale, vu->scale, 1); m4Translate (mat, vu->translate.x, vu->translate.y, 0); // Perspective { double d = std::max (width, height); double near = d / vu->perspective; double far = near + d; double factor = near / (2 * near + d); m4Frustum (mat, -width * factor, width * factor, -height * factor, height * factor, near, far); m4Translate (mat, 0, 0, -(near + d * .5)); } // Rotate float m[4][4]; build_rotmatrix (m, vu->quat); m4MultMatrix(mat, &m[0][0]); // Fix 'up' m4Scale (mat, 1, -1, 1); } /* return current time in milli-seconds */ static long current_time (void) { return glutGet (GLUT_ELAPSED_TIME); } static void next_frame (demo_view_t *vu) { glutPostRedisplay (); } static void timed_step (int ms) { demo_view_t *vu = static_vu; if (vu->animate) { glutTimerFunc (ms, timed_step, ms); next_frame (vu); } } static void idle_step (void) { demo_view_t *vu = static_vu; if (vu->animate) { next_frame (vu); } else glutIdleFunc (NULL); } static void print_fps (int ms) { demo_view_t *vu = static_vu; if (vu->animate) { glutTimerFunc (ms, print_fps, ms); long t = current_time (); LOGI ("%gfps\n", vu->num_frames * 1000. / (t - vu->fps_start_time)); vu->num_frames = 0; vu->fps_start_time = t; } else vu->has_fps_timer = false; } static void start_animation (demo_view_t *vu) { vu->num_frames = 0; vu->last_frame_time = vu->fps_start_time = current_time (); //glutTimerFunc (1000/60, timed_step, 1000/60); glutIdleFunc (idle_step); if (!vu->has_fps_timer) { vu->has_fps_timer = true; glutTimerFunc (5000, print_fps, 5000); } } static void demo_view_toggle_animation (demo_view_t *vu) { vu->animate = !vu->animate; if (vu->animate) start_animation (vu); } static void demo_view_toggle_vsync (demo_view_t *vu) { vu->vsync = !vu->vsync; LOGI ("Setting vsync %s.\n", vu->vsync ? "on" : "off"); #if defined(__APPLE__) CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &vu->vsync); #elif defined(__WGLEW__) if (wglewIsSupported ("WGL_EXT_swap_control")) wglSwapIntervalEXT (vu->vsync); else LOGW ("WGL_EXT_swal_control not supported; failed to set vsync\n"); #elif defined(__GLXEW_H__) if (glxewIsSupported ("GLX_SGI_swap_control")) glXSwapIntervalSGI (vu->vsync); else LOGW ("GLX_SGI_swap_control not supported; failed to set vsync\n"); #else LOGW ("No vsync extension found; failed to set vsync\n"); #endif } static void demo_view_toggle_srgb (demo_view_t *vu) { vu->srgb = !vu->srgb; LOGI ("Setting sRGB framebuffer %s.\n", vu->srgb ? "on" : "off"); #if defined(GL_FRAMEBUFFER_SRGB) && defined(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT) GLboolean available = false; if ((glewIsSupported ("GL_ARB_framebuffer_sRGB") || glewIsSupported ("GL_EXT_framebuffer_sRGB")) && (glGetBooleanv (GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &available), available)) { if (vu->srgb) glEnable (GL_FRAMEBUFFER_SRGB); else glDisable (GL_FRAMEBUFFER_SRGB); } else #endif LOGW ("No sRGB framebuffer extension found; failed to set sRGB framebuffer\n"); } static void demo_view_toggle_fullscreen (demo_view_t *vu) { vu->fullscreen = !vu->fullscreen; if (vu->fullscreen) { vu->x = glutGet (GLUT_WINDOW_X); vu->y = glutGet (GLUT_WINDOW_Y); vu->width = glutGet (GLUT_WINDOW_WIDTH); vu->height = glutGet (GLUT_WINDOW_HEIGHT); glutFullScreen (); } else { glutReshapeWindow (vu->width, vu->height); glutPositionWindow (vu->x, vu->y); } } static void demo_view_toggle_debug (demo_view_t *vu) { demo_glstate_toggle_debug (vu->st); } void demo_view_reshape_func (demo_view_t *vu, int width, int height) { glViewport (0, 0, width, height); glutPostRedisplay (); } #define STEP 1.05 void demo_view_keyboard_func (demo_view_t *vu, unsigned char key, int x, int y) { switch (key) { case '\033': case 'q': exit (0); break; case ' ': demo_view_toggle_animation (vu); break; case 'v': demo_view_toggle_vsync (vu); break; case 'f': demo_view_toggle_fullscreen (vu); break; case 'd': demo_view_toggle_debug (vu); break; case 'o': demo_view_toggle_outline (vu); break; case 'p': demo_view_scale_outline_thickness (vu, STEP); break; case 'i': demo_view_scale_outline_thickness (vu, 1. / STEP); break; case '0': demo_view_adjust_boldness (vu, +.01); break; case '9': demo_view_adjust_boldness (vu, -.01); break; case 'a': demo_view_scale_contrast (vu, STEP); break; case 'z': demo_view_scale_contrast (vu, 1. / STEP); break; case 'g': demo_view_scale_gamma_adjust (vu, STEP); break; case 'b': demo_view_scale_gamma_adjust (vu, 1. / STEP); break; case 'c': demo_view_toggle_srgb (vu); break; case '=': demo_view_scale (vu, STEP); break; case '-': demo_view_scale (vu, 1. / STEP); break; case 'k': demo_view_translate (vu, 0, -.1); break; case 'j': demo_view_translate (vu, 0, +.1); break; case 'h': demo_view_translate (vu, +.1, 0); break; case 'l': demo_view_translate (vu, -.1, 0); break; case 'r': demo_view_reset (vu); break; default: return; } glutPostRedisplay (); } void demo_view_special_func (demo_view_t *vu, int key, int x, int y) { switch (key) { case GLUT_KEY_UP: demo_view_translate (vu, 0, -.1); break; case GLUT_KEY_DOWN: demo_view_translate (vu, 0, +.1); break; case GLUT_KEY_LEFT: demo_view_translate (vu, +.1, 0); break; case GLUT_KEY_RIGHT: demo_view_translate (vu, -.1, 0); break; default: return; } glutPostRedisplay (); } void demo_view_mouse_func (demo_view_t *vu, int button, int state, int x, int y) { if (state == GLUT_DOWN) { vu->buttons |= (1 << button); vu->click_handled = false; } else vu->buttons &= !(1 << button); vu->modifiers = glutGetModifiers (); switch (button) { case GLUT_RIGHT_BUTTON: switch (state) { case GLUT_DOWN: if (vu->animate) { demo_view_toggle_animation (vu); vu->click_handled = true; } break; case GLUT_UP: if (!vu->animate) { if (!vu->dragged && !vu->click_handled) demo_view_toggle_animation (vu); else if (vu->dt) { double speed = hypot (vu->dx, vu->dy) / vu->dt; if (speed > 0.1) demo_view_toggle_animation (vu); } vu->dx = vu->dy = vu->dt = 0; } break; } break; #if defined(GLUT_WHEEL_UP) case GLUT_WHEEL_UP: demo_view_scale (vu, STEP); break; case GLUT_WHEEL_DOWN: demo_view_scale (vu, 1. / STEP); break; #endif } vu->beginx = vu->lastx = x; vu->beginy = vu->lasty = y; vu->dragged = false; glutPostRedisplay (); } void demo_view_motion_func (demo_view_t *vu, int x, int y) { vu->dragged = true; int viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); GLuint width = viewport[2]; GLuint height = viewport[3]; if (vu->buttons & (1 << GLUT_LEFT_BUTTON)) { if (vu->modifiers & GLUT_ACTIVE_SHIFT) { /* adjust contrast/gamma */ demo_view_scale_gamma_adjust (vu, 1 - ((y - vu->lasty) / height)); demo_view_scale_contrast (vu, 1 + ((x - vu->lastx) / width)); } else { /* translate */ demo_view_translate (vu, +2 * (x - vu->lastx) / width, -2 * (y - vu->lasty) / height); } } if (vu->buttons & (1 << GLUT_RIGHT_BUTTON)) { if (vu->modifiers & GLUT_ACTIVE_SHIFT) { /* adjust perspective */ demo_view_scale_perspective (vu, 1 - ((y - vu->lasty) / height) * 5); } else { /* rotate */ float dquat[4]; trackball (dquat, (2.0*vu->lastx - width) / width, ( height - 2.0*vu->lasty) / height, ( 2.0*x - width) / width, ( height - 2.0*y) / height ); vu->dx = x - vu->lastx; vu->dy = y - vu->lasty; vu->dt = current_time () - vu->lastt; add_quats (dquat, vu->quat, vu->quat); if (vu->dt) { vcopy (dquat, vu->rot_axis); vnormal (vu->rot_axis); vu->rot_speed = 2 * acos (dquat[3]) / vu->dt; } } } if (vu->buttons & (1 << GLUT_MIDDLE_BUTTON)) { /* scale */ double factor = 1 - ((y - vu->lasty) / height) * 5; demo_view_scale (vu, factor); /* adjust translate so we scale centered at the drag-begin mouse position */ demo_view_translate (vu, +(2. * vu->beginx / width - 1) * (1 - factor), -(2. * vu->beginy / height - 1) * (1 - factor)); } vu->lastx = x; vu->lasty = y; vu->lastt = current_time (); glutPostRedisplay (); } void demo_view_print_help (demo_view_t *vu) { LOGI ("Welcome to GLyphy demo\n"); } static void advance_frame (demo_view_t *vu, long dtime) { if (vu->animate) { float dquat[4]; axis_to_quat (vu->rot_axis, vu->rot_speed * dtime, dquat); add_quats (dquat, vu->quat, vu->quat); vu->num_frames++; } } void demo_view_display (demo_view_t *vu, demo_buffer_t *buffer) { long new_time = current_time (); advance_frame (vu, new_time - vu->last_frame_time); vu->last_frame_time = new_time; int viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); GLint width = viewport[2]; GLint height = viewport[3]; float mat[16]; m4LoadIdentity (mat); demo_view_apply_transform (vu, mat); // Buffer best-fit glyphy_extents_t extents; demo_buffer_extents (buffer, NULL, &extents); double content_scale = .9 * std::min (width / (extents.max_x - extents.min_x), height / (extents.max_y - extents.min_y)); m4Scale (mat, content_scale, content_scale, 1); // Center buffer m4Translate (mat, -(extents.max_x + extents.min_x) / 2., -(extents.max_y + extents.min_y) / 2., 0); demo_glstate_set_matrix (vu->st, mat); glClearColor (1, 1, 1, 1); glClear (GL_COLOR_BUFFER_BIT); demo_buffer_draw (buffer); glutSwapBuffers (); } void demo_view_setup (demo_view_t *vu) { if (!vu->vsync) demo_view_toggle_vsync (vu); if (!vu->srgb) demo_view_toggle_srgb (vu); demo_glstate_setup (vu->st); }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-glstate.h" struct demo_glstate_t { unsigned int refcount; GLuint program; demo_atlas_t *atlas; /* Uniforms */ double u_debug; double u_contrast; double u_gamma_adjust; double u_outline; double u_outline_thickness; double u_boldness; }; demo_glstate_t * demo_glstate_create (void) { TRACE(); demo_glstate_t *st = (demo_glstate_t *) calloc (1, sizeof (demo_glstate_t)); st->refcount = 1; st->program = demo_shader_create_program (); st->atlas = demo_atlas_create (2048, 1024, 64, 8); st->u_debug = false; st->u_contrast = 1.0; st->u_gamma_adjust = 1.0; st->u_outline = false; st->u_outline_thickness = 1.0; st->u_boldness = 0.; return st; } demo_glstate_t * demo_glstate_reference (demo_glstate_t *st) { if (st) st->refcount++; return st; } void demo_glstate_destroy (demo_glstate_t *st) { if (!st || --st->refcount) return; demo_atlas_destroy (st->atlas); glDeleteProgram (st->program); free (st); } static void set_uniform (GLuint program, const char *name, double *p, double value) { *p = value; glUniform1f (glGetUniformLocation (program, name), value); LOGI ("Setting %s to %g\n", name + 2, value); } #define SET_UNIFORM(name, value) set_uniform (st->program, #name, &st->name, value) void demo_glstate_setup (demo_glstate_t *st) { glUseProgram (st->program); demo_atlas_set_uniforms (st->atlas); SET_UNIFORM (u_debug, st->u_debug); SET_UNIFORM (u_contrast, st->u_contrast); SET_UNIFORM (u_gamma_adjust, st->u_gamma_adjust); SET_UNIFORM (u_outline, st->u_outline); SET_UNIFORM (u_outline_thickness, st->u_outline_thickness); SET_UNIFORM (u_boldness, st->u_boldness); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } demo_atlas_t * demo_glstate_get_atlas (demo_glstate_t *st) { return st->atlas; } void demo_glstate_scale_gamma_adjust (demo_glstate_t *st, double factor) { SET_UNIFORM (u_gamma_adjust, clamp (st->u_gamma_adjust * factor, .1, 10.)); } void demo_glstate_scale_contrast (demo_glstate_t *st, double factor) { SET_UNIFORM (u_contrast, clamp (st->u_contrast * factor, .1, 10.)); } void demo_glstate_toggle_debug (demo_glstate_t *st) { SET_UNIFORM (u_debug, 1 - st->u_debug); } void demo_glstate_set_matrix (demo_glstate_t *st, float mat[16]) { glUniformMatrix4fv (glGetUniformLocation (st->program, "u_matViewProjection"), 1, GL_FALSE, mat); } void demo_glstate_toggle_outline (demo_glstate_t *st) { SET_UNIFORM (u_outline, 1 - st->u_outline); } void demo_glstate_scale_outline_thickness (demo_glstate_t *st, double factor) { SET_UNIFORM (u_outline_thickness, clamp (st->u_outline_thickness * factor, .5, 3.)); } void demo_glstate_adjust_boldness (demo_glstate_t *st, double adjustment) { SET_UNIFORM (u_boldness, clamp (st->u_boldness + adjustment, -.2, .7)); }
C++
/* * Copyright 2012 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. * * Google Author(s): Behdad Esfahbod, Maysum Panju, Wojciech Baranowski */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "demo-buffer.h" #include "demo-font.h" #include "demo-view.h" static demo_glstate_t *st; static demo_view_t *vu; static demo_buffer_t *buffer; #define WINDOW_W 700 #define WINDOW_H 700 static void reshape_func (int width, int height) { demo_view_reshape_func (vu, width, height); } static void keyboard_func (unsigned char key, int x, int y) { demo_view_keyboard_func (vu, key, x, y); } static void special_func (int key, int x, int y) { demo_view_special_func (vu, key, x, y); } static void mouse_func (int button, int state, int x, int y) { demo_view_mouse_func (vu, button, state, x, y); } static void motion_func (int x, int y) { demo_view_motion_func (vu, x, y); } static void display_func (void) { demo_view_display (vu, buffer); } int main (int argc, char** argv) { /* Setup glut */ glutInit (&argc, argv); glutInitWindowSize (WINDOW_W, WINDOW_H); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); int window = glutCreateWindow ("GLyphy Demo"); glutReshapeFunc (reshape_func); glutDisplayFunc (display_func); glutKeyboardFunc (keyboard_func); glutSpecialFunc (special_func); glutMouseFunc (mouse_func); glutMotionFunc (motion_func); /* Setup glew */ if (GLEW_OK != glewInit ()) die ("Failed to initialize GL; something really broken"); if (!glewIsSupported ("GL_VERSION_2_0")) die ("OpenGL 2.0 not supported"); if ((argc > 1 && 0 == strcmp (argv[1], "--help")) || argc > 3) { fprintf (stderr, "Usage: %s [FONTFILE [TEXT]]\n", argv[0]); exit (1); } const char *font_path = NULL; if (argc >= 2) font_path = argv[1]; else font_path = DEFAULT_FONT; const char *text = NULL; if (argc >= 3) text = argv[2]; else { # include "jabberwocky.h" text = jabberwocky; } st = demo_glstate_create (); vu = demo_view_create (st); demo_view_print_help (vu); FT_Library ft_library; FT_Init_FreeType (&ft_library); FT_Face ft_face; #ifdef EMSCRIPTEN # include "DroidSans.c" FT_New_Memory_Face (ft_library, (const FT_Byte *) DroidSans, sizeof (DroidSans), 0/*face_index*/, &ft_face); #else FT_New_Face (ft_library, font_path, 0/*face_index*/, &ft_face); #endif if (!ft_face) die ("Failed to open font file"); demo_font_t *font = demo_font_create (ft_face, demo_glstate_get_atlas (st)); buffer = demo_buffer_create (); glyphy_point_t top_left = {0, 0}; demo_buffer_move_to (buffer, &top_left); demo_buffer_add_text (buffer, text, font, 1); demo_font_print_stats (font); demo_view_setup (vu); glutMainLoop (); demo_buffer_destroy (buffer); demo_font_destroy (font); FT_Done_Face (ft_face); FT_Done_FreeType (ft_library); demo_view_destroy (vu); demo_glstate_destroy (st); glutDestroyWindow (window); return 0; }
C++