tesseract  4.0.0-1-g2a2b
tesseract::LSTMRecognizer Class Reference

#include <lstmrecognizer.h>

Inheritance diagram for tesseract::LSTMRecognizer:
tesseract::LSTMTrainer

Public Member Functions

 LSTMRecognizer ()
 
 ~LSTMRecognizer ()
 
int NumOutputs () const
 
int training_iteration () const
 
int sample_iteration () const
 
double learning_rate () const
 
LossType OutputLossType () const
 
bool SimpleTextOutput () const
 
bool IsIntMode () const
 
bool IsRecoding () const
 
bool IsTensorFlow () const
 
GenericVector< STRINGEnumerateLayers () const
 
NetworkGetLayer (const STRING &id) const
 
float GetLayerLearningRate (const STRING &id) const
 
void ScaleLearningRate (double factor)
 
void ScaleLayerLearningRate (const STRING &id, double factor)
 
void ConvertToInt ()
 
const UNICHARSETGetUnicharset () const
 
const UnicharCompressGetRecoder () const
 
const DictGetDict () const
 
void SetIteration (int iteration)
 
int NumInputs () const
 
int null_char () const
 
bool Load (const char *lang, TessdataManager *mgr)
 
bool Serialize (const TessdataManager *mgr, TFile *fp) const
 
bool DeSerialize (const TessdataManager *mgr, TFile *fp)
 
bool LoadCharsets (const TessdataManager *mgr)
 
bool LoadRecoder (TFile *fp)
 
bool LoadDictionary (const char *lang, TessdataManager *mgr)
 
void RecognizeLine (const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0)
 
void OutputStats (const NetworkIO &outputs, float *min_output, float *mean_output, float *sd)
 
bool RecognizeLine (const ImageData &image_data, bool invert, bool debug, bool re_invert, bool upside_down, float *scale_factor, NetworkIO *inputs, NetworkIO *outputs)
 
STRING DecodeLabels (const GenericVector< int > &labels)
 
void DisplayForward (const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
 
void LabelsFromOutputs (const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)
 

Protected Member Functions

void SetRandomSeed ()
 
void DisplayLSTMOutput (const GenericVector< int > &labels, const GenericVector< int > &xcoords, int height, ScrollView *window)
 
void DebugActivationPath (const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
 
void DebugActivationRange (const NetworkIO &outputs, const char *label, int best_choice, int x_start, int x_end)
 
void LabelsViaReEncode (const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)
 
void LabelsViaSimpleText (const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)
 
const char * DecodeLabel (const GenericVector< int > &labels, int start, int *end, int *decoded)
 
const char * DecodeSingleLabel (int label)
 

Protected Attributes

Networknetwork_
 
CCUtil ccutil_
 
UnicharCompress recoder_
 
STRING network_str_
 
int32_t training_flags_
 
int32_t training_iteration_
 
int32_t sample_iteration_
 
int32_t null_char_
 
float learning_rate_
 
float momentum_
 
float adam_beta_
 
TRand randomizer_
 
NetworkScratch scratch_space_
 
Dictdict_
 
RecodeBeamSearchsearch_
 
ScrollViewdebug_win_
 

Detailed Description

Definition at line 53 of file lstmrecognizer.h.

Constructor & Destructor Documentation

◆ LSTMRecognizer()

tesseract::LSTMRecognizer::LSTMRecognizer ( )

Definition at line 49 of file lstmrecognizer.cpp.

◆ ~LSTMRecognizer()

tesseract::LSTMRecognizer::~LSTMRecognizer ( )

Definition at line 62 of file lstmrecognizer.cpp.

62  {
63  delete network_;
64  delete dict_;
65  delete search_;
66 }
RecodeBeamSearch * search_

Member Function Documentation

◆ ConvertToInt()

void tesseract::LSTMRecognizer::ConvertToInt ( )
inline

Definition at line 131 of file lstmrecognizer.h.

131  {
132  if ((training_flags_ & TF_INT_MODE) == 0) {
135  }
136  }
virtual void ConvertToInt()
Definition: network.h:191

◆ DebugActivationPath()

void tesseract::LSTMRecognizer::DebugActivationPath ( const NetworkIO outputs,
const GenericVector< int > &  labels,
const GenericVector< int > &  xcoords 
)
protected

Definition at line 347 of file lstmrecognizer.cpp.

349  {
350  if (xcoords[0] > 0)
351  DebugActivationRange(outputs, "<null>", null_char_, 0, xcoords[0]);
352  int end = 1;
353  for (int start = 0; start < labels.size(); start = end) {
354  if (labels[start] == null_char_) {
355  end = start + 1;
356  DebugActivationRange(outputs, "<null>", null_char_, xcoords[start],
357  xcoords[end]);
358  continue;
359  } else {
360  int decoded;
361  const char* label = DecodeLabel(labels, start, &end, &decoded);
362  DebugActivationRange(outputs, label, labels[start], xcoords[start],
363  xcoords[start + 1]);
364  for (int i = start + 1; i < end; ++i) {
365  DebugActivationRange(outputs, DecodeSingleLabel(labels[i]), labels[i],
366  xcoords[i], xcoords[i + 1]);
367  }
368  }
369  }
370 }
int size() const
Definition: genericvector.h:71
const char * DecodeSingleLabel(int label)
void DebugActivationRange(const NetworkIO &outputs, const char *label, int best_choice, int x_start, int x_end)
const char * DecodeLabel(const GenericVector< int > &labels, int start, int *end, int *decoded)

◆ DebugActivationRange()

void tesseract::LSTMRecognizer::DebugActivationRange ( const NetworkIO outputs,
const char *  label,
int  best_choice,
int  x_start,
int  x_end 
)
protected

Definition at line 374 of file lstmrecognizer.cpp.

376  {
377  tprintf("%s=%d On [%d, %d), scores=", label, best_choice, x_start, x_end);
378  double max_score = 0.0;
379  double mean_score = 0.0;
380  const int width = x_end - x_start;
381  for (int x = x_start; x < x_end; ++x) {
382  const float* line = outputs.f(x);
383  const double score = line[best_choice] * 100.0;
384  if (score > max_score) max_score = score;
385  mean_score += score / width;
386  int best_c = 0;
387  double best_score = 0.0;
388  for (int c = 0; c < outputs.NumFeatures(); ++c) {
389  if (c != best_choice && line[c] > best_score) {
390  best_c = c;
391  best_score = line[c];
392  }
393  }
394  tprintf(" %.3g(%s=%d=%.3g)", score, DecodeSingleLabel(best_c), best_c,
395  best_score * 100.0);
396  }
397  tprintf(", Mean=%g, max=%g\n", mean_score, max_score);
398 }
const char * DecodeSingleLabel(int label)
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37

◆ DecodeLabel()

const char * tesseract::LSTMRecognizer::DecodeLabel ( const GenericVector< int > &  labels,
int  start,
int *  end,
int *  decoded 
)
protected

Definition at line 462 of file lstmrecognizer.cpp.

463  {
464  *end = start + 1;
465  if (IsRecoding()) {
466  // Decode labels via recoder_.
467  RecodedCharID code;
468  if (labels[start] == null_char_) {
469  if (decoded != nullptr) {
470  code.Set(0, null_char_);
471  *decoded = recoder_.DecodeUnichar(code);
472  }
473  return "<null>";
474  }
475  int index = start;
476  while (index < labels.size() &&
477  code.length() < RecodedCharID::kMaxCodeLen) {
478  code.Set(code.length(), labels[index++]);
479  while (index < labels.size() && labels[index] == null_char_) ++index;
480  int uni_id = recoder_.DecodeUnichar(code);
481  // If the next label isn't a valid first code, then we need to continue
482  // extending even if we have a valid uni_id from this prefix.
483  if (uni_id != INVALID_UNICHAR_ID &&
484  (index == labels.size() ||
485  code.length() == RecodedCharID::kMaxCodeLen ||
486  recoder_.IsValidFirstCode(labels[index]))) {
487  *end = index;
488  if (decoded != nullptr) *decoded = uni_id;
489  if (uni_id == UNICHAR_SPACE) return " ";
490  return GetUnicharset().get_normed_unichar(uni_id);
491  }
492  }
493  return "<Undecodable>";
494  } else {
495  if (decoded != nullptr) *decoded = labels[start];
496  if (labels[start] == null_char_) return "<null>";
497  if (labels[start] == UNICHAR_SPACE) return " ";
498  return GetUnicharset().get_normed_unichar(labels[start]);
499  }
500 }
const UNICHARSET & GetUnicharset() const
static const int kMaxCodeLen
int size() const
Definition: genericvector.h:71
int DecodeUnichar(const RecodedCharID &code) const
const char * get_normed_unichar(UNICHAR_ID unichar_id) const
Definition: unicharset.h:823
bool IsValidFirstCode(int code) const

◆ DecodeLabels()

STRING tesseract::LSTMRecognizer::DecodeLabels ( const GenericVector< int > &  labels)

Definition at line 289 of file lstmrecognizer.cpp.

289  {
290  STRING result;
291  int end = 1;
292  for (int start = 0; start < labels.size(); start = end) {
293  if (labels[start] == null_char_) {
294  end = start + 1;
295  } else {
296  result += DecodeLabel(labels, start, &end, nullptr);
297  }
298  }
299  return result;
300 }
int size() const
Definition: genericvector.h:71
const char * DecodeLabel(const GenericVector< int > &labels, int start, int *end, int *decoded)
Definition: strngs.h:45

◆ DecodeSingleLabel()

const char * tesseract::LSTMRecognizer::DecodeSingleLabel ( int  label)
protected

Definition at line 504 of file lstmrecognizer.cpp.

504  {
505  if (label == null_char_) return "<null>";
506  if (IsRecoding()) {
507  // Decode label via recoder_.
508  RecodedCharID code;
509  code.Set(0, label);
510  label = recoder_.DecodeUnichar(code);
511  if (label == INVALID_UNICHAR_ID) return ".."; // Part of a bigger code.
512  }
513  if (label == UNICHAR_SPACE) return " ";
514  return GetUnicharset().get_normed_unichar(label);
515 }
const UNICHARSET & GetUnicharset() const
int DecodeUnichar(const RecodedCharID &code) const
const char * get_normed_unichar(UNICHAR_ID unichar_id) const
Definition: unicharset.h:823

◆ DeSerialize()

bool tesseract::LSTMRecognizer::DeSerialize ( const TessdataManager mgr,
TFile fp 
)

Definition at line 99 of file lstmrecognizer.cpp.

99  {
100  delete network_;
102  if (network_ == nullptr) return false;
103  bool include_charsets = mgr == nullptr ||
104  !mgr->IsComponentAvailable(TESSDATA_LSTM_RECODER) ||
105  !mgr->IsComponentAvailable(TESSDATA_LSTM_UNICHARSET);
106  if (include_charsets && !ccutil_.unicharset.load_from_file(fp, false))
107  return false;
108  if (!network_str_.DeSerialize(fp)) return false;
109  if (!fp->DeSerialize(&training_flags_)) return false;
110  if (!fp->DeSerialize(&training_iteration_)) return false;
111  if (!fp->DeSerialize(&sample_iteration_)) return false;
112  if (!fp->DeSerialize(&null_char_)) return false;
113  if (!fp->DeSerialize(&adam_beta_)) return false;
114  if (!fp->DeSerialize(&learning_rate_)) return false;
115  if (!fp->DeSerialize(&momentum_)) return false;
116  if (include_charsets && !LoadRecoder(fp)) return false;
117  if (!include_charsets && !LoadCharsets(mgr)) return false;
120  return true;
121 }
bool LoadCharsets(const TessdataManager *mgr)
virtual void CacheXScaleFactor(int factor)
Definition: network.h:215
static Network * CreateFromFile(TFile *fp)
Definition: network.cpp:199
bool DeSerialize(bool swap, FILE *fp)
Definition: strngs.cpp:161
virtual void SetRandomizer(TRand *randomizer)
Definition: network.cpp:138
virtual int XScaleFactor() const
Definition: network.h:209
UNICHARSET unicharset
Definition: ccutil.h:68
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:383

◆ DisplayForward()

void tesseract::LSTMRecognizer::DisplayForward ( const NetworkIO inputs,
const GenericVector< int > &  labels,
const GenericVector< int > &  label_coords,
const char *  window_name,
ScrollView **  window 
)

Definition at line 304 of file lstmrecognizer.cpp.

308  {
309 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics
310  Pix* input_pix = inputs.ToPix();
311  Network::ClearWindow(false, window_name, pixGetWidth(input_pix),
312  pixGetHeight(input_pix), window);
313  int line_height = Network::DisplayImage(input_pix, *window);
314  DisplayLSTMOutput(labels, label_coords, line_height, *window);
315 #endif // GRAPHICS_DISABLED
316 }
static void ClearWindow(bool tess_coords, const char *window_name, int width, int height, ScrollView **window)
Definition: network.cpp:306
void DisplayLSTMOutput(const GenericVector< int > &labels, const GenericVector< int > &xcoords, int height, ScrollView *window)
static int DisplayImage(Pix *pix, ScrollView *window)
Definition: network.cpp:329

◆ DisplayLSTMOutput()

void tesseract::LSTMRecognizer::DisplayLSTMOutput ( const GenericVector< int > &  labels,
const GenericVector< int > &  xcoords,
int  height,
ScrollView window 
)
protected

Definition at line 320 of file lstmrecognizer.cpp.

322  {
323 #ifndef GRAPHICS_DISABLED // do nothing if there's no graphics
324  int x_scale = network_->XScaleFactor();
325  window->TextAttributes("Arial", height / 4, false, false, false);
326  int end = 1;
327  for (int start = 0; start < labels.size(); start = end) {
328  int xpos = xcoords[start] * x_scale;
329  if (labels[start] == null_char_) {
330  end = start + 1;
331  window->Pen(ScrollView::RED);
332  } else {
333  window->Pen(ScrollView::GREEN);
334  const char* str = DecodeLabel(labels, start, &end, nullptr);
335  if (*str == '\\') str = "\\\\";
336  xpos = xcoords[(start + end) / 2] * x_scale;
337  window->Text(xpos, height, str);
338  }
339  window->Line(xpos, 0, xpos, height * 3 / 2);
340  }
341  window->Update();
342 #endif // GRAPHICS_DISABLED
343 }
void TextAttributes(const char *font, int pixel_size, bool bold, bool italic, bool underlined)
Definition: scrollview.cpp:637
int size() const
Definition: genericvector.h:71
const char * DecodeLabel(const GenericVector< int > &labels, int start, int *end, int *decoded)
static void Update()
Definition: scrollview.cpp:711
virtual int XScaleFactor() const
Definition: network.h:209
void Text(int x, int y, const char *mystring)
Definition: scrollview.cpp:654
void Pen(Color color)
Definition: scrollview.cpp:722
void Line(int x1, int y1, int x2, int y2)
Definition: scrollview.cpp:534

◆ EnumerateLayers()

GenericVector<STRING> tesseract::LSTMRecognizer::EnumerateLayers ( ) const
inline

Definition at line 86 of file lstmrecognizer.h.

86  {
87  ASSERT_HOST(network_ != nullptr && network_->type() == NT_SERIES);
88  Series* series = static_cast<Series*>(network_);
89  GenericVector<STRING> layers;
90  series->EnumerateLayers(nullptr, &layers);
91  return layers;
92  }
NetworkType type() const
Definition: network.h:112
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ GetDict()

const Dict* tesseract::LSTMRecognizer::GetDict ( ) const
inline

Definition at line 143 of file lstmrecognizer.h.

143 { return dict_; }

◆ GetLayer()

Network* tesseract::LSTMRecognizer::GetLayer ( const STRING id) const
inline

Definition at line 94 of file lstmrecognizer.h.

94  {
95  ASSERT_HOST(network_ != nullptr && network_->type() == NT_SERIES);
96  ASSERT_HOST(id.length() > 1 && id[0] == ':');
97  Series* series = static_cast<Series*>(network_);
98  return series->GetLayer(&id[1]);
99  }
NetworkType type() const
Definition: network.h:112
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ GetLayerLearningRate()

float tesseract::LSTMRecognizer::GetLayerLearningRate ( const STRING id) const
inline

Definition at line 101 of file lstmrecognizer.h.

101  {
102  ASSERT_HOST(network_ != nullptr && network_->type() == NT_SERIES);
104  ASSERT_HOST(id.length() > 1 && id[0] == ':');
105  Series* series = static_cast<Series*>(network_);
106  return series->LayerLearningRate(&id[1]);
107  } else {
108  return learning_rate_;
109  }
110  }
NetworkType type() const
Definition: network.h:112
bool TestFlag(NetworkFlags flag) const
Definition: network.h:144
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ GetRecoder()

const UnicharCompress& tesseract::LSTMRecognizer::GetRecoder ( ) const
inline

Definition at line 141 of file lstmrecognizer.h.

141 { return recoder_; }

◆ GetUnicharset()

const UNICHARSET& tesseract::LSTMRecognizer::GetUnicharset ( ) const
inline

Definition at line 139 of file lstmrecognizer.h.

139 { return ccutil_.unicharset; }
UNICHARSET unicharset
Definition: ccutil.h:68

◆ IsIntMode()

bool tesseract::LSTMRecognizer::IsIntMode ( ) const
inline

Definition at line 77 of file lstmrecognizer.h.

◆ IsRecoding()

bool tesseract::LSTMRecognizer::IsRecoding ( ) const
inline

Definition at line 79 of file lstmrecognizer.h.

◆ IsTensorFlow()

bool tesseract::LSTMRecognizer::IsTensorFlow ( ) const
inline

Definition at line 83 of file lstmrecognizer.h.

83 { return network_->type() == NT_TENSORFLOW; }
NetworkType type() const
Definition: network.h:112

◆ LabelsFromOutputs()

void tesseract::LSTMRecognizer::LabelsFromOutputs ( const NetworkIO outputs,
GenericVector< int > *  labels,
GenericVector< int > *  xcoords 
)

Definition at line 417 of file lstmrecognizer.cpp.

419  {
420  if (SimpleTextOutput()) {
421  LabelsViaSimpleText(outputs, labels, xcoords);
422  } else {
423  LabelsViaReEncode(outputs, labels, xcoords);
424  }
425 }
void LabelsViaReEncode(const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)
void LabelsViaSimpleText(const NetworkIO &output, GenericVector< int > *labels, GenericVector< int > *xcoords)

◆ LabelsViaReEncode()

void tesseract::LSTMRecognizer::LabelsViaReEncode ( const NetworkIO output,
GenericVector< int > *  labels,
GenericVector< int > *  xcoords 
)
protected

Definition at line 429 of file lstmrecognizer.cpp.

431  {
432  if (search_ == nullptr) {
433  search_ =
434  new RecodeBeamSearch(recoder_, null_char_, SimpleTextOutput(), dict_);
435  }
436  search_->Decode(output, 1.0, 0.0, RecodeBeamSearch::kMinCertainty, nullptr);
437  search_->ExtractBestPathAsLabels(labels, xcoords);
438 }
void ExtractBestPathAsLabels(GenericVector< int > *labels, GenericVector< int > *xcoords) const
Definition: recodebeam.cpp:140
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset, int lstm_choice_mode=0)
Definition: recodebeam.cpp:82
static const float kMinCertainty
Definition: recodebeam.h:222
RecodeBeamSearch * search_

◆ LabelsViaSimpleText()

void tesseract::LSTMRecognizer::LabelsViaSimpleText ( const NetworkIO output,
GenericVector< int > *  labels,
GenericVector< int > *  xcoords 
)
protected

Definition at line 443 of file lstmrecognizer.cpp.

445  {
446  labels->truncate(0);
447  xcoords->truncate(0);
448  const int width = output.Width();
449  for (int t = 0; t < width; ++t) {
450  float score = 0.0f;
451  const int label = output.BestLabel(t, &score);
452  if (label != null_char_) {
453  labels->push_back(label);
454  xcoords->push_back(t);
455  }
456  }
457  xcoords->push_back(width);
458 }
int push_back(T object)
void truncate(int size)

◆ learning_rate()

double tesseract::LSTMRecognizer::learning_rate ( ) const
inline

Definition at line 67 of file lstmrecognizer.h.

67  {
68  return learning_rate_;
69  }

◆ Load()

bool tesseract::LSTMRecognizer::Load ( const char *  lang,
TessdataManager mgr 
)

Definition at line 69 of file lstmrecognizer.cpp.

69  {
70  TFile fp;
71  if (!mgr->GetComponent(TESSDATA_LSTM, &fp)) return false;
72  if (!DeSerialize(mgr, &fp)) return false;
73  if (lang == nullptr) return true;
74  // Allow it to run without a dictionary.
75  LoadDictionary(lang, mgr);
76  return true;
77 }
bool LoadDictionary(const char *lang, TessdataManager *mgr)
bool DeSerialize(const TessdataManager *mgr, TFile *fp)

◆ LoadCharsets()

bool tesseract::LSTMRecognizer::LoadCharsets ( const TessdataManager mgr)

Definition at line 124 of file lstmrecognizer.cpp.

124  {
125  TFile fp;
126  if (!mgr->GetComponent(TESSDATA_LSTM_UNICHARSET, &fp)) return false;
127  if (!ccutil_.unicharset.load_from_file(&fp, false)) return false;
128  if (!mgr->GetComponent(TESSDATA_LSTM_RECODER, &fp)) return false;
129  if (!LoadRecoder(&fp)) return false;
130  return true;
131 }
UNICHARSET unicharset
Definition: ccutil.h:68
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:383

◆ LoadDictionary()

bool tesseract::LSTMRecognizer::LoadDictionary ( const char *  lang,
TessdataManager mgr 
)

Definition at line 157 of file lstmrecognizer.cpp.

157  {
158  delete dict_;
159  dict_ = new Dict(&ccutil_);
161  dict_->LoadLSTM(lang, mgr);
162  if (dict_->FinishLoad()) return true; // Success.
163  tprintf("Failed to load any lstm-specific dictionaries for lang %s!!\n",
164  lang);
165  delete dict_;
166  dict_ = nullptr;
167  return false;
168 }
static DawgCache * GlobalDawgCache()
Definition: dict.cpp:193
bool FinishLoad()
Definition: dict.cpp:323
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
void LoadLSTM(const STRING &lang, TessdataManager *data_file)
Definition: dict.cpp:302
void SetupForLoad(DawgCache *dawg_cache)
Definition: dict.cpp:201

◆ LoadRecoder()

bool tesseract::LSTMRecognizer::LoadRecoder ( TFile fp)

Definition at line 134 of file lstmrecognizer.cpp.

134  {
135  if (IsRecoding()) {
136  if (!recoder_.DeSerialize(fp)) return false;
137  RecodedCharID code;
139  if (code(0) != UNICHAR_SPACE) {
140  tprintf("Space was garbled in recoding!!\n");
141  return false;
142  }
143  } else {
146  }
147  return true;
148 }
const UNICHARSET & GetUnicharset() const
int EncodeUnichar(int unichar_id, RecodedCharID *code) const
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
void SetupPassThrough(const UNICHARSET &unicharset)

◆ null_char()

int tesseract::LSTMRecognizer::null_char ( ) const
inline

Definition at line 154 of file lstmrecognizer.h.

154 { return null_char_; }

◆ NumInputs()

int tesseract::LSTMRecognizer::NumInputs ( ) const
inline

Definition at line 151 of file lstmrecognizer.h.

151  {
152  return network_->NumInputs();
153  }
int NumInputs() const
Definition: network.h:120

◆ NumOutputs()

int tesseract::LSTMRecognizer::NumOutputs ( ) const
inline

Definition at line 58 of file lstmrecognizer.h.

58  {
59  return network_->NumOutputs();
60  }
int NumOutputs() const
Definition: network.h:123

◆ OutputLossType()

LossType tesseract::LSTMRecognizer::OutputLossType ( ) const
inline

Definition at line 70 of file lstmrecognizer.h.

70  {
71  if (network_ == nullptr) return LT_NONE;
72  StaticShape shape;
73  shape = network_->OutputShape(shape);
74  return shape.loss_type();
75  }
LossType loss_type() const
Definition: static_shape.h:50
virtual StaticShape OutputShape(const StaticShape &input_shape) const
Definition: network.h:133

◆ OutputStats()

void tesseract::LSTMRecognizer::OutputStats ( const NetworkIO outputs,
float *  min_output,
float *  mean_output,
float *  sd 
)

Definition at line 194 of file lstmrecognizer.cpp.

195  {
196  const int kOutputScale = INT8_MAX;
197  STATS stats(0, kOutputScale + 1);
198  for (int t = 0; t < outputs.Width(); ++t) {
199  int best_label = outputs.BestLabel(t, nullptr);
200  if (best_label != null_char_) {
201  float best_output = outputs.f(t)[best_label];
202  stats.add(static_cast<int>(kOutputScale * best_output), 1);
203  }
204  }
205  // If the output is all nulls it could be that the photometric interpretation
206  // is wrong, so make it look bad, so the other way can win, even if not great.
207  if (stats.get_total() == 0) {
208  *min_output = 0.0f;
209  *mean_output = 0.0f;
210  *sd = 1.0f;
211  } else {
212  *min_output = static_cast<float>(stats.min_bucket()) / kOutputScale;
213  *mean_output = stats.mean() / kOutputScale;
214  *sd = stats.sd() / kOutputScale;
215  }
216 }
Definition: statistc.h:33

◆ RecognizeLine() [1/2]

void tesseract::LSTMRecognizer::RecognizeLine ( const ImageData image_data,
bool  invert,
bool  debug,
double  worst_dict_cert,
const TBOX line_box,
PointerVector< WERD_RES > *  words,
int  lstm_choice_mode = 0 
)

Definition at line 172 of file lstmrecognizer.cpp.

176  {
177  NetworkIO outputs;
178  float scale_factor;
179  NetworkIO inputs;
180  if (!RecognizeLine(image_data, invert, debug, false, false, &scale_factor,
181  &inputs, &outputs))
182  return;
183  if (search_ == nullptr) {
184  search_ =
185  new RecodeBeamSearch(recoder_, null_char_, SimpleTextOutput(), dict_);
186  }
187  search_->Decode(outputs, kDictRatio, kCertOffset, worst_dict_cert,
188  &GetUnicharset(), lstm_choice_mode);
189  search_->ExtractBestPathAsWords(line_box, scale_factor, debug,
190  &GetUnicharset(), words, lstm_choice_mode);
191 }
const UNICHARSET & GetUnicharset() const
void Decode(const NetworkIO &output, double dict_ratio, double cert_offset, double worst_dict_cert, const UNICHARSET *charset, int lstm_choice_mode=0)
Definition: recodebeam.cpp:82
const double kCertOffset
void RecognizeLine(const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words, int lstm_choice_mode=0)
const double kDictRatio
void ExtractBestPathAsWords(const TBOX &line_box, float scale_factor, bool debug, const UNICHARSET *unicharset, PointerVector< WERD_RES > *words, int lstm_choice_mode=0)
Definition: recodebeam.cpp:178
RecodeBeamSearch * search_

◆ RecognizeLine() [2/2]

bool tesseract::LSTMRecognizer::RecognizeLine ( const ImageData image_data,
bool  invert,
bool  debug,
bool  re_invert,
bool  upside_down,
float *  scale_factor,
NetworkIO inputs,
NetworkIO outputs 
)

Definition at line 220 of file lstmrecognizer.cpp.

223  {
224  // Maximum width of image to train on.
225  const int kMaxImageWidth = 2560;
226  // This ensures consistent recognition results.
227  SetRandomSeed();
228  int min_width = network_->XScaleFactor();
229  Pix* pix = Input::PrepareLSTMInputs(image_data, network_, min_width,
230  &randomizer_, scale_factor);
231  if (pix == nullptr) {
232  tprintf("Line cannot be recognized!!\n");
233  return false;
234  }
235  if (network_->IsTraining() && pixGetWidth(pix) > kMaxImageWidth) {
236  tprintf("Image too large to learn!! Size = %dx%d\n", pixGetWidth(pix),
237  pixGetHeight(pix));
238  pixDestroy(&pix);
239  return false;
240  }
241  if (upside_down) pixRotate180(pix, pix);
242  // Reduction factor from image to coords.
243  *scale_factor = min_width / *scale_factor;
244  inputs->set_int_mode(IsIntMode());
245  SetRandomSeed();
247  network_->Forward(debug, *inputs, nullptr, &scratch_space_, outputs);
248  // Check for auto inversion.
249  float pos_min, pos_mean, pos_sd;
250  OutputStats(*outputs, &pos_min, &pos_mean, &pos_sd);
251  if (invert && pos_min < 0.5) {
252  // Run again inverted and see if it is any better.
253  NetworkIO inv_inputs, inv_outputs;
254  inv_inputs.set_int_mode(IsIntMode());
255  SetRandomSeed();
256  pixInvert(pix, pix);
258  &inv_inputs);
259  network_->Forward(debug, inv_inputs, nullptr, &scratch_space_, &inv_outputs);
260  float inv_min, inv_mean, inv_sd;
261  OutputStats(inv_outputs, &inv_min, &inv_mean, &inv_sd);
262  if (inv_min > pos_min && inv_mean > pos_mean && inv_sd < pos_sd) {
263  // Inverted did better. Use inverted data.
264  if (debug) {
265  tprintf("Inverting image: old min=%g, mean=%g, sd=%g, inv %g,%g,%g\n",
266  pos_min, pos_mean, pos_sd, inv_min, inv_mean, inv_sd);
267  }
268  *outputs = inv_outputs;
269  *inputs = inv_inputs;
270  } else if (re_invert) {
271  // Inverting was not an improvement, so undo and run again, so the
272  // outputs match the best forward result.
273  SetRandomSeed();
274  network_->Forward(debug, *inputs, nullptr, &scratch_space_, outputs);
275  }
276  }
277  pixDestroy(&pix);
278  if (debug) {
279  GenericVector<int> labels, coords;
280  LabelsFromOutputs(*outputs, &labels, &coords);
281  DisplayForward(*inputs, labels, coords, "LSTMForward", &debug_win_);
282  DebugActivationPath(*outputs, labels, coords);
283  }
284  return true;
285 }
virtual void Forward(bool debug, const NetworkIO &input, const TransposedArray *input_transpose, NetworkScratch *scratch, NetworkIO *output)
Definition: network.h:262
NetworkScratch scratch_space_
virtual int XScaleFactor() const
Definition: network.h:209
virtual StaticShape InputShape() const
Definition: network.h:127
void DebugActivationPath(const NetworkIO &outputs, const GenericVector< int > &labels, const GenericVector< int > &xcoords)
void DisplayForward(const NetworkIO &inputs, const GenericVector< int > &labels, const GenericVector< int > &label_coords, const char *window_name, ScrollView **window)
void OutputStats(const NetworkIO &outputs, float *min_output, float *mean_output, float *sd)
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
static void PreparePixInput(const StaticShape &shape, const Pix *pix, TRand *randomizer, NetworkIO *input)
Definition: input.cpp:112
bool IsTraining() const
Definition: network.h:115
static Pix * PrepareLSTMInputs(const ImageData &image_data, const Network *network, int min_width, TRand *randomizer, float *image_scale)
Definition: input.cpp:84
void LabelsFromOutputs(const NetworkIO &outputs, GenericVector< int > *labels, GenericVector< int > *xcoords)

◆ sample_iteration()

int tesseract::LSTMRecognizer::sample_iteration ( ) const
inline

Definition at line 64 of file lstmrecognizer.h.

64  {
65  return sample_iteration_;
66  }

◆ ScaleLayerLearningRate()

void tesseract::LSTMRecognizer::ScaleLayerLearningRate ( const STRING id,
double  factor 
)
inline

Definition at line 123 of file lstmrecognizer.h.

123  {
124  ASSERT_HOST(network_ != nullptr && network_->type() == NT_SERIES);
125  ASSERT_HOST(id.length() > 1 && id[0] == ':');
126  Series* series = static_cast<Series*>(network_);
127  series->ScaleLayerLearningRate(&id[1], factor);
128  }
NetworkType type() const
Definition: network.h:112
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ ScaleLearningRate()

void tesseract::LSTMRecognizer::ScaleLearningRate ( double  factor)
inline

Definition at line 112 of file lstmrecognizer.h.

112  {
113  ASSERT_HOST(network_ != nullptr && network_->type() == NT_SERIES);
114  learning_rate_ *= factor;
117  for (int i = 0; i < layers.size(); ++i) {
118  ScaleLayerLearningRate(layers[i], factor);
119  }
120  }
121  }
int size() const
Definition: genericvector.h:71
void ScaleLayerLearningRate(const STRING &id, double factor)
NetworkType type() const
Definition: network.h:112
GenericVector< STRING > EnumerateLayers() const
bool TestFlag(NetworkFlags flag) const
Definition: network.h:144
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ Serialize()

bool tesseract::LSTMRecognizer::Serialize ( const TessdataManager mgr,
TFile fp 
) const

Definition at line 80 of file lstmrecognizer.cpp.

80  {
81  bool include_charsets = mgr == nullptr ||
82  !mgr->IsComponentAvailable(TESSDATA_LSTM_RECODER) ||
83  !mgr->IsComponentAvailable(TESSDATA_LSTM_UNICHARSET);
84  if (!network_->Serialize(fp)) return false;
85  if (include_charsets && !GetUnicharset().save_to_file(fp)) return false;
86  if (!network_str_.Serialize(fp)) return false;
87  if (!fp->Serialize(&training_flags_)) return false;
88  if (!fp->Serialize(&training_iteration_)) return false;
89  if (!fp->Serialize(&sample_iteration_)) return false;
90  if (!fp->Serialize(&null_char_)) return false;
91  if (!fp->Serialize(&adam_beta_)) return false;
92  if (!fp->Serialize(&learning_rate_)) return false;
93  if (!fp->Serialize(&momentum_)) return false;
94  if (include_charsets && IsRecoding() && !recoder_.Serialize(fp)) return false;
95  return true;
96 }
bool Serialize(FILE *fp) const
Definition: strngs.cpp:148
const UNICHARSET & GetUnicharset() const
bool save_to_file(const char *const filename) const
Definition: unicharset.h:345
virtual bool Serialize(TFile *fp) const
Definition: network.cpp:151
bool Serialize(TFile *fp) const

◆ SetIteration()

void tesseract::LSTMRecognizer::SetIteration ( int  iteration)
inline

Definition at line 147 of file lstmrecognizer.h.

147  {
148  sample_iteration_ = iteration;
149  }

◆ SetRandomSeed()

void tesseract::LSTMRecognizer::SetRandomSeed ( )
inlineprotected

Definition at line 225 of file lstmrecognizer.h.

225  {
226  int64_t seed = static_cast<int64_t>(sample_iteration_) * 0x10000001;
227  randomizer_.set_seed(seed);
229  }
int32_t IntRand()
Definition: helpers.h:56
void set_seed(uint64_t seed)
Definition: helpers.h:46

◆ SimpleTextOutput()

bool tesseract::LSTMRecognizer::SimpleTextOutput ( ) const
inline

Definition at line 76 of file lstmrecognizer.h.

◆ training_iteration()

int tesseract::LSTMRecognizer::training_iteration ( ) const
inline

Definition at line 61 of file lstmrecognizer.h.

61  {
62  return training_iteration_;
63  }

Member Data Documentation

◆ adam_beta_

float tesseract::LSTMRecognizer::adam_beta_
protected

Definition at line 295 of file lstmrecognizer.h.

◆ ccutil_

CCUtil tesseract::LSTMRecognizer::ccutil_
protected

Definition at line 273 of file lstmrecognizer.h.

◆ debug_win_

ScrollView* tesseract::LSTMRecognizer::debug_win_
protected

Definition at line 307 of file lstmrecognizer.h.

◆ dict_

Dict* tesseract::LSTMRecognizer::dict_
protected

Definition at line 301 of file lstmrecognizer.h.

◆ learning_rate_

float tesseract::LSTMRecognizer::learning_rate_
protected

Definition at line 292 of file lstmrecognizer.h.

◆ momentum_

float tesseract::LSTMRecognizer::momentum_
protected

Definition at line 293 of file lstmrecognizer.h.

◆ network_

Network* tesseract::LSTMRecognizer::network_
protected

Definition at line 270 of file lstmrecognizer.h.

◆ network_str_

STRING tesseract::LSTMRecognizer::network_str_
protected

Definition at line 280 of file lstmrecognizer.h.

◆ null_char_

int32_t tesseract::LSTMRecognizer::null_char_
protected

Definition at line 290 of file lstmrecognizer.h.

◆ randomizer_

TRand tesseract::LSTMRecognizer::randomizer_
protected

Definition at line 298 of file lstmrecognizer.h.

◆ recoder_

UnicharCompress tesseract::LSTMRecognizer::recoder_
protected

Definition at line 277 of file lstmrecognizer.h.

◆ sample_iteration_

int32_t tesseract::LSTMRecognizer::sample_iteration_
protected

Definition at line 287 of file lstmrecognizer.h.

◆ scratch_space_

NetworkScratch tesseract::LSTMRecognizer::scratch_space_
protected

Definition at line 299 of file lstmrecognizer.h.

◆ search_

RecodeBeamSearch* tesseract::LSTMRecognizer::search_
protected

Definition at line 303 of file lstmrecognizer.h.

◆ training_flags_

int32_t tesseract::LSTMRecognizer::training_flags_
protected

Definition at line 283 of file lstmrecognizer.h.

◆ training_iteration_

int32_t tesseract::LSTMRecognizer::training_iteration_
protected

Definition at line 285 of file lstmrecognizer.h.


The documentation for this class was generated from the following files: