code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
///////////////////////////////////////////////////////////////////////
// File: unichar.cpp
// Description: Unicode character/ligature class.
// Author: Ray Smith
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "unichar.h"
#include "errcode.h"
#include "genericvector.h"
#include "tprintf.h"
#define UNI_MAX_LEGAL_UTF32 0x0010FFFF
// Construct from a utf8 string. If len<0 then the string is null terminated.
// If the string is too long to fit in the UNICHAR then it takes only what
// will fit. Checks for illegal input and stops at an illegal sequence.
// The resulting UNICHAR may be empty.
UNICHAR::UNICHAR(const char* utf8_str, int len) {
int total_len = 0;
int step = 0;
if (len < 0) {
for (len = 0; len < UNICHAR_LEN && utf8_str[len] != 0; ++len);
}
for (total_len = 0; total_len < len; total_len += step) {
step = utf8_step(utf8_str + total_len);
if (total_len + step > UNICHAR_LEN)
break; // Too long.
if (step == 0)
break; // Illegal first byte.
int i;
for (i = 1; i < step; ++i)
if ((utf8_str[total_len + i] & 0xc0) != 0x80)
break;
if (i < step)
break; // Illegal surrogate
}
memcpy(chars, utf8_str, total_len);
if (total_len < UNICHAR_LEN) {
chars[UNICHAR_LEN - 1] = total_len;
while (total_len < UNICHAR_LEN - 1)
chars[total_len++] = 0;
}
}
// Construct from a single UCS4 character. Illegal values are ignored,
// resulting in an empty UNICHAR.
UNICHAR::UNICHAR(int unicode) {
const int bytemask = 0xBF;
const int bytemark = 0x80;
if (unicode < 0x80) {
chars[UNICHAR_LEN - 1] = 1;
chars[2] = 0;
chars[1] = 0;
chars[0] = static_cast<char>(unicode);
} else if (unicode < 0x800) {
chars[UNICHAR_LEN - 1] = 2;
chars[2] = 0;
chars[1] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[0] = static_cast<char>(unicode | 0xc0);
} else if (unicode < 0x10000) {
chars[UNICHAR_LEN - 1] = 3;
chars[2] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[1] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[0] = static_cast<char>(unicode | 0xe0);
} else if (unicode <= UNI_MAX_LEGAL_UTF32) {
chars[UNICHAR_LEN - 1] = 4;
chars[3] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[2] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[1] = static_cast<char>((unicode | bytemark) & bytemask);
unicode >>= 6;
chars[0] = static_cast<char>(unicode | 0xf0);
} else {
memset(chars, 0, UNICHAR_LEN);
}
}
// Get the first character as UCS-4.
int UNICHAR::first_uni() const {
static const int utf8_offsets[5] = {
0, 0, 0x3080, 0xE2080, 0x3C82080
};
int uni = 0;
int len = utf8_step(chars);
const char* src = chars;
switch (len) {
default:
break;
case 4:
uni += static_cast<unsigned char>(*src++);
uni <<= 6;
case 3:
uni += static_cast<unsigned char>(*src++);
uni <<= 6;
case 2:
uni += static_cast<unsigned char>(*src++);
uni <<= 6;
case 1:
uni += static_cast<unsigned char>(*src++);
}
uni -= utf8_offsets[len];
return uni;
}
// Get a terminated UTF8 string: Must delete[] it after use.
char* UNICHAR::utf8_str() const {
int len = utf8_len();
char* str = new char[len + 1];
memcpy(str, chars, len);
str[len] = 0;
return str;
}
// Get the number of bytes in the first character of the given utf8 string.
int UNICHAR::utf8_step(const char* utf8_str) {
static const char utf8_bytes[256] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0
};
return utf8_bytes[static_cast<unsigned char>(*utf8_str)];
}
UNICHAR::const_iterator& UNICHAR::const_iterator::operator++() {
ASSERT_HOST(it_ != NULL);
int step = utf8_step(it_);
if (step == 0) {
tprintf("ERROR: Illegal UTF8 encountered.\n");
for (int i = 0; i < 5 && it_[i] != '\0'; ++i) {
tprintf("Index %d char = 0x%x\n", i, it_[i]);
}
step = 1;
}
it_ += step;
return *this;
}
int UNICHAR::const_iterator::operator*() const {
ASSERT_HOST(it_ != NULL);
const int len = utf8_step(it_);
if (len == 0) {
tprintf("WARNING: Illegal UTF8 encountered\n");
return ' ';
}
UNICHAR uch(it_, len);
return uch.first_uni();
}
int UNICHAR::const_iterator::get_utf8(char* utf8_output) const {
ASSERT_HOST(it_ != NULL);
const int len = utf8_step(it_);
if (len == 0) {
tprintf("WARNING: Illegal UTF8 encountered\n");
utf8_output[0] = ' ';
return 1;
}
strncpy(utf8_output, it_, len);
return len;
}
int UNICHAR::const_iterator::utf8_len() const {
ASSERT_HOST(it_ != NULL);
const int len = utf8_step(it_);
if (len == 0) {
tprintf("WARNING: Illegal UTF8 encountered\n");
return 1;
}
return len;
}
bool UNICHAR::const_iterator::is_legal() const {
return utf8_step(it_) > 0;
}
UNICHAR::const_iterator UNICHAR::begin(const char* utf8_str, const int len) {
return UNICHAR::const_iterator(utf8_str);
}
UNICHAR::const_iterator UNICHAR::end(const char* utf8_str, const int len) {
return UNICHAR::const_iterator(utf8_str + len);
}
// Converts a utf-8 string to a vector of unicodes.
void UNICHAR::UTF8ToUnicode(const char* utf8_str,
GenericVector<int>* unicodes) {
const int utf8_length = strlen(utf8_str);
const_iterator end_it(end(utf8_str, utf8_length));
for (const_iterator it(begin(utf8_str, utf8_length)); it != end_it; ++it) {
unicodes->push_back(*it);
}
}
| C++ |
/**********************************************************************
* File: basedir.c (Formerly getpath.c)
* Description: Find the directory location of the current executable using PATH.
* Author: Ray Smith
* Created: Mon Jul 09 09:06:39 BST 1990
*
* (C) Copyright 1990, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "basedir.h"
#include <stdlib.h>
// Assuming that code_path is the name of some file in a desired directory,
// returns the given code_path stripped back to the last slash, leaving
// the last slash in place. If there is no slash, returns ./ assuming that
// the input was the name of something in the current directory.
// Useful for getting to the directory of argv[0], but does not search
// any paths.
TESS_API void truncate_path(const char *code_path, STRING* trunc_path) {
int trunc_index = -1;
if (code_path != NULL) {
const char* last_slash = strrchr(code_path, '/');
if (last_slash != NULL && last_slash + 1 - code_path > trunc_index)
trunc_index = last_slash + 1 - code_path;
last_slash = strrchr(code_path, '\\');
if (last_slash != NULL && last_slash + 1 - code_path > trunc_index)
trunc_index = last_slash + 1 - code_path;
}
*trunc_path = code_path;
if (trunc_index >= 0)
trunc_path->truncate_at(trunc_index);
else
*trunc_path = "./";
}
| C++ |
/**********************************************************************
* File: bits16.h (Formerly bits8.h)
* Description: Code for 8 bit field class.
* Author: Phil Cheatle
* Created: Thu Oct 17 10:10:05 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef BITS16_H
#define BITS16_H
#include "host.h"
class DLLSYM BITS16
{
public:
uinT16 val;
BITS16() {
val = 0;
} // constructor
BITS16( // constructor
uinT16 init); // initial val
void turn_on_bit( // flip specified bit
uinT8 bit_num) { // bit to flip 0..7
val = val | 01 << bit_num;
};
void turn_off_bit( // flip specified bit
uinT8 bit_num) { // bit to flip 0..7
val = val & ~(01 << bit_num);
};
void set_bit( // flip specified bit
uinT8 bit_num, // bit to flip 0..7
BOOL8 value) { // value to flip to
if (value)
val = val | 01 << bit_num;
else
val = val & ~(01 << bit_num);
};
BOOL8 bit( // access bit
uinT8 bit_num) const { // bit to access
return (val >> bit_num) & 01;
};
};
#endif
| C++ |
/**********************************************************************
* File: elst.h (Formerly elist.h)
* Description: Embedded list module include file.
* Author: Phil Cheatle
* Created: Mon Jan 07 08:35:34 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef ELST_H
#define ELST_H
#include <stdio.h>
#include "host.h"
#include "serialis.h"
#include "lsterr.h"
class ELIST_ITERATOR;
/**********************************************************************
This module implements list classes and iterators.
The following list types and iterators are provided:
List type List Class Iterator Class Element Class
--------- ---------- -------------- -------------
Embedded list ELIST
ELIST_ITERATOR
ELIST_LINK
(Single linked)
Embedded list ELIST2
ELIST2_ITERATOR
ELIST2_LINK
(Double linked)
Cons List CLIST
CLIST_ITERATOR
CLIST_LINK
(Single linked)
Cons List CLIST2
CLIST2_ITERATOR
CLIST2_LINK
(Double linked)
An embedded list is where the list pointers are provided by a generic class.
Data types to be listed inherit from the generic class. Data is thus linked
in only ONE list at any one time.
A cons list has a separate structure for a "cons cell". This contains the
list pointer(s) AND a pointer to the data structure held on the list. A
structure can be on many cons lists at the same time, and the structure does
not need to inherit from any generic class in order to be on the list.
The implementation of lists is very careful about space and speed overheads.
This is why many embedded lists are provided. The same concerns mean that
in-line type coercion is done, rather than use virtual functions. This is
cumbersome in that each data type to be listed requires its own iterator and
list class - though macros can gererate these. It also prevents heterogenous
lists.
**********************************************************************/
/**********************************************************************
* CLASS - ELIST_LINK
*
* Generic link class for singly linked lists with embedded links
*
* Note: No destructor - elements are assumed to be destroyed EITHER after
* they have been extracted from a list OR by the ELIST destructor which
* walks the list.
**********************************************************************/
class DLLSYM ELIST_LINK
{
friend class ELIST_ITERATOR;
friend class ELIST;
ELIST_LINK *next;
public:
ELIST_LINK() {
next = NULL;
}
//constructor
ELIST_LINK(const ELIST_LINK &) { // don't copy link.
next = NULL;
}
void operator= ( //dont copy links
const ELIST_LINK &) {
next = NULL;
}
};
/**********************************************************************
* CLASS - ELIST
*
* Generic list class for singly linked lists with embedded links
**********************************************************************/
class DLLSYM ELIST
{
friend class ELIST_ITERATOR;
ELIST_LINK *last; //End of list
//(Points to head)
ELIST_LINK *First() { // return first
return last ? last->next : NULL;
}
public:
ELIST() { //constructor
last = NULL;
}
void internal_clear ( //destroy all links
//ptr to zapper functn
void (*zapper) (ELIST_LINK *));
bool empty() const { //is list empty?
return !last;
}
bool singleton() const {
return last ? (last == last->next) : false;
}
void shallow_copy( //dangerous!!
ELIST *from_list) { //beware destructors!!
last = from_list->last;
}
//ptr to copier functn
void internal_deep_copy (ELIST_LINK * (*copier) (ELIST_LINK *),
const ELIST * list); //list being copied
void assign_to_sublist( //to this list
ELIST_ITERATOR *start_it, //from list start
ELIST_ITERATOR *end_it); //from list end
inT32 length() const; // # elements in list
void sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *));
// Assuming list has been sorted already, insert new_link to
// keep the list sorted according to the same comparison function.
// Comparision function is the same as used by sort, i.e. uses double
// indirection. Time is O(1) to add to beginning or end.
// Time is linear to add pre-sorted items to an empty list.
// If unique is set to true and comparator() returns 0 (an entry with the
// same information as the one contained in new_link is already in the
// list) - new_link is not added to the list and the function returns the
// pointer to the identical entry that already exists in the list
// (otherwise the function returns new_link).
ELIST_LINK *add_sorted_and_find(int comparator(const void*, const void*),
bool unique, ELIST_LINK* new_link);
// Same as above, but returns true if the new entry was inserted, false
// if the identical entry already existed in the list.
bool add_sorted(int comparator(const void*, const void*),
bool unique, ELIST_LINK* new_link) {
return (add_sorted_and_find(comparator, unique, new_link) == new_link);
}
};
/***********************************************************************
* CLASS - ELIST_ITERATOR
*
* Generic iterator class for singly linked lists with embedded links
**********************************************************************/
class DLLSYM ELIST_ITERATOR
{
friend void ELIST::assign_to_sublist(ELIST_ITERATOR *, ELIST_ITERATOR *);
ELIST *list; //List being iterated
ELIST_LINK *prev; //prev element
ELIST_LINK *current; //current element
ELIST_LINK *next; //next element
bool ex_current_was_last; //current extracted
//was end of list
bool ex_current_was_cycle_pt; //current extracted
//was cycle point
ELIST_LINK *cycle_pt; //point we are cycling
//the list to.
bool started_cycling; //Have we moved off
//the start?
ELIST_LINK *extract_sublist( //from this current...
ELIST_ITERATOR *other_it); //to other current
public:
ELIST_ITERATOR() { //constructor
list = NULL;
} //unassigned list
explicit ELIST_ITERATOR(ELIST *list_to_iterate);
void set_to_list( //change list
ELIST *list_to_iterate);
void add_after_then_move( //add after current &
ELIST_LINK *new_link); //move to new
void add_after_stay_put( //add after current &
ELIST_LINK *new_link); //stay at current
void add_before_then_move( //add before current &
ELIST_LINK *new_link); //move to new
void add_before_stay_put( //add before current &
ELIST_LINK *new_link); //stay at current
void add_list_after( //add a list &
ELIST *list_to_add); //stay at current
void add_list_before( //add a list &
ELIST *list_to_add); //move to it 1st item
ELIST_LINK *data() { //get current data
#ifndef NDEBUG
if (!list)
NO_LIST.error ("ELIST_ITERATOR::data", ABORT, NULL);
if (!current)
NULL_DATA.error ("ELIST_ITERATOR::data", ABORT, NULL);
#endif
return current;
}
ELIST_LINK *data_relative( //get data + or - ...
inT8 offset); //offset from current
ELIST_LINK *forward(); //move to next element
ELIST_LINK *extract(); //remove from list
ELIST_LINK *move_to_first(); //go to start of list
ELIST_LINK *move_to_last(); //go to end of list
void mark_cycle_pt(); //remember current
bool empty() { //is list empty?
#ifndef NDEBUG
if (!list)
NO_LIST.error ("ELIST_ITERATOR::empty", ABORT, NULL);
#endif
return list->empty ();
}
bool current_extracted() { //current extracted?
return !current;
}
bool at_first(); //Current is first?
bool at_last(); //Current is last?
bool cycled_list(); //Completed a cycle?
void add_to_end( //add at end &
ELIST_LINK *new_link); //dont move
void exchange( //positions of 2 links
ELIST_ITERATOR *other_it); //other iterator
inT32 length(); //# elements in list
void sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *));
};
/***********************************************************************
* ELIST_ITERATOR::set_to_list
*
* (Re-)initialise the iterator to point to the start of the list_to_iterate
* over.
**********************************************************************/
inline void ELIST_ITERATOR::set_to_list( //change list
ELIST *list_to_iterate) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::set_to_list", ABORT, NULL);
if (!list_to_iterate)
BAD_PARAMETER.error ("ELIST_ITERATOR::set_to_list", ABORT,
"list_to_iterate is NULL");
#endif
list = list_to_iterate;
prev = list->last;
current = list->First ();
next = current ? current->next : NULL;
cycle_pt = NULL; //await explicit set
started_cycling = FALSE;
ex_current_was_last = FALSE;
ex_current_was_cycle_pt = FALSE;
}
/***********************************************************************
* ELIST_ITERATOR::ELIST_ITERATOR
*
* CONSTRUCTOR - set iterator to specified list;
**********************************************************************/
inline ELIST_ITERATOR::ELIST_ITERATOR(ELIST *list_to_iterate) {
set_to_list(list_to_iterate);
}
/***********************************************************************
* ELIST_ITERATOR::add_after_then_move
*
* Add a new element to the list after the current element and move the
* iterator to the new element.
**********************************************************************/
inline void ELIST_ITERATOR::add_after_then_move( // element to add
ELIST_LINK *new_element) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_after_then_move", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_after_then_move", ABORT, NULL);
if (!new_element)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_after_then_move", ABORT,
"new_element is NULL");
if (new_element->next)
STILL_LINKED.error ("ELIST_ITERATOR::add_after_then_move", ABORT, NULL);
#endif
if (list->empty ()) {
new_element->next = new_element;
list->last = new_element;
prev = next = new_element;
}
else {
new_element->next = next;
if (current) { //not extracted
current->next = new_element;
prev = current;
if (current == list->last)
list->last = new_element;
}
else { //current extracted
prev->next = new_element;
if (ex_current_was_last)
list->last = new_element;
if (ex_current_was_cycle_pt)
cycle_pt = new_element;
}
}
current = new_element;
}
/***********************************************************************
* ELIST_ITERATOR::add_after_stay_put
*
* Add a new element to the list after the current element but do not move
* the iterator to the new element.
**********************************************************************/
inline void ELIST_ITERATOR::add_after_stay_put( // element to add
ELIST_LINK *new_element) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_after_stay_put", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_after_stay_put", ABORT, NULL);
if (!new_element)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_after_stay_put", ABORT,
"new_element is NULL");
if (new_element->next)
STILL_LINKED.error ("ELIST_ITERATOR::add_after_stay_put", ABORT, NULL);
#endif
if (list->empty ()) {
new_element->next = new_element;
list->last = new_element;
prev = next = new_element;
ex_current_was_last = FALSE;
current = NULL;
}
else {
new_element->next = next;
if (current) { //not extracted
current->next = new_element;
if (prev == current)
prev = new_element;
if (current == list->last)
list->last = new_element;
}
else { //current extracted
prev->next = new_element;
if (ex_current_was_last) {
list->last = new_element;
ex_current_was_last = FALSE;
}
}
next = new_element;
}
}
/***********************************************************************
* ELIST_ITERATOR::add_before_then_move
*
* Add a new element to the list before the current element and move the
* iterator to the new element.
**********************************************************************/
inline void ELIST_ITERATOR::add_before_then_move( // element to add
ELIST_LINK *new_element) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_before_then_move", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_before_then_move", ABORT, NULL);
if (!new_element)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_before_then_move", ABORT,
"new_element is NULL");
if (new_element->next)
STILL_LINKED.error ("ELIST_ITERATOR::add_before_then_move", ABORT, NULL);
#endif
if (list->empty ()) {
new_element->next = new_element;
list->last = new_element;
prev = next = new_element;
}
else {
prev->next = new_element;
if (current) { //not extracted
new_element->next = current;
next = current;
}
else { //current extracted
new_element->next = next;
if (ex_current_was_last)
list->last = new_element;
if (ex_current_was_cycle_pt)
cycle_pt = new_element;
}
}
current = new_element;
}
/***********************************************************************
* ELIST_ITERATOR::add_before_stay_put
*
* Add a new element to the list before the current element but dont move the
* iterator to the new element.
**********************************************************************/
inline void ELIST_ITERATOR::add_before_stay_put( // element to add
ELIST_LINK *new_element) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_before_stay_put", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_before_stay_put", ABORT, NULL);
if (!new_element)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_before_stay_put", ABORT,
"new_element is NULL");
if (new_element->next)
STILL_LINKED.error ("ELIST_ITERATOR::add_before_stay_put", ABORT, NULL);
#endif
if (list->empty ()) {
new_element->next = new_element;
list->last = new_element;
prev = next = new_element;
ex_current_was_last = TRUE;
current = NULL;
}
else {
prev->next = new_element;
if (current) { //not extracted
new_element->next = current;
if (next == current)
next = new_element;
}
else { //current extracted
new_element->next = next;
if (ex_current_was_last)
list->last = new_element;
}
prev = new_element;
}
}
/***********************************************************************
* ELIST_ITERATOR::add_list_after
*
* Insert another list to this list after the current element but dont move the
* iterator.
**********************************************************************/
inline void ELIST_ITERATOR::add_list_after(ELIST *list_to_add) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_list_after", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_list_after", ABORT, NULL);
if (!list_to_add)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_list_after", ABORT,
"list_to_add is NULL");
#endif
if (!list_to_add->empty ()) {
if (list->empty ()) {
list->last = list_to_add->last;
prev = list->last;
next = list->First ();
ex_current_was_last = TRUE;
current = NULL;
}
else {
if (current) { //not extracted
current->next = list_to_add->First ();
if (current == list->last)
list->last = list_to_add->last;
list_to_add->last->next = next;
next = current->next;
}
else { //current extracted
prev->next = list_to_add->First ();
if (ex_current_was_last) {
list->last = list_to_add->last;
ex_current_was_last = FALSE;
}
list_to_add->last->next = next;
next = prev->next;
}
}
list_to_add->last = NULL;
}
}
/***********************************************************************
* ELIST_ITERATOR::add_list_before
*
* Insert another list to this list before the current element. Move the
* iterator to the start of the inserted elements
* iterator.
**********************************************************************/
inline void ELIST_ITERATOR::add_list_before(ELIST *list_to_add) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_list_before", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_list_before", ABORT, NULL);
if (!list_to_add)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_list_before", ABORT,
"list_to_add is NULL");
#endif
if (!list_to_add->empty ()) {
if (list->empty ()) {
list->last = list_to_add->last;
prev = list->last;
current = list->First ();
next = current->next;
ex_current_was_last = FALSE;
}
else {
prev->next = list_to_add->First ();
if (current) { //not extracted
list_to_add->last->next = current;
}
else { //current extracted
list_to_add->last->next = next;
if (ex_current_was_last)
list->last = list_to_add->last;
if (ex_current_was_cycle_pt)
cycle_pt = prev->next;
}
current = prev->next;
next = current->next;
}
list_to_add->last = NULL;
}
}
/***********************************************************************
* ELIST_ITERATOR::extract
*
* Do extraction by removing current from the list, returning it to the
* caller, but NOT updating the iterator. (So that any calling loop can do
* this.) The iterator's current points to NULL. If the extracted element
* is to be deleted, this is the callers responsibility.
**********************************************************************/
inline ELIST_LINK *ELIST_ITERATOR::extract() {
ELIST_LINK *extracted_link;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::extract", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::extract", ABORT, NULL);
if (!current) //list empty or
//element extracted
NULL_CURRENT.error ("ELIST_ITERATOR::extract",
ABORT, NULL);
#endif
if (list->singleton()) {
// Special case where we do need to change the iterator.
prev = next = list->last = NULL;
} else {
prev->next = next; //remove from list
if (current == list->last) {
list->last = prev;
ex_current_was_last = TRUE;
} else {
ex_current_was_last = FALSE;
}
}
// Always set ex_current_was_cycle_pt so an add/forward will work in a loop.
ex_current_was_cycle_pt = (current == cycle_pt) ? TRUE : FALSE;
extracted_link = current;
extracted_link->next = NULL; //for safety
current = NULL;
return extracted_link;
}
/***********************************************************************
* ELIST_ITERATOR::move_to_first()
*
* Move current so that it is set to the start of the list.
* Return data just in case anyone wants it.
**********************************************************************/
inline ELIST_LINK *ELIST_ITERATOR::move_to_first() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::move_to_first", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::move_to_first", ABORT, NULL);
#endif
current = list->First ();
prev = list->last;
next = current ? current->next : NULL;
return current;
}
/***********************************************************************
* ELIST_ITERATOR::mark_cycle_pt()
*
* Remember the current location so that we can tell whether we've returned
* to this point later.
*
* If the current point is deleted either now, or in the future, the cycle
* point will be set to the next item which is set to current. This could be
* by a forward, add_after_then_move or add_after_then_move.
**********************************************************************/
inline void ELIST_ITERATOR::mark_cycle_pt() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::mark_cycle_pt", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::mark_cycle_pt", ABORT, NULL);
#endif
if (current)
cycle_pt = current;
else
ex_current_was_cycle_pt = TRUE;
started_cycling = FALSE;
}
/***********************************************************************
* ELIST_ITERATOR::at_first()
*
* Are we at the start of the list?
*
**********************************************************************/
inline bool ELIST_ITERATOR::at_first() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::at_first", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::at_first", ABORT, NULL);
#endif
//we're at a deleted
return ((list->empty ()) || (current == list->First ()) || ((current == NULL) &&
(prev == list->last) && //NON-last pt between
!ex_current_was_last)); //first and last
}
/***********************************************************************
* ELIST_ITERATOR::at_last()
*
* Are we at the end of the list?
*
**********************************************************************/
inline bool ELIST_ITERATOR::at_last() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::at_last", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::at_last", ABORT, NULL);
#endif
//we're at a deleted
return ((list->empty ()) || (current == list->last) || ((current == NULL) &&
(prev == list->last) && //last point between
ex_current_was_last)); //first and last
}
/***********************************************************************
* ELIST_ITERATOR::cycled_list()
*
* Have we returned to the cycle_pt since it was set?
*
**********************************************************************/
inline bool ELIST_ITERATOR::cycled_list() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::cycled_list", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::cycled_list", ABORT, NULL);
#endif
return ((list->empty ()) || ((current == cycle_pt) && started_cycling));
}
/***********************************************************************
* ELIST_ITERATOR::length()
*
* Return the length of the list
*
**********************************************************************/
inline inT32 ELIST_ITERATOR::length() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::length", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::length", ABORT, NULL);
#endif
return list->length ();
}
/***********************************************************************
* ELIST_ITERATOR::sort()
*
* Sort the elements of the list, then reposition at the start.
*
**********************************************************************/
inline void
ELIST_ITERATOR::sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *)) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::sort", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::sort", ABORT, NULL);
#endif
list->sort (comparator);
move_to_first();
}
/***********************************************************************
* ELIST_ITERATOR::add_to_end
*
* Add a new element to the end of the list without moving the iterator.
* This is provided because a single linked list cannot move to the last as
* the iterator couldn't set its prev pointer. Adding to the end is
* essential for implementing
queues.
**********************************************************************/
inline void ELIST_ITERATOR::add_to_end( // element to add
ELIST_LINK *new_element) {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::add_to_end", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::add_to_end", ABORT, NULL);
if (!new_element)
BAD_PARAMETER.error ("ELIST_ITERATOR::add_to_end", ABORT,
"new_element is NULL");
if (new_element->next)
STILL_LINKED.error ("ELIST_ITERATOR::add_to_end", ABORT, NULL);
#endif
if (this->at_last ()) {
this->add_after_stay_put (new_element);
}
else {
if (this->at_first ()) {
this->add_before_stay_put (new_element);
list->last = new_element;
}
else { //Iteratr is elsewhere
new_element->next = list->last->next;
list->last->next = new_element;
list->last = new_element;
}
}
}
/***********************************************************************
******************** MACROS **************************************
***********************************************************************/
/***********************************************************************
QUOTE_IT MACRO DEFINITION
===========================
Replace <parm> with "<parm>". <parm> may be an arbitrary number of tokens
***********************************************************************/
#define QUOTE_IT( parm ) #parm
/***********************************************************************
ELISTIZE( CLASSNAME ) MACRO
============================
CLASSNAME is assumed to be the name of a class which has a baseclass of
ELIST_LINK.
NOTE: Because we dont use virtual functions in the list code, the list code
will NOT work correctly for classes derived from this.
The macros generate:
- An element deletion function: CLASSNAME##_zapper
- An E_LIST subclass: CLASSNAME##_LIST
- An E_LIST_ITERATOR subclass: CLASSNAME##_IT
NOTE: Generated names are DELIBERATELY designed to clash with those for
ELIST2IZE but NOT with those for CLISTIZE and CLIST2IZE
Two macros are provided: ELISTIZE and ELISTIZEH.
The ...IZEH macros just define the class names for use in .h files
The ...IZE macros define the code use in .c files
***********************************************************************/
/***********************************************************************
ELISTIZEH( CLASSNAME ) MACRO
ELISTIZEH is a concatenation of 3 fragments ELISTIZEH_A, ELISTIZEH_B and
ELISTIZEH_C.
***********************************************************************/
#define ELISTIZEH_A(CLASSNAME) \
\
extern DLLSYM void CLASSNAME##_zapper(ELIST_LINK* link);
#define ELISTIZEH_B(CLASSNAME) \
\
/*********************************************************************** \
* CLASS - CLASSNAME##_LIST \
* \
* List class for class CLASSNAME \
* \
**********************************************************************/ \
\
class DLLSYM CLASSNAME##_LIST : public ELIST { \
public: \
CLASSNAME##_LIST():ELIST() {} \
\
void clear() { /* delete elements */\
ELIST::internal_clear(&CLASSNAME##_zapper); \
} \
\
~CLASSNAME##_LIST() { \
clear(); \
} \
\
/* Become a deep copy of src_list*/ \
void deep_copy(const CLASSNAME##_LIST* src_list, \
CLASSNAME* (*copier)(const CLASSNAME*)); \
\
private: \
/* Prevent assign and copy construction. */ \
CLASSNAME##_LIST(const CLASSNAME##_LIST&) { \
DONT_CONSTRUCT_LIST_BY_COPY.error(QUOTE_IT(CLASSNAME##_LIST), ABORT, NULL);\
} \
void operator=(const CLASSNAME##_LIST&) { \
DONT_ASSIGN_LISTS.error(QUOTE_IT(CLASSNAME##_LIST), ABORT, NULL ); \
} \
#define ELISTIZEH_C( CLASSNAME ) \
}; \
\
\
\
/*********************************************************************** \
* CLASS - CLASSNAME##_IT \
* \
* Iterator class for class CLASSNAME##_LIST \
* \
* Note: We don't need to coerce pointers to member functions input \
* parameters as these are automatically converted to the type of the base \
* type. ("A ptr to a class may be converted to a pointer to a public base \
* class of that class") \
**********************************************************************/ \
\
class DLLSYM CLASSNAME##_IT : public ELIST_ITERATOR { \
public: \
CLASSNAME##_IT():ELIST_ITERATOR(){} \
\
/* TODO(rays) This constructor should be explicit, but that means changing \
hundreds of incorrect initializations of iterators that use = over () */ \
CLASSNAME##_IT(CLASSNAME##_LIST* list) : ELIST_ITERATOR(list) {} \
\
CLASSNAME* data() { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::data()); \
} \
\
CLASSNAME* data_relative(inT8 offset) { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::data_relative(offset));\
} \
\
CLASSNAME* forward() { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::forward()); \
} \
\
CLASSNAME* extract() { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::extract()); \
} \
\
CLASSNAME* move_to_first() { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::move_to_first()); \
} \
\
CLASSNAME* move_to_last() { \
return reinterpret_cast<CLASSNAME*>(ELIST_ITERATOR::move_to_last()); \
} \
};
#define ELISTIZEH( CLASSNAME ) \
\
ELISTIZEH_A( CLASSNAME ) \
\
ELISTIZEH_B( CLASSNAME ) \
\
ELISTIZEH_C( CLASSNAME )
/***********************************************************************
ELISTIZE( CLASSNAME ) MACRO
***********************************************************************/
#define ELISTIZE(CLASSNAME) \
\
/*********************************************************************** \
* CLASSNAME##_zapper \
* \
* A function which can delete a CLASSNAME element. This is passed to the \
* generic clear list member function so that when a list is cleared the \
* elements on the list are properly destroyed from the base class, even \
* though we dont use a virtual destructor function. \
**********************************************************************/ \
\
DLLSYM void CLASSNAME##_zapper(ELIST_LINK* link) { \
delete reinterpret_cast<CLASSNAME*>(link); \
} \
\
/* Become a deep copy of src_list*/ \
void CLASSNAME##_LIST::deep_copy(const CLASSNAME##_LIST* src_list, \
CLASSNAME* (*copier)(const CLASSNAME*)) { \
\
CLASSNAME##_IT from_it(const_cast<CLASSNAME##_LIST*>(src_list)); \
CLASSNAME##_IT to_it(this); \
\
for (from_it.mark_cycle_pt(); !from_it.cycled_list(); from_it.forward()) \
to_it.add_after_then_move((*copier)(from_it.data())); \
}
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: unicharmap.h
// Description: Unicode character/ligature to integer id class.
// Author: Thomas Kielbus
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_UNICHARMAP_H__
#define TESSERACT_CCUTIL_UNICHARMAP_H__
#include "unichar.h"
// A UNICHARMAP stores unique unichars. Each of them is associated with one
// UNICHAR_ID.
class UNICHARMAP {
public:
// Create an empty UNICHARMAP
UNICHARMAP();
~UNICHARMAP();
// Insert the given unichar represention in the UNICHARMAP and associate it
// with the given id. The length of the representation MUST be non-zero.
void insert(const char* const unichar_repr, UNICHAR_ID id);
// Return the id associated with the given unichar representation,
// this representation MUST exist within the UNICHARMAP.
// The length of the representation MUST be non-zero.
UNICHAR_ID unichar_to_id(const char* const unichar_repr) const;
// Return the id associated with the given unichar representation,
// this representation MUST exist within the UNICHARMAP. The first
// length characters (maximum) from unichar_repr are used. The length
// MUST be non-zero.
UNICHAR_ID unichar_to_id(const char* const unichar_repr, int length) const;
// Return true if the given unichar representation is already present in the
// UNICHARMAP. The length of the representation MUST be non-zero.
bool contains(const char* const unichar_repr) const;
// Return true if the given unichar representation is already present in the
// UNICHARMAP. The first length characters (maximum) from unichar_repr are
// used. The length MUST be non-zero.
bool contains(const char* const unichar_repr, int length) const;
// Return the minimum number of characters that must be used from this string
// to obtain a match in the UNICHARMAP.
int minmatch(const char* const unichar_repr) const;
// Clear the UNICHARMAP. All previous data is lost.
void clear();
private:
// The UNICHARMAP is represented as a tree whose nodes are of type
// UNICHARMAP_NODE.
struct UNICHARMAP_NODE {
UNICHARMAP_NODE();
~UNICHARMAP_NODE();
UNICHARMAP_NODE* children;
UNICHAR_ID id;
};
UNICHARMAP_NODE* nodes;
};
#endif // TESSERACT_CCUTIL_UNICHARMAP_H__
| C++ |
// Copyright 2012 Google Inc. All Rights Reserved.
// Author: rays@google.com (Ray Smith)
///////////////////////////////////////////////////////////////////////
// File: kdpair.h
// Description: Template pair class like STL pair but geared towards
// the Key+Data design pattern in which some data needs
// to be sorted or kept in a heap sorted on some separate key.
// Author: Ray Smith.
// Created: Thu Mar 15 14:48:05 PDT 2012
//
// (C) Copyright 2012, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_KDPAIR_H_
#define TESSERACT_CCUTIL_KDPAIR_H_
#include "genericvector.h"
namespace tesseract {
// A useful base struct to facilitate the common operation of sorting a vector
// of simple or smart-pointer data using a separate key. Similar to STL pair.
template <typename Key, typename Data>
struct KDPair {
KDPair() {}
KDPair(Key k, Data d) : data(d), key(k) {}
int operator==(const KDPair<Key, Data>& other) const {
return key == other.key;
}
// WARNING! Keep data as the first element! KDPairInc and KDPairDec depend
// on the order of these elements so they can downcast pointers appropriately
// for use by GenericHeap::Reshuffle.
Data data;
Key key;
};
// Specialization of KDPair to provide operator< for sorting in increasing order
// and recasting of data pointers for use with DoublePtr.
template <typename Key, typename Data>
struct KDPairInc : public KDPair<Key, Data> {
KDPairInc() {}
KDPairInc(Key k, Data d) : KDPair<Key, Data>(k, d) {}
// Operator< facilitates sorting in increasing order.
int operator<(const KDPairInc<Key, Data>& other) const {
return this->key < other.key;
}
// Returns the input Data pointer recast to a KDPairInc pointer.
// Just casts a pointer to the first element to a pointer to the whole struct.
static KDPairInc* RecastDataPointer(Data* data_ptr) {
return reinterpret_cast<KDPairInc*>(data_ptr);
}
};
// Specialization of KDPair to provide operator< for sorting in decreasing order
// and recasting of data pointers for use with DoublePtr.
template <typename Key, typename Data>
struct KDPairDec : public KDPair<Key, Data> {
KDPairDec() {}
KDPairDec(Key k, Data d) : KDPair<Key, Data>(k, d) {}
// Operator< facilitates sorting in decreasing order by using operator> on
// the key values.
int operator<(const KDPairDec<Key, Data>& other) const {
return this->key > other.key;
}
// Returns the input Data pointer recast to a KDPairDec pointer.
// Just casts a pointer to the first element to a pointer to the whole struct.
static KDPairDec* RecastDataPointer(Data* data_ptr) {
return reinterpret_cast<KDPairDec*>(data_ptr);
}
};
// A useful base class to facilitate the common operation of sorting a vector
// of owned pointer data using a separate key. This class owns its data pointer,
// deleting it when it has finished with it, and providing copy constructor and
// operator= that have move semantics so that the data does not get copied and
// only a single instance of KDPtrPair holds a specific data pointer.
template <typename Key, typename Data>
class KDPtrPair {
public:
KDPtrPair() : data_(NULL) {}
KDPtrPair(Key k, Data* d) : data_(d), key_(k) {}
// Copy constructor steals the pointer from src and NULLs it in src, thereby
// moving the (single) ownership of the data.
KDPtrPair(KDPtrPair& src) : data_(src.data_), key_(src.key_) {
src.data_ = NULL;
}
// Destructor deletes data, assuming it is the sole owner.
~KDPtrPair() {
delete this->data_;
this->data_ = NULL;
}
// Operator= steals the pointer from src and NULLs it in src, thereby
// moving the (single) ownership of the data.
void operator=(KDPtrPair& src) {
delete this->data_;
this->data_ = src.data_;
src.data_ = NULL;
this->key_ = src.key_;
}
int operator==(const KDPtrPair<Key, Data>& other) const {
return key_ == other.key_;
}
// Accessors.
const Key& key() const {
return key_;
}
void set_key(const Key& new_key) {
key_ = new_key;
}
const Data* data() const {
return data_;
}
// Sets the data pointer, taking ownership of the data.
void set_data(Data* new_data) {
delete data_;
data_ = new_data;
}
// Relinquishes ownership of the data pointer (setting it to NULL).
Data* extract_data() {
Data* result = data_;
data_ = NULL;
return result;
}
private:
// Data members are private to keep deletion of data_ encapsulated.
Data* data_;
Key key_;
};
// Specialization of KDPtrPair to provide operator< for sorting in increasing
// order.
template <typename Key, typename Data>
struct KDPtrPairInc : public KDPtrPair<Key, Data> {
// Since we are doing non-standard stuff we have to duplicate *all* the
// constructors and operator=.
KDPtrPairInc() : KDPtrPair<Key, Data>() {}
KDPtrPairInc(Key k, Data* d) : KDPtrPair<Key, Data>(k, d) {}
KDPtrPairInc(KDPtrPairInc& src) : KDPtrPair<Key, Data>(src) {}
void operator=(KDPtrPairInc& src) {
KDPtrPair<Key, Data>::operator=(src);
}
// Operator< facilitates sorting in increasing order.
int operator<(const KDPtrPairInc<Key, Data>& other) const {
return this->key() < other.key();
}
};
// Specialization of KDPtrPair to provide operator< for sorting in decreasing
// order.
template <typename Key, typename Data>
struct KDPtrPairDec : public KDPtrPair<Key, Data> {
// Since we are doing non-standard stuff we have to duplicate *all* the
// constructors and operator=.
KDPtrPairDec() : KDPtrPair<Key, Data>() {}
KDPtrPairDec(Key k, Data* d) : KDPtrPair<Key, Data>(k, d) {}
KDPtrPairDec(KDPtrPairDec& src) : KDPtrPair<Key, Data>(src) {}
void operator=(KDPtrPairDec& src) {
KDPtrPair<Key, Data>::operator=(src);
}
// Operator< facilitates sorting in decreasing order by using operator> on
// the key values.
int operator<(const KDPtrPairDec<Key, Data>& other) const {
return this->key() > other.key();
}
};
// Specialization for a pair of ints in increasing order.
typedef KDPairInc<int, int> IntKDPair;
// Vector of IntKDPair.
class KDVector : public GenericVector<IntKDPair> {
// TODO(rays) Add some code to manipulate a KDVector. For now there
// is nothing and this class is effectively a specialization typedef.
};
} // namespace tesseract
#endif // TESSERACT_CCUTIL_KDPAIR_H_
| C++ |
/**********************************************************************
* File: elst2.c (Formerly elist2.c)
* Description: Doubly linked embedded list code not in the include file.
* Author: Phil Cheatle
* Created: Wed Jan 23 11:04:47 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <stdlib.h>
#include "host.h"
#include "elst2.h"
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: ELIST2
* =================================
**********************************************************************/
/***********************************************************************
* ELIST2::internal_clear
*
* Used by the destructor and the "clear" member function of derived list
* classes to destroy all the elements on the list.
* The calling function passes a "zapper" function which can be called to
* delete each element of the list, regardless of its derived type. This
* technique permits a generic clear function to destroy elements of
* different derived types correctly, without requiring virtual functions and
* the consequential memory overhead.
**********************************************************************/
void
ELIST2::internal_clear ( //destroy all links
void (*zapper) (ELIST2_LINK *)) {
//ptr to zapper functn
ELIST2_LINK *ptr;
ELIST2_LINK *next;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2::internal_clear", ABORT, NULL);
#endif
if (!empty ()) {
ptr = last->next; //set to first
last->next = NULL; //break circle
last = NULL; //set list empty
while (ptr) {
next = ptr->next;
zapper(ptr);
ptr = next;
}
}
}
/***********************************************************************
* ELIST2::assign_to_sublist
*
* The list is set to a sublist of another list. "This" list must be empty
* before this function is invoked. The two iterators passed must refer to
* the same list, different from "this" one. The sublist removed is the
* inclusive list from start_it's current position to end_it's current
* position. If this range passes over the end of the source list then the
* source list has its end set to the previous element of start_it. The
* extracted sublist is unaffected by the end point of the source list, its
* end point is always the end_it position.
**********************************************************************/
void ELIST2::assign_to_sublist( //to this list
ELIST2_ITERATOR *start_it, //from list start
ELIST2_ITERATOR *end_it) { //from list end
const ERRCODE LIST_NOT_EMPTY =
"Destination list must be empty before extracting a sublist";
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2::assign_to_sublist", ABORT, NULL);
#endif
if (!empty ())
LIST_NOT_EMPTY.error ("ELIST2.assign_to_sublist", ABORT, NULL);
last = start_it->extract_sublist (end_it);
}
/***********************************************************************
* ELIST2::length
*
* Return count of elements on list
**********************************************************************/
inT32 ELIST2::length() const { // count elements
ELIST2_ITERATOR it(const_cast<ELIST2*>(this));
inT32 count = 0;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2::length", ABORT, NULL);
#endif
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
count++;
return count;
}
/***********************************************************************
* ELIST2::sort
*
* Sort elements on list
* NB If you dont like the const declarations in the comparator, coerce yours:
* ( int (*)(const void *, const void *)
**********************************************************************/
void
ELIST2::sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *)) {
ELIST2_ITERATOR it(this);
inT32 count;
ELIST2_LINK **base; //ptr array to sort
ELIST2_LINK **current;
inT32 i;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2::sort", ABORT, NULL);
#endif
/* Allocate an array of pointers, one per list element */
count = length ();
base = (ELIST2_LINK **) malloc (count * sizeof (ELIST2_LINK *));
/* Extract all elements, putting the pointers in the array */
current = base;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
*current = it.extract ();
current++;
}
/* Sort the pointer array */
qsort ((char *) base, count, sizeof (*base), comparator);
/* Rebuild the list from the sorted pointers */
current = base;
for (i = 0; i < count; i++) {
it.add_to_end (*current);
current++;
}
free(base);
}
// Assuming list has been sorted already, insert new_link to
// keep the list sorted according to the same comparison function.
// Comparision function is the same as used by sort, i.e. uses double
// indirection. Time is O(1) to add to beginning or end.
// Time is linear to add pre-sorted items to an empty list.
void ELIST2::add_sorted(int comparator(const void*, const void*),
ELIST2_LINK* new_link) {
// Check for adding at the end.
if (last == NULL || comparator(&last, &new_link) < 0) {
if (last == NULL) {
new_link->next = new_link;
new_link->prev = new_link;
} else {
new_link->next = last->next;
new_link->prev = last;
last->next = new_link;
new_link->next->prev = new_link;
}
last = new_link;
} else {
// Need to use an iterator.
ELIST2_ITERATOR it(this);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
ELIST2_LINK* link = it.data();
if (comparator(&link, &new_link) > 0)
break;
}
if (it.cycled_list())
it.add_to_end(new_link);
else
it.add_before_then_move(new_link);
}
}
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: ELIST2_ITERATOR
* ==========================================
**********************************************************************/
/***********************************************************************
* ELIST2_ITERATOR::forward
*
* Move the iterator to the next element of the list.
* REMEMBER: ALL LISTS ARE CIRCULAR.
**********************************************************************/
ELIST2_LINK *ELIST2_ITERATOR::forward() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2_ITERATOR::forward", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST2_ITERATOR::forward", ABORT, NULL);
#endif
if (list->empty ())
return NULL;
if (current) { //not removed so
//set previous
prev = current;
started_cycling = TRUE;
// In case next is deleted by another iterator, get it from the current.
current = current->next;
}
else {
if (ex_current_was_cycle_pt)
cycle_pt = next;
current = next;
}
next = current->next;
#ifndef NDEBUG
if (!current)
NULL_DATA.error ("ELIST2_ITERATOR::forward", ABORT, NULL);
if (!next)
NULL_NEXT.error ("ELIST2_ITERATOR::forward", ABORT,
"This is: %p Current is: %p", this, current);
#endif
return current;
}
/***********************************************************************
* ELIST2_ITERATOR::backward
*
* Move the iterator to the previous element of the list.
* REMEMBER: ALL LISTS ARE CIRCULAR.
**********************************************************************/
ELIST2_LINK *ELIST2_ITERATOR::backward() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2_ITERATOR::backward", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST2_ITERATOR::backward", ABORT, NULL);
#endif
if (list->empty ())
return NULL;
if (current) { //not removed so
//set previous
next = current;
started_cycling = TRUE;
// In case prev is deleted by another iterator, get it from current.
current = current->prev;
} else {
if (ex_current_was_cycle_pt)
cycle_pt = prev;
current = prev;
}
prev = current->prev;
#ifndef NDEBUG
if (!current)
NULL_DATA.error ("ELIST2_ITERATOR::backward", ABORT, NULL);
if (!prev)
NULL_PREV.error ("ELIST2_ITERATOR::backward", ABORT,
"This is: %p Current is: %p", this, current);
#endif
return current;
}
/***********************************************************************
* ELIST2_ITERATOR::data_relative
*
* Return the data pointer to the element "offset" elements from current.
* (This function can't be INLINEd because it contains a loop)
**********************************************************************/
ELIST2_LINK *ELIST2_ITERATOR::data_relative( //get data + or - ..
inT8 offset) { //offset from current
ELIST2_LINK *ptr;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2_ITERATOR::data_relative", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST2_ITERATOR::data_relative", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("ELIST2_ITERATOR::data_relative", ABORT, NULL);
#endif
if (offset < 0)
for (ptr = current ? current : next; offset++ < 0; ptr = ptr->prev);
else
for (ptr = current ? current : prev; offset-- > 0; ptr = ptr->next);
#ifndef NDEBUG
if (!ptr)
NULL_DATA.error ("ELIST2_ITERATOR::data_relative", ABORT, NULL);
#endif
return ptr;
}
/***********************************************************************
* ELIST2_ITERATOR::exchange()
*
* Given another iterator, whose current element is a different element on
* the same list list OR an element of another list, exchange the two current
* elements. On return, each iterator points to the element which was the
* other iterators current on entry.
* (This function hasn't been in-lined because its a bit big!)
**********************************************************************/
void ELIST2_ITERATOR::exchange( //positions of 2 links
ELIST2_ITERATOR *other_it) { //other iterator
const ERRCODE DONT_EXCHANGE_DELETED =
"Can't exchange deleted elements of lists";
ELIST2_LINK *old_current;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2_ITERATOR::exchange", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST2_ITERATOR::exchange", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("ELIST2_ITERATOR::exchange", ABORT, "other_it NULL");
if (!(other_it->list))
NO_LIST.error ("ELIST2_ITERATOR::exchange", ABORT, "other_it");
#endif
/* Do nothing if either list is empty or if both iterators reference the same
link */
if ((list->empty ()) ||
(other_it->list->empty ()) || (current == other_it->current))
return;
/* Error if either current element is deleted */
if (!current || !other_it->current)
DONT_EXCHANGE_DELETED.error ("ELIST2_ITERATOR.exchange", ABORT, NULL);
/* Now handle the 4 cases: doubleton list; non-doubleton adjacent elements
(other before this); non-doubleton adjacent elements (this before other);
non-adjacent elements. */
//adjacent links
if ((next == other_it->current) ||
(other_it->next == current)) {
//doubleton list
if ((next == other_it->current) &&
(other_it->next == current)) {
prev = next = current;
other_it->prev = other_it->next = other_it->current;
}
else { //non-doubleton with
//adjacent links
//other before this
if (other_it->next == current) {
other_it->prev->next = current;
other_it->current->next = next;
other_it->current->prev = current;
current->next = other_it->current;
current->prev = other_it->prev;
next->prev = other_it->current;
other_it->next = other_it->current;
prev = current;
}
else { //this before other
prev->next = other_it->current;
current->next = other_it->next;
current->prev = other_it->current;
other_it->current->next = current;
other_it->current->prev = prev;
other_it->next->prev = current;
next = current;
other_it->prev = other_it->current;
}
}
}
else { //no overlap
prev->next = other_it->current;
current->next = other_it->next;
current->prev = other_it->prev;
next->prev = other_it->current;
other_it->prev->next = current;
other_it->current->next = next;
other_it->current->prev = prev;
other_it->next->prev = current;
}
/* update end of list pointer when necessary (remember that the 2 iterators
may iterate over different lists!) */
if (list->last == current)
list->last = other_it->current;
if (other_it->list->last == other_it->current)
other_it->list->last = current;
if (current == cycle_pt)
cycle_pt = other_it->cycle_pt;
if (other_it->current == other_it->cycle_pt)
other_it->cycle_pt = cycle_pt;
/* The actual exchange - in all cases*/
old_current = current;
current = other_it->current;
other_it->current = old_current;
}
/***********************************************************************
* ELIST2_ITERATOR::extract_sublist()
*
* This is a private member, used only by ELIST2::assign_to_sublist.
* Given another iterator for the same list, extract the links from THIS to
* OTHER inclusive, link them into a new circular list, and return a
* pointer to the last element.
* (Can't inline this function because it contains a loop)
**********************************************************************/
ELIST2_LINK *ELIST2_ITERATOR::extract_sublist( //from this current
ELIST2_ITERATOR *other_it) { //to other current
#ifndef NDEBUG
const ERRCODE BAD_EXTRACTION_PTS =
"Can't extract sublist from points on different lists";
const ERRCODE DONT_EXTRACT_DELETED =
"Can't extract a sublist marked by deleted points";
#endif
const ERRCODE BAD_SUBLIST = "Can't find sublist end point in original list";
ELIST2_ITERATOR temp_it = *this;
ELIST2_LINK *end_of_new_list;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST2_ITERATOR::extract_sublist", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("ELIST2_ITERATOR::extract_sublist", ABORT,
"other_it NULL");
if (!list)
NO_LIST.error ("ELIST2_ITERATOR::extract_sublist", ABORT, NULL);
if (list != other_it->list)
BAD_EXTRACTION_PTS.error ("ELIST2_ITERATOR.extract_sublist", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("ELIST2_ITERATOR::extract_sublist", ABORT, NULL);
if (!current || !other_it->current)
DONT_EXTRACT_DELETED.error ("ELIST2_ITERATOR.extract_sublist", ABORT,
NULL);
#endif
ex_current_was_last = other_it->ex_current_was_last = FALSE;
ex_current_was_cycle_pt = FALSE;
other_it->ex_current_was_cycle_pt = FALSE;
temp_it.mark_cycle_pt ();
do { //walk sublist
if (temp_it.cycled_list ()) //cant find end pt
BAD_SUBLIST.error ("ELIST2_ITERATOR.extract_sublist", ABORT, NULL);
if (temp_it.at_last ()) {
list->last = prev;
ex_current_was_last = other_it->ex_current_was_last = TRUE;
}
if (temp_it.current == cycle_pt)
ex_current_was_cycle_pt = TRUE;
if (temp_it.current == other_it->cycle_pt)
other_it->ex_current_was_cycle_pt = TRUE;
temp_it.forward ();
}
//do INCLUSIVE list
while (temp_it.prev != other_it->current);
//circularise sublist
other_it->current->next = current;
//circularise sublist
current->prev = other_it->current;
end_of_new_list = other_it->current;
//sublist = whole list
if (prev == other_it->current) {
list->last = NULL;
prev = current = next = NULL;
other_it->prev = other_it->current = other_it->next = NULL;
}
else {
prev->next = other_it->next;
other_it->next->prev = prev;
current = other_it->current = NULL;
next = other_it->next;
other_it->prev = prev;
}
return end_of_new_list;
}
| C++ |
/**********************************************************************
* File: strngs.c (Formerly strings.c)
* Description: STRING class functions.
* Author: Ray Smith
* Created: Fri Feb 15 09:13:30 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "strngs.h"
#include <assert.h>
#include "genericvector.h"
#include "helpers.h"
#include "serialis.h"
#include "tprintf.h"
using tesseract::TFile;
// Size of buffer needed to host the decimal representation of the maximum
// possible length of an int (in 64 bits), being -<20 digits>.
const int kMaxIntSize = 22;
// Size of buffer needed to host the decimal representation of the maximum
// possible length of a %.8g being -0.12345678e+999<nul> = 15.
const int kMaxDoubleSize = 15;
/**********************************************************************
* STRING_HEADER provides metadata about the allocated buffer,
* including total capacity and how much used (strlen with '\0').
*
* The implementation hides this header at the start of the data
* buffer and appends the string on the end to keep sizeof(STRING)
* unchanged from earlier versions so serialization is not affected.
*
* The collection of MACROS provide different implementations depending
* on whether the string keeps track of its strlen or not so that this
* feature can be added in later when consumers dont modifify the string
**********************************************************************/
// Smallest string to allocate by default
const int kMinCapacity = 16;
char* STRING::AllocData(int used, int capacity) {
data_ = (STRING_HEADER *)alloc_string(capacity + sizeof(STRING_HEADER));
// header is the metadata for this memory block
STRING_HEADER* header = GetHeader();
header->capacity_ = capacity;
header->used_ = used;
return GetCStr();
}
void STRING::DiscardData() {
free_string((char *)data_);
}
// This is a private method; ensure FixHeader is called (or used_ is well defined)
// beforehand
char* STRING::ensure_cstr(inT32 min_capacity) {
STRING_HEADER* orig_header = GetHeader();
if (min_capacity <= orig_header->capacity_)
return ((char *)this->data_) + sizeof(STRING_HEADER);
// if we are going to grow bigger, than double our existing
// size, but if that still is not big enough then keep the
// requested capacity
if (min_capacity < 2 * orig_header->capacity_)
min_capacity = 2 * orig_header->capacity_;
int alloc = sizeof(STRING_HEADER) + min_capacity;
STRING_HEADER* new_header = (STRING_HEADER*)(alloc_string(alloc));
memcpy(&new_header[1], GetCStr(), orig_header->used_);
new_header->capacity_ = min_capacity;
new_header->used_ = orig_header->used_;
// free old memory, then rebind to new memory
DiscardData();
data_ = new_header;
assert(InvariantOk());
return ((char *)data_) + sizeof(STRING_HEADER);
}
// This is const, but is modifying a mutable field
// this way it can be used on const or non-const instances.
void STRING::FixHeader() const {
const STRING_HEADER* header = GetHeader();
if (header->used_ < 0)
header->used_ = strlen(GetCStr()) + 1;
}
STRING::STRING() {
// Empty STRINGs contain just the "\0".
memcpy(AllocData(1, kMinCapacity), "", 1);
}
STRING::STRING(const STRING& str) {
str.FixHeader();
const STRING_HEADER* str_header = str.GetHeader();
int str_used = str_header->used_;
char *this_cstr = AllocData(str_used, str_used);
memcpy(this_cstr, str.GetCStr(), str_used);
assert(InvariantOk());
}
STRING::STRING(const char* cstr) {
if (cstr == NULL) {
// Empty STRINGs contain just the "\0".
memcpy(AllocData(1, kMinCapacity), "", 1);
} else {
int len = strlen(cstr) + 1;
char* this_cstr = AllocData(len, len);
memcpy(this_cstr, cstr, len);
}
assert(InvariantOk());
}
STRING::STRING(const char *data, int length) {
if (data == NULL) {
// Empty STRINGs contain just the "\0".
memcpy(AllocData(1, kMinCapacity), "", 1);
} else {
char* this_cstr = AllocData(length + 1, length + 1);
memcpy(this_cstr, data, length);
this_cstr[length] = '\0';
}
}
STRING::~STRING() {
DiscardData();
}
// TODO(rays) Change all callers to use TFile and remove the old functions.
// Writes to the given file. Returns false in case of error.
bool STRING::Serialize(FILE* fp) const {
inT32 len = length();
if (fwrite(&len, sizeof(len), 1, fp) != 1) return false;
if (static_cast<int>(fwrite(GetCStr(), 1, len, fp)) != len) return false;
return true;
}
// Writes to the given file. Returns false in case of error.
bool STRING::Serialize(TFile* fp) const {
inT32 len = length();
if (fp->FWrite(&len, sizeof(len), 1) != 1) return false;
if (fp->FWrite(GetCStr(), 1, len) != len) return false;
return true;
}
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool STRING::DeSerialize(bool swap, FILE* fp) {
inT32 len;
if (fread(&len, sizeof(len), 1, fp) != 1) return false;
if (swap)
ReverseN(&len, sizeof(len));
truncate_at(len);
if (static_cast<int>(fread(GetCStr(), 1, len, fp)) != len) return false;
return true;
}
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool STRING::DeSerialize(bool swap, TFile* fp) {
inT32 len;
if (fp->FRead(&len, sizeof(len), 1) != 1) return false;
if (swap)
ReverseN(&len, sizeof(len));
truncate_at(len);
if (fp->FRead(GetCStr(), 1, len) != len) return false;
return true;
}
BOOL8 STRING::contains(const char c) const {
return (c != '\0') && (strchr (GetCStr(), c) != NULL);
}
inT32 STRING::length() const {
FixHeader();
return GetHeader()->used_ - 1;
}
const char* STRING::string() const {
const STRING_HEADER* header = GetHeader();
if (header->used_ == 0)
return NULL;
// mark header length unreliable because tesseract might
// cast away the const and mutate the string directly.
header->used_ = -1;
return GetCStr();
}
const char* STRING::c_str() const {
return string();
}
/******
* The STRING_IS_PROTECTED interface adds additional support to migrate
* code that needs to modify the STRING in ways not otherwise supported
* without violating encapsulation.
*
* Also makes the [] operator return a const so it is immutable
*/
#if STRING_IS_PROTECTED
const char& STRING::operator[](inT32 index) const {
return GetCStr()[index];
}
void STRING::insert_range(inT32 index, const char* str, int len) {
// if index is outside current range, then also grow size of string
// to accmodate the requested range.
STRING_HEADER* this_header = GetHeader();
int used = this_header->used_;
if (index > used)
used = index;
char* this_cstr = ensure_cstr(used + len + 1);
if (index < used) {
// move existing string from index to '\0' inclusive.
memmove(this_cstr + index + len,
this_cstr + index,
this_header->used_ - index);
} else if (len > 0) {
// We are going to overwrite previous null terminator, so write the new one.
this_cstr[this_header->used_ + len - 1] = '\0';
// If the old header did not have the terminator,
// then we need to account for it now that we've added it.
// Otherwise it was already accounted for; we just moved it.
if (this_header->used_ == 0)
++this_header->used_;
}
// Write new string to index.
// The string is already terminated from the conditions above.
memcpy(this_cstr + index, str, len);
this_header->used_ += len;
assert(InvariantOk());
}
void STRING::erase_range(inT32 index, int len) {
char* this_cstr = GetCStr();
STRING_HEADER* this_header = GetHeader();
memcpy(this_cstr+index, this_cstr+index+len,
this_header->used_ - index - len);
this_header->used_ -= len;
assert(InvariantOk());
}
#else
void STRING::truncate_at(inT32 index) {
ASSERT_HOST(index >= 0);
FixHeader();
char* this_cstr = ensure_cstr(index + 1);
this_cstr[index] = '\0';
GetHeader()->used_ = index + 1;
assert(InvariantOk());
}
char& STRING::operator[](inT32 index) const {
// Code is casting away this const and mutating the string,
// so mark used_ as -1 to flag it unreliable.
GetHeader()->used_ = -1;
return ((char *)GetCStr())[index];
}
#endif
void STRING::split(const char c, GenericVector<STRING> *splited) {
int start_index = 0;
int len = length();
for (int i = 0; i < len; i++) {
if ((*this)[i] == c) {
if (i != start_index) {
(*this)[i] = '\0';
splited->push_back(STRING(GetCStr() + start_index, i - start_index));
(*this)[i] = c;
}
start_index = i + 1;
}
}
if (len != start_index) {
splited->push_back(STRING(GetCStr() + start_index, len - start_index));
}
}
BOOL8 STRING::operator==(const STRING& str) const {
FixHeader();
str.FixHeader();
const STRING_HEADER* str_header = str.GetHeader();
const STRING_HEADER* this_header = GetHeader();
int this_used = this_header->used_;
int str_used = str_header->used_;
return (this_used == str_used)
&& (memcmp(GetCStr(), str.GetCStr(), this_used) == 0);
}
BOOL8 STRING::operator!=(const STRING& str) const {
FixHeader();
str.FixHeader();
const STRING_HEADER* str_header = str.GetHeader();
const STRING_HEADER* this_header = GetHeader();
int this_used = this_header->used_;
int str_used = str_header->used_;
return (this_used != str_used)
|| (memcmp(GetCStr(), str.GetCStr(), this_used) != 0);
}
BOOL8 STRING::operator!=(const char* cstr) const {
FixHeader();
const STRING_HEADER* this_header = GetHeader();
if (cstr == NULL)
return this_header->used_ > 1; // either '\0' or NULL
else {
inT32 length = strlen(cstr) + 1;
return (this_header->used_ != length)
|| (memcmp(GetCStr(), cstr, length) != 0);
}
}
STRING& STRING::operator=(const STRING& str) {
str.FixHeader();
const STRING_HEADER* str_header = str.GetHeader();
int str_used = str_header->used_;
GetHeader()->used_ = 0; // clear since ensure doesnt need to copy data
char* this_cstr = ensure_cstr(str_used);
STRING_HEADER* this_header = GetHeader();
memcpy(this_cstr, str.GetCStr(), str_used);
this_header->used_ = str_used;
assert(InvariantOk());
return *this;
}
STRING & STRING::operator+=(const STRING& str) {
FixHeader();
str.FixHeader();
const STRING_HEADER* str_header = str.GetHeader();
const char* str_cstr = str.GetCStr();
int str_used = str_header->used_;
int this_used = GetHeader()->used_;
char* this_cstr = ensure_cstr(this_used + str_used);
STRING_HEADER* this_header = GetHeader(); // after ensure for realloc
if (this_used > 1) {
memcpy(this_cstr + this_used - 1, str_cstr, str_used);
this_header->used_ += str_used - 1; // overwrite '\0'
} else {
memcpy(this_cstr, str_cstr, str_used);
this_header->used_ = str_used;
}
assert(InvariantOk());
return *this;
}
void STRING::add_str_int(const char* str, int number) {
if (str != NULL)
*this += str;
// Allow space for the maximum possible length of inT64.
char num_buffer[kMaxIntSize];
snprintf(num_buffer, kMaxIntSize - 1, "%d", number);
num_buffer[kMaxIntSize - 1] = '\0';
*this += num_buffer;
}
// Appends the given string and double (as a %.8g) to this.
void STRING::add_str_double(const char* str, double number) {
if (str != NULL)
*this += str;
// Allow space for the maximum possible length of %8g.
char num_buffer[kMaxDoubleSize];
snprintf(num_buffer, kMaxDoubleSize - 1, "%.8g", number);
num_buffer[kMaxDoubleSize - 1] = '\0';
*this += num_buffer;
}
STRING & STRING::operator=(const char* cstr) {
STRING_HEADER* this_header = GetHeader();
if (cstr) {
int len = strlen(cstr) + 1;
this_header->used_ = 0; // dont bother copying data if need to realloc
char* this_cstr = ensure_cstr(len);
this_header = GetHeader(); // for realloc
memcpy(this_cstr, cstr, len);
this_header->used_ = len;
} else {
// Reallocate to same state as default constructor.
DiscardData();
// Empty STRINGs contain just the "\0".
memcpy(AllocData(1, kMinCapacity), "", 1);
}
assert(InvariantOk());
return *this;
}
void STRING::assign(const char *cstr, int len) {
STRING_HEADER* this_header = GetHeader();
this_header->used_ = 0; // dont bother copying data if need to realloc
char* this_cstr = ensure_cstr(len + 1); // +1 for '\0'
this_header = GetHeader(); // for realloc
memcpy(this_cstr, cstr, len);
this_cstr[len] = '\0';
this_header->used_ = len + 1;
assert(InvariantOk());
}
STRING STRING::operator+(const STRING& str) const {
STRING result(*this);
result += str;
assert(InvariantOk());
return result;
}
STRING STRING::operator+(const char ch) const {
STRING result;
FixHeader();
const STRING_HEADER* this_header = GetHeader();
int this_used = this_header->used_;
char* result_cstr = result.ensure_cstr(this_used + 1);
STRING_HEADER* result_header = result.GetHeader();
int result_used = result_header->used_;
// copies '\0' but we'll overwrite that
memcpy(result_cstr, GetCStr(), this_used);
result_cstr[result_used] = ch; // overwrite old '\0'
result_cstr[result_used + 1] = '\0'; // append on '\0'
++result_header->used_;
assert(InvariantOk());
return result;
}
STRING& STRING::operator+=(const char *str) {
if (!str || !*str) // empty string has no effect
return *this;
FixHeader();
int len = strlen(str) + 1;
int this_used = GetHeader()->used_;
char* this_cstr = ensure_cstr(this_used + len);
STRING_HEADER* this_header = GetHeader(); // after ensure for realloc
// if we had non-empty string then append overwriting old '\0'
// otherwise replace
if (this_used > 0) {
memcpy(this_cstr + this_used - 1, str, len);
this_header->used_ += len - 1;
} else {
memcpy(this_cstr, str, len);
this_header->used_ = len;
}
assert(InvariantOk());
return *this;
}
STRING& STRING::operator+=(const char ch) {
if (ch == '\0')
return *this;
FixHeader();
int this_used = GetHeader()->used_;
char* this_cstr = ensure_cstr(this_used + 1);
STRING_HEADER* this_header = GetHeader();
if (this_used > 0)
--this_used; // undo old empty null if there was one
this_cstr[this_used++] = ch; // append ch to end
this_cstr[this_used++] = '\0'; // append '\0' after ch
this_header->used_ = this_used;
assert(InvariantOk());
return *this;
}
| C++ |
/**********************************************************************
* File: clst.c (Formerly clist.c)
* Description: CONS cell list handling code which is not in the include file.
* Author: Phil Cheatle
* Created: Mon Jan 28 08:33:13 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <stdlib.h>
#include "clst.h"
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: CLIST
* ================================
**********************************************************************/
/***********************************************************************
* CLIST::internal_deep_clear
*
* Used by the "deep_clear" member function of derived list
* classes to destroy all the elements on the list.
* The calling function passes a "zapper" function which can be called to
* delete each data element of the list, regardless of its class. This
* technique permits a generic clear function to destroy elements of
* different derived types correctly, without requiring virtual functions and
* the consequential memory overhead.
**********************************************************************/
void
CLIST::internal_deep_clear ( //destroy all links
void (*zapper) (void *)) { //ptr to zapper functn
CLIST_LINK *ptr;
CLIST_LINK *next;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST::internal_deep_clear", ABORT, NULL);
#endif
if (!empty ()) {
ptr = last->next; //set to first
last->next = NULL; //break circle
last = NULL; //set list empty
while (ptr) {
next = ptr->next;
zapper (ptr->data);
delete(ptr);
ptr = next;
}
}
}
/***********************************************************************
* CLIST::shallow_clear
*
* Used by the destructor and the "shallow_clear" member function of derived
* list classes to destroy the list.
* The data elements are NOT destroyed.
*
**********************************************************************/
void CLIST::shallow_clear() { //destroy all links
CLIST_LINK *ptr;
CLIST_LINK *next;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST::shallow_clear", ABORT, NULL);
#endif
if (!empty ()) {
ptr = last->next; //set to first
last->next = NULL; //break circle
last = NULL; //set list empty
while (ptr) {
next = ptr->next;
delete(ptr);
ptr = next;
}
}
}
/***********************************************************************
* CLIST::assign_to_sublist
*
* The list is set to a sublist of another list. "This" list must be empty
* before this function is invoked. The two iterators passed must refer to
* the same list, different from "this" one. The sublist removed is the
* inclusive list from start_it's current position to end_it's current
* position. If this range passes over the end of the source list then the
* source list has its end set to the previous element of start_it. The
* extracted sublist is unaffected by the end point of the source list, its
* end point is always the end_it position.
**********************************************************************/
void CLIST::assign_to_sublist( //to this list
CLIST_ITERATOR *start_it, //from list start
CLIST_ITERATOR *end_it) { //from list end
const ERRCODE LIST_NOT_EMPTY =
"Destination list must be empty before extracting a sublist";
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST::assign_to_sublist", ABORT, NULL);
#endif
if (!empty ())
LIST_NOT_EMPTY.error ("CLIST.assign_to_sublist", ABORT, NULL);
last = start_it->extract_sublist (end_it);
}
/***********************************************************************
* CLIST::length
*
* Return count of elements on list
**********************************************************************/
inT32 CLIST::length() const { //count elements
CLIST_ITERATOR it(const_cast<CLIST*>(this));
inT32 count = 0;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST::length", ABORT, NULL);
#endif
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward())
count++;
return count;
}
/***********************************************************************
* CLIST::sort
*
* Sort elements on list
**********************************************************************/
void
CLIST::sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *)) {
CLIST_ITERATOR it(this);
inT32 count;
void **base; //ptr array to sort
void **current;
inT32 i;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST::sort", ABORT, NULL);
#endif
/* Allocate an array of pointers, one per list element */
count = length ();
base = (void **) malloc (count * sizeof (void *));
/* Extract all elements, putting the pointers in the array */
current = base;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
*current = it.extract ();
current++;
}
/* Sort the pointer array */
qsort ((char *) base, count, sizeof (*base), comparator);
/* Rebuild the list from the sorted pointers */
current = base;
for (i = 0; i < count; i++) {
it.add_to_end (*current);
current++;
}
free(base);
}
// Assuming list has been sorted already, insert new_data to
// keep the list sorted according to the same comparison function.
// Comparision function is the same as used by sort, i.e. uses double
// indirection. Time is O(1) to add to beginning or end.
// Time is linear to add pre-sorted items to an empty list.
// If unique, then don't add duplicate entries.
// Returns true if the element was added to the list.
bool CLIST::add_sorted(int comparator(const void*, const void*),
bool unique, void* new_data) {
// Check for adding at the end.
if (last == NULL || comparator(&last->data, &new_data) < 0) {
CLIST_LINK* new_element = new CLIST_LINK;
new_element->data = new_data;
if (last == NULL) {
new_element->next = new_element;
} else {
new_element->next = last->next;
last->next = new_element;
}
last = new_element;
return true;
} else if (!unique || last->data != new_data) {
// Need to use an iterator.
CLIST_ITERATOR it(this);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
void* data = it.data();
if (data == new_data && unique)
return false;
if (comparator(&data, &new_data) > 0)
break;
}
if (it.cycled_list())
it.add_to_end(new_data);
else
it.add_before_then_move(new_data);
return true;
}
return false;
}
// Assuming that the minuend and subtrahend are already sorted with
// the same comparison function, shallow clears this and then copies
// the set difference minuend - subtrahend to this, being the elements
// of minuend that do not compare equal to anything in subtrahend.
// If unique is true, any duplicates in minuend are also eliminated.
void CLIST::set_subtract(int comparator(const void*, const void*),
bool unique,
CLIST* minuend, CLIST* subtrahend) {
shallow_clear();
CLIST_ITERATOR m_it(minuend);
CLIST_ITERATOR s_it(subtrahend);
// Since both lists are sorted, finding the subtras that are not
// minus is a case of a parallel iteration.
for (m_it.mark_cycle_pt(); !m_it.cycled_list(); m_it.forward()) {
void* minu = m_it.data();
void* subtra = NULL;
if (!s_it.empty()) {
subtra = s_it.data();
while (!s_it.at_last() &&
comparator(&subtra, &minu) < 0) {
s_it.forward();
subtra = s_it.data();
}
}
if (subtra == NULL || comparator(&subtra, &minu) != 0)
add_sorted(comparator, unique, minu);
}
}
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: CLIST_ITERATOR
* =========================================
**********************************************************************/
/***********************************************************************
* CLIST_ITERATOR::forward
*
* Move the iterator to the next element of the list.
* REMEMBER: ALL LISTS ARE CIRCULAR.
**********************************************************************/
void *CLIST_ITERATOR::forward() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST_ITERATOR::forward", ABORT, NULL);
if (!list)
NO_LIST.error ("CLIST_ITERATOR::forward", ABORT, NULL);
#endif
if (list->empty ())
return NULL;
if (current) { //not removed so
//set previous
prev = current;
started_cycling = TRUE;
// In case next is deleted by another iterator, get next from current.
current = current->next;
} else {
if (ex_current_was_cycle_pt)
cycle_pt = next;
current = next;
}
next = current->next;
#ifndef NDEBUG
if (!current)
NULL_DATA.error ("CLIST_ITERATOR::forward", ABORT, NULL);
if (!next)
NULL_NEXT.error ("CLIST_ITERATOR::forward", ABORT,
"This is: %p Current is: %p", this, current);
#endif
return current->data;
}
/***********************************************************************
* CLIST_ITERATOR::data_relative
*
* Return the data pointer to the element "offset" elements from current.
* "offset" must not be less than -1.
* (This function can't be INLINEd because it contains a loop)
**********************************************************************/
void *CLIST_ITERATOR::data_relative( //get data + or - ...
inT8 offset) { //offset from current
CLIST_LINK *ptr;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST_ITERATOR::data_relative", ABORT, NULL);
if (!list)
NO_LIST.error ("CLIST_ITERATOR::data_relative", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("CLIST_ITERATOR::data_relative", ABORT, NULL);
if (offset < -1)
BAD_PARAMETER.error ("CLIST_ITERATOR::data_relative", ABORT,
"offset < -l");
#endif
if (offset == -1)
ptr = prev;
else
for (ptr = current ? current : prev; offset-- > 0; ptr = ptr->next);
#ifndef NDEBUG
if (!ptr)
NULL_DATA.error ("CLIST_ITERATOR::data_relative", ABORT, NULL);
#endif
return ptr->data;
}
/***********************************************************************
* CLIST_ITERATOR::move_to_last()
*
* Move current so that it is set to the end of the list.
* Return data just in case anyone wants it.
* (This function can't be INLINEd because it contains a loop)
**********************************************************************/
void *CLIST_ITERATOR::move_to_last() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST_ITERATOR::move_to_last", ABORT, NULL);
if (!list)
NO_LIST.error ("CLIST_ITERATOR::move_to_last", ABORT, NULL);
#endif
while (current != list->last)
forward();
if (current == NULL)
return NULL;
else
return current->data;
}
/***********************************************************************
* CLIST_ITERATOR::exchange()
*
* Given another iterator, whose current element is a different element on
* the same list list OR an element of another list, exchange the two current
* elements. On return, each iterator points to the element which was the
* other iterators current on entry.
* (This function hasn't been in-lined because its a bit big!)
**********************************************************************/
void CLIST_ITERATOR::exchange( //positions of 2 links
CLIST_ITERATOR *other_it) { //other iterator
const ERRCODE DONT_EXCHANGE_DELETED =
"Can't exchange deleted elements of lists";
CLIST_LINK *old_current;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("CLIST_ITERATOR::exchange", ABORT, NULL);
if (!list)
NO_LIST.error ("CLIST_ITERATOR::exchange", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("CLIST_ITERATOR::exchange", ABORT, "other_it NULL");
if (!(other_it->list))
NO_LIST.error ("CLIST_ITERATOR::exchange", ABORT, "other_it");
#endif
/* Do nothing if either list is empty or if both iterators reference the same
link */
if ((list->empty ()) ||
(other_it->list->empty ()) || (current == other_it->current))
return;
/* Error if either current element is deleted */
if (!current || !other_it->current)
DONT_EXCHANGE_DELETED.error ("CLIST_ITERATOR.exchange", ABORT, NULL);
/* Now handle the 4 cases: doubleton list; non-doubleton adjacent elements
(other before this); non-doubleton adjacent elements (this before other);
non-adjacent elements. */
//adjacent links
if ((next == other_it->current) ||
(other_it->next == current)) {
//doubleton list
if ((next == other_it->current) &&
(other_it->next == current)) {
prev = next = current;
other_it->prev = other_it->next = other_it->current;
}
else { //non-doubleton with
//adjacent links
//other before this
if (other_it->next == current) {
other_it->prev->next = current;
other_it->current->next = next;
current->next = other_it->current;
other_it->next = other_it->current;
prev = current;
}
else { //this before other
prev->next = other_it->current;
current->next = other_it->next;
other_it->current->next = current;
next = current;
other_it->prev = other_it->current;
}
}
}
else { //no overlap
prev->next = other_it->current;
current->next = other_it->next;
other_it->prev->next = current;
other_it->current->next = next;
}
/* update end of list pointer when necessary (remember that the 2 iterators
may iterate over different lists!) */
if (list->last == current)
list->last = other_it->current;
if (other_it->list->last == other_it->current)
other_it->list->last = current;
if (current == cycle_pt)
cycle_pt = other_it->cycle_pt;
if (other_it->current == other_it->cycle_pt)
other_it->cycle_pt = cycle_pt;
/* The actual exchange - in all cases*/
old_current = current;
current = other_it->current;
other_it->current = old_current;
}
/***********************************************************************
* CLIST_ITERATOR::extract_sublist()
*
* This is a private member, used only by CLIST::assign_to_sublist.
* Given another iterator for the same list, extract the links from THIS to
* OTHER inclusive, link them into a new circular list, and return a
* pointer to the last element.
* (Can't inline this function because it contains a loop)
**********************************************************************/
CLIST_LINK *CLIST_ITERATOR::extract_sublist( //from this current
CLIST_ITERATOR *other_it) { //to other current
CLIST_ITERATOR temp_it = *this;
CLIST_LINK *end_of_new_list;
const ERRCODE BAD_SUBLIST = "Can't find sublist end point in original list";
#ifndef NDEBUG
const ERRCODE BAD_EXTRACTION_PTS =
"Can't extract sublist from points on different lists";
const ERRCODE DONT_EXTRACT_DELETED =
"Can't extract a sublist marked by deleted points";
if (!this)
NULL_OBJECT.error ("CLIST_ITERATOR::extract_sublist", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("CLIST_ITERATOR::extract_sublist", ABORT,
"other_it NULL");
if (!list)
NO_LIST.error ("CLIST_ITERATOR::extract_sublist", ABORT, NULL);
if (list != other_it->list)
BAD_EXTRACTION_PTS.error ("CLIST_ITERATOR.extract_sublist", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("CLIST_ITERATOR::extract_sublist", ABORT, NULL);
if (!current || !other_it->current)
DONT_EXTRACT_DELETED.error ("CLIST_ITERATOR.extract_sublist", ABORT,
NULL);
#endif
ex_current_was_last = other_it->ex_current_was_last = FALSE;
ex_current_was_cycle_pt = FALSE;
other_it->ex_current_was_cycle_pt = FALSE;
temp_it.mark_cycle_pt ();
do { //walk sublist
if (temp_it.cycled_list ()) //cant find end pt
BAD_SUBLIST.error ("CLIST_ITERATOR.extract_sublist", ABORT, NULL);
if (temp_it.at_last ()) {
list->last = prev;
ex_current_was_last = other_it->ex_current_was_last = TRUE;
}
if (temp_it.current == cycle_pt)
ex_current_was_cycle_pt = TRUE;
if (temp_it.current == other_it->cycle_pt)
other_it->ex_current_was_cycle_pt = TRUE;
temp_it.forward ();
}
while (temp_it.prev != other_it->current);
//circularise sublist
other_it->current->next = current;
end_of_new_list = other_it->current;
//sublist = whole list
if (prev == other_it->current) {
list->last = NULL;
prev = current = next = NULL;
other_it->prev = other_it->current = other_it->next = NULL;
}
else {
prev->next = other_it->next;
current = other_it->current = NULL;
next = other_it->next;
other_it->prev = prev;
}
return end_of_new_list;
}
| C++ |
///////////////////////////////////////////////////////////////////////
// File: genericvector.h
// Description: Generic vector class
// Author: Daria Antonova
// Created: Mon Jun 23 11:26:43 PDT 2008
//
// (C) Copyright 2007, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
//
#ifndef TESSERACT_CCUTIL_GENERICVECTOR_H_
#define TESSERACT_CCUTIL_GENERICVECTOR_H_
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "tesscallback.h"
#include "errcode.h"
#include "helpers.h"
#include "ndminx.h"
#include "serialis.h"
#include "strngs.h"
// Use PointerVector<T> below in preference to GenericVector<T*>, as that
// provides automatic deletion of pointers, [De]Serialize that works, and
// sort that works.
template <typename T>
class GenericVector {
public:
GenericVector() {
init(kDefaultVectorSize);
}
GenericVector(int size, T init_val) {
init(size);
init_to_size(size, init_val);
}
// Copy
GenericVector(const GenericVector& other) {
this->init(other.size());
this->operator+=(other);
}
GenericVector<T> &operator+=(const GenericVector& other);
GenericVector<T> &operator=(const GenericVector& other);
~GenericVector();
// Reserve some memory.
void reserve(int size);
// Double the size of the internal array.
void double_the_size();
// Resizes to size and sets all values to t.
void init_to_size(int size, T t);
// Resizes to size without any initialization.
void resize_no_init(int size) {
reserve(size);
size_used_ = size;
}
// Return the size used.
int size() const {
return size_used_;
}
int size_reserved() const {
return size_reserved_;
}
int length() const {
return size_used_;
}
// Return true if empty.
bool empty() const {
return size_used_ == 0;
}
// Return the object from an index.
T &get(int index) const;
T &back() const;
T &operator[](int index) const;
// Returns the last object and removes it.
T pop_back();
// Return the index of the T object.
// This method NEEDS a compare_callback to be passed to
// set_compare_callback.
int get_index(T object) const;
// Return true if T is in the array
bool contains(T object) const;
// Return true if the index is valid
T contains_index(int index) const;
// Push an element in the end of the array
int push_back(T object);
void operator+=(T t);
// Push an element in the end of the array if the same
// element is not already contained in the array.
int push_back_new(T object);
// Push an element in the front of the array
// Note: This function is O(n)
int push_front(T object);
// Set the value at the given index
void set(T t, int index);
// Insert t at the given index, push other elements to the right.
void insert(T t, int index);
// Removes an element at the given index and
// shifts the remaining elements to the left.
void remove(int index);
// Truncates the array to the given size by removing the end.
// If the current size is less, the array is not expanded.
void truncate(int size) {
if (size < size_used_)
size_used_ = size;
}
// Add a callback to be called to delete the elements when the array took
// their ownership.
void set_clear_callback(TessCallback1<T>* cb);
// Add a callback to be called to compare the elements when needed (contains,
// get_id, ...)
void set_compare_callback(TessResultCallback2<bool, T const &, T const &>* cb);
// Clear the array, calling the clear callback function if any.
// All the owned callbacks are also deleted.
// If you don't want the callbacks to be deleted, before calling clear, set
// the callback to NULL.
void clear();
// Delete objects pointed to by data_[i]
void delete_data_pointers();
// This method clears the current object, then, does a shallow copy of
// its argument, and finally invalidates its argument.
// Callbacks are moved to the current object;
void move(GenericVector<T>* from);
// Read/Write the array to a file. This does _NOT_ read/write the callbacks.
// The callback given must be permanent since they will be called more than
// once. The given callback will be deleted at the end.
// If the callbacks are NULL, then the data is simply read/written using
// fread (and swapping)/fwrite.
// Returns false on error or if the callback returns false.
// DEPRECATED. Use [De]Serialize[Classes] instead.
bool write(FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const;
bool read(FILE* f, TessResultCallback3<bool, FILE*, T*, bool>* cb, bool swap);
// Writes a vector of simple types to the given file. Assumes that bitwise
// read/write of T will work. Returns false in case of error.
// TODO(rays) Change all callers to use TFile and remove deprecated methods.
bool Serialize(FILE* fp) const;
bool Serialize(tesseract::TFile* fp) const;
// Reads a vector of simple types from the given file. Assumes that bitwise
// read/write will work with ReverseN according to sizeof(T).
// Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
bool DeSerialize(bool swap, tesseract::TFile* fp);
// Writes a vector of classes to the given file. Assumes the existence of
// bool T::Serialize(FILE* fp) const that returns false in case of error.
// Returns false in case of error.
bool SerializeClasses(FILE* fp) const;
bool SerializeClasses(tesseract::TFile* fp) const;
// Reads a vector of classes from the given file. Assumes the existence of
// bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
// error. Also needs T::T() and T::T(constT&), as init_to_size is used in
// this function. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerializeClasses(bool swap, FILE* fp);
bool DeSerializeClasses(bool swap, tesseract::TFile* fp);
// Allocates a new array of double the current_size, copies over the
// information from data to the new location, deletes data and returns
// the pointed to the new larger array.
// This function uses memcpy to copy the data, instead of invoking
// operator=() for each element like double_the_size() does.
static T *double_the_size_memcpy(int current_size, T *data) {
T *data_new = new T[current_size * 2];
memcpy(data_new, data, sizeof(T) * current_size);
delete[] data;
return data_new;
}
// Reverses the elements of the vector.
void reverse() {
for (int i = 0; i < size_used_ / 2; ++i)
Swap(&data_[i], &data_[size_used_ - 1 - i]);
}
// Sorts the members of this vector using the less than comparator (cmp_lt),
// which compares the values. Useful for GenericVectors to primitive types.
// Will not work so great for pointers (unless you just want to sort some
// pointers). You need to provide a specialization to sort_cmp to use
// your type.
void sort();
// Sort the array into the order defined by the qsort function comparator.
// The comparator function is as defined by qsort, ie. it receives pointers
// to two Ts and returns negative if the first element is to appear earlier
// in the result and positive if it is to appear later, with 0 for equal.
void sort(int (*comparator)(const void*, const void*)) {
qsort(data_, size_used_, sizeof(*data_), comparator);
}
// Searches the array (assuming sorted in ascending order, using sort()) for
// an element equal to target and returns true if it is present.
// Use binary_search to get the index of target, or its nearest candidate.
bool bool_binary_search(const T& target) const {
int index = binary_search(target);
if (index >= size_used_)
return false;
return data_[index] == target;
}
// Searches the array (assuming sorted in ascending order, using sort()) for
// an element equal to target and returns the index of the best candidate.
// The return value is conceptually the largest index i such that
// data_[i] <= target or 0 if target < the whole vector.
// NOTE that this function uses operator> so really the return value is
// the largest index i such that data_[i] > target is false.
int binary_search(const T& target) const {
int bottom = 0;
int top = size_used_;
do {
int middle = (bottom + top) / 2;
if (data_[middle] > target)
top = middle;
else
bottom = middle;
}
while (top - bottom > 1);
return bottom;
}
// Compact the vector by deleting elements using operator!= on basic types.
// The vector must be sorted.
void compact_sorted() {
if (size_used_ == 0)
return;
// First element is in no matter what, hence the i = 1.
int last_write = 0;
for (int i = 1; i < size_used_; ++i) {
// Finds next unique item and writes it.
if (data_[last_write] != data_[i])
data_[++last_write] = data_[i];
}
// last_write is the index of a valid data cell, so add 1.
size_used_ = last_write + 1;
}
// Compact the vector by deleting elements for which delete_cb returns
// true. delete_cb is a permanent callback and will be deleted.
void compact(TessResultCallback1<bool, int>* delete_cb) {
int new_size = 0;
int old_index = 0;
// Until the callback returns true, the elements stay the same.
while (old_index < size_used_ && !delete_cb->Run(old_index++))
++new_size;
// Now just copy anything else that gets false from delete_cb.
for (; old_index < size_used_; ++old_index) {
if (!delete_cb->Run(old_index)) {
data_[new_size++] = data_[old_index];
}
}
size_used_ = new_size;
delete delete_cb;
}
T dot_product(const GenericVector<T>& other) const {
T result = static_cast<T>(0);
for (int i = MIN(size_used_, other.size_used_) - 1; i >= 0; --i)
result += data_[i] * other.data_[i];
return result;
}
// Returns the index of what would be the target_index_th item in the array
// if the members were sorted, without actually sorting. Members are
// shuffled around, but it takes O(n) time.
// NOTE: uses operator< and operator== on the members.
int choose_nth_item(int target_index) {
// Make sure target_index is legal.
if (target_index < 0)
target_index = 0; // ensure legal
else if (target_index >= size_used_)
target_index = size_used_ - 1;
unsigned int seed = 1;
return choose_nth_item(target_index, 0, size_used_, &seed);
}
// Swaps the elements with the given indices.
void swap(int index1, int index2) {
if (index1 != index2) {
T tmp = data_[index1];
data_[index1] = data_[index2];
data_[index2] = tmp;
}
}
// Returns true if all elements of *this are within the given range.
// Only uses operator<
bool WithinBounds(const T& rangemin, const T& rangemax) const {
for (int i = 0; i < size_used_; ++i) {
if (data_[i] < rangemin || rangemax < data_[i])
return false;
}
return true;
}
protected:
// Internal recursive version of choose_nth_item.
int choose_nth_item(int target_index, int start, int end, unsigned int* seed);
// Init the object, allocating size memory.
void init(int size);
// We are assuming that the object generally placed in thie
// vector are small enough that for efficiency it makes sence
// to start with a larger initial size.
static const int kDefaultVectorSize = 4;
inT32 size_used_;
inT32 size_reserved_;
T* data_;
TessCallback1<T>* clear_cb_;
// Mutable because Run method is not const
mutable TessResultCallback2<bool, T const &, T const &>* compare_cb_;
};
namespace tesseract {
// Function to read a GenericVector<char> from a whole file.
// Returns false on failure.
typedef bool (*FileReader)(const STRING& filename, GenericVector<char>* data);
// Function to write a GenericVector<char> to a whole file.
// Returns false on failure.
typedef bool (*FileWriter)(const GenericVector<char>& data,
const STRING& filename);
// The default FileReader loads the whole file into the vector of char,
// returning false on error.
inline bool LoadDataFromFile(const STRING& filename,
GenericVector<char>* data) {
FILE* fp = fopen(filename.string(), "rb");
if (fp == NULL) return false;
fseek(fp, 0, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET);
// Pad with a 0, just in case we treat the result as a string.
data->init_to_size(size + 1, 0);
bool result = fread(&(*data)[0], 1, size, fp) == size;
fclose(fp);
return result;
}
// The default FileWriter writes the vector of char to the filename file,
// returning false on error.
inline bool SaveDataToFile(const GenericVector<char>& data,
const STRING& filename) {
FILE* fp = fopen(filename.string(), "wb");
if (fp == NULL) return false;
bool result =
static_cast<int>(fwrite(&data[0], 1, data.size(), fp)) == data.size();
fclose(fp);
return result;
}
template <typename T>
bool cmp_eq(T const & t1, T const & t2) {
return t1 == t2;
}
// Used by sort()
// return < 0 if t1 < t2
// return 0 if t1 == t2
// return > 0 if t1 > t2
template <typename T>
int sort_cmp(const void* t1, const void* t2) {
const T* a = static_cast<const T *> (t1);
const T* b = static_cast<const T *> (t2);
if (*a < *b) {
return -1;
} else if (*b < *a) {
return 1;
} else {
return 0;
}
}
// Used by PointerVector::sort()
// return < 0 if t1 < t2
// return 0 if t1 == t2
// return > 0 if t1 > t2
template <typename T>
int sort_ptr_cmp(const void* t1, const void* t2) {
const T* a = *reinterpret_cast<T * const *>(t1);
const T* b = *reinterpret_cast<T * const *>(t2);
if (*a < *b) {
return -1;
} else if (*b < *a) {
return 1;
} else {
return 0;
}
}
// Subclass for a vector of pointers. Use in preference to GenericVector<T*>
// as it provides automatic deletion and correct serialization, with the
// corollary that all copy operations are deep copies of the pointed-to objects.
template<typename T>
class PointerVector : public GenericVector<T*> {
public:
PointerVector() : GenericVector<T*>() { }
explicit PointerVector(int size) : GenericVector<T*>(size) { }
~PointerVector() {
// Clear must be called here, even though it is called again by the base,
// as the base will call the wrong clear.
clear();
}
// Copy must be deep, as the pointers will be automatically deleted on
// destruction.
PointerVector(const PointerVector& other) {
this->init(other.size());
this->operator+=(other);
}
PointerVector<T>& operator+=(const PointerVector& other) {
this->reserve(this->size_used_ + other.size_used_);
for (int i = 0; i < other.size(); ++i) {
this->push_back(new T(*other.data_[i]));
}
return *this;
}
PointerVector<T>& operator=(const PointerVector& other) {
this->truncate(0);
this->operator+=(other);
return *this;
}
// Removes an element at the given index and
// shifts the remaining elements to the left.
void remove(int index) {
delete GenericVector<T*>::data_[index];
GenericVector<T*>::remove(index);
}
// Truncates the array to the given size by removing the end.
// If the current size is less, the array is not expanded.
void truncate(int size) {
for (int i = size; i < GenericVector<T*>::size_used_; ++i)
delete GenericVector<T*>::data_[i];
GenericVector<T*>::truncate(size);
}
// Compact the vector by deleting elements for which delete_cb returns
// true. delete_cb is a permanent callback and will be deleted.
void compact(TessResultCallback1<bool, const T*>* delete_cb) {
int new_size = 0;
int old_index = 0;
// Until the callback returns true, the elements stay the same.
while (old_index < GenericVector<T*>::size_used_ &&
!delete_cb->Run(GenericVector<T*>::data_[old_index++]))
++new_size;
// Now just copy anything else that gets false from delete_cb.
for (; old_index < GenericVector<T*>::size_used_; ++old_index) {
if (!delete_cb->Run(GenericVector<T*>::data_[old_index])) {
GenericVector<T*>::data_[new_size++] =
GenericVector<T*>::data_[old_index];
} else {
delete GenericVector<T*>::data_[old_index];
}
}
GenericVector<T*>::size_used_ = new_size;
delete delete_cb;
}
// Clear the array, calling the clear callback function if any.
// All the owned callbacks are also deleted.
// If you don't want the callbacks to be deleted, before calling clear, set
// the callback to NULL.
void clear() {
GenericVector<T*>::delete_data_pointers();
GenericVector<T*>::clear();
}
// Writes a vector of (pointers to) classes to the given file. Assumes the
// existence of bool T::Serialize(FILE*) const that returns false in case of
// error. There is no Serialize for simple types, as you would have a
// normal GenericVector of those.
// Returns false in case of error.
bool Serialize(FILE* fp) const {
inT32 used = GenericVector<T*>::size_used_;
if (fwrite(&used, sizeof(used), 1, fp) != 1) return false;
for (int i = 0; i < used; ++i) {
inT8 non_null = GenericVector<T*>::data_[i] != NULL;
if (fwrite(&non_null, sizeof(non_null), 1, fp) != 1) return false;
if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
}
return true;
}
bool Serialize(TFile* fp) const {
inT32 used = GenericVector<T*>::size_used_;
if (fp->FWrite(&used, sizeof(used), 1) != 1) return false;
for (int i = 0; i < used; ++i) {
inT8 non_null = GenericVector<T*>::data_[i] != NULL;
if (fp->FWrite(&non_null, sizeof(non_null), 1) != 1) return false;
if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
}
return true;
}
// Reads a vector of (pointers to) classes to the given file. Assumes the
// existence of bool T::DeSerialize(bool, Tfile*) const that returns false in
// case of error. There is no Serialize for simple types, as you would have a
// normal GenericVector of those.
// If swap is true, assumes a big/little-endian swap is needed.
// Also needs T::T(), as new T is used in this function.
// Returns false in case of error.
bool DeSerialize(bool swap, FILE* fp) {
inT32 reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
GenericVector<T*>::reserve(reserved);
truncate(0);
for (int i = 0; i < reserved; ++i) {
inT8 non_null;
if (fread(&non_null, sizeof(non_null), 1, fp) != 1) return false;
T* item = NULL;
if (non_null) {
item = new T;
if (!item->DeSerialize(swap, fp)) {
delete item;
return false;
}
this->push_back(item);
} else {
// Null elements should keep their place in the vector.
this->push_back(NULL);
}
}
return true;
}
bool DeSerialize(bool swap, TFile* fp) {
inT32 reserved;
if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
if (swap) Reverse32(&reserved);
GenericVector<T*>::reserve(reserved);
truncate(0);
for (int i = 0; i < reserved; ++i) {
inT8 non_null;
if (fp->FRead(&non_null, sizeof(non_null), 1) != 1) return false;
T* item = NULL;
if (non_null) {
item = new T;
if (!item->DeSerialize(swap, fp)) {
delete item;
return false;
}
this->push_back(item);
} else {
// Null elements should keep their place in the vector.
this->push_back(NULL);
}
}
return true;
}
// Sorts the items pointed to by the members of this vector using
// t::operator<().
void sort() {
sort(&sort_ptr_cmp<T>);
}
};
} // namespace tesseract
// A useful vector that uses operator== to do comparisons.
template <typename T>
class GenericVectorEqEq : public GenericVector<T> {
public:
GenericVectorEqEq() {
GenericVector<T>::set_compare_callback(
NewPermanentTessCallback(tesseract::cmp_eq<T>));
}
GenericVectorEqEq(int size) : GenericVector<T>(size) {
GenericVector<T>::set_compare_callback(
NewPermanentTessCallback(tesseract::cmp_eq<T>));
}
};
template <typename T>
void GenericVector<T>::init(int size) {
size_used_ = 0;
size_reserved_ = 0;
data_ = 0;
clear_cb_ = 0;
compare_cb_ = 0;
reserve(size);
}
template <typename T>
GenericVector<T>::~GenericVector() {
clear();
}
// Reserve some memory. If the internal array contains elements, they are
// copied.
template <typename T>
void GenericVector<T>::reserve(int size) {
if (size_reserved_ >= size || size <= 0)
return;
T* new_array = new T[size];
for (int i = 0; i < size_used_; ++i)
new_array[i] = data_[i];
if (data_ != NULL) delete[] data_;
data_ = new_array;
size_reserved_ = size;
}
template <typename T>
void GenericVector<T>::double_the_size() {
if (size_reserved_ == 0) {
reserve(kDefaultVectorSize);
}
else {
reserve(2 * size_reserved_);
}
}
// Resizes to size and sets all values to t.
template <typename T>
void GenericVector<T>::init_to_size(int size, T t) {
reserve(size);
size_used_ = size;
for (int i = 0; i < size; ++i)
data_[i] = t;
}
// Return the object from an index.
template <typename T>
T &GenericVector<T>::get(int index) const {
ASSERT_HOST(index >= 0 && index < size_used_);
return data_[index];
}
template <typename T>
T &GenericVector<T>::operator[](int index) const {
assert(index >= 0 && index < size_used_);
return data_[index];
}
template <typename T>
T &GenericVector<T>::back() const {
ASSERT_HOST(size_used_ > 0);
return data_[size_used_ - 1];
}
// Returns the last object and removes it.
template <typename T>
T GenericVector<T>::pop_back() {
ASSERT_HOST(size_used_ > 0);
return data_[--size_used_];
}
// Return the object from an index.
template <typename T>
void GenericVector<T>::set(T t, int index) {
ASSERT_HOST(index >= 0 && index < size_used_);
data_[index] = t;
}
// Shifts the rest of the elements to the right to make
// space for the new elements and inserts the given element
// at the specified index.
template <typename T>
void GenericVector<T>::insert(T t, int index) {
ASSERT_HOST(index >= 0 && index <= size_used_);
if (size_reserved_ == size_used_)
double_the_size();
for (int i = size_used_; i > index; --i) {
data_[i] = data_[i-1];
}
data_[index] = t;
size_used_++;
}
// Removes an element at the given index and
// shifts the remaining elements to the left.
template <typename T>
void GenericVector<T>::remove(int index) {
ASSERT_HOST(index >= 0 && index < size_used_);
for (int i = index; i < size_used_ - 1; ++i) {
data_[i] = data_[i+1];
}
size_used_--;
}
// Return true if the index is valindex
template <typename T>
T GenericVector<T>::contains_index(int index) const {
return index >= 0 && index < size_used_;
}
// Return the index of the T object.
template <typename T>
int GenericVector<T>::get_index(T object) const {
for (int i = 0; i < size_used_; ++i) {
ASSERT_HOST(compare_cb_ != NULL);
if (compare_cb_->Run(object, data_[i]))
return i;
}
return -1;
}
// Return true if T is in the array
template <typename T>
bool GenericVector<T>::contains(T object) const {
return get_index(object) != -1;
}
// Add an element in the array
template <typename T>
int GenericVector<T>::push_back(T object) {
int index = 0;
if (size_used_ == size_reserved_)
double_the_size();
index = size_used_++;
data_[index] = object;
return index;
}
template <typename T>
int GenericVector<T>::push_back_new(T object) {
int index = get_index(object);
if (index >= 0)
return index;
return push_back(object);
}
// Add an element in the array (front)
template <typename T>
int GenericVector<T>::push_front(T object) {
if (size_used_ == size_reserved_)
double_the_size();
for (int i = size_used_; i > 0; --i)
data_[i] = data_[i-1];
data_[0] = object;
++size_used_;
return 0;
}
template <typename T>
void GenericVector<T>::operator+=(T t) {
push_back(t);
}
template <typename T>
GenericVector<T> &GenericVector<T>::operator+=(const GenericVector& other) {
this->reserve(size_used_ + other.size_used_);
for (int i = 0; i < other.size(); ++i) {
this->operator+=(other.data_[i]);
}
return *this;
}
template <typename T>
GenericVector<T> &GenericVector<T>::operator=(const GenericVector& other) {
this->truncate(0);
this->operator+=(other);
return *this;
}
// Add a callback to be called to delete the elements when the array took
// their ownership.
template <typename T>
void GenericVector<T>::set_clear_callback(TessCallback1<T>* cb) {
clear_cb_ = cb;
}
// Add a callback to be called to delete the elements when the array took
// their ownership.
template <typename T>
void GenericVector<T>::set_compare_callback(
TessResultCallback2<bool, T const &, T const &>* cb) {
compare_cb_ = cb;
}
// Clear the array, calling the callback function if any.
template <typename T>
void GenericVector<T>::clear() {
if (size_reserved_ > 0) {
if (clear_cb_ != NULL)
for (int i = 0; i < size_used_; ++i)
clear_cb_->Run(data_[i]);
delete[] data_;
data_ = NULL;
size_used_ = 0;
size_reserved_ = 0;
}
if (clear_cb_ != NULL) {
delete clear_cb_;
clear_cb_ = NULL;
}
if (compare_cb_ != NULL) {
delete compare_cb_;
compare_cb_ = NULL;
}
}
template <typename T>
void GenericVector<T>::delete_data_pointers() {
for (int i = 0; i < size_used_; ++i)
if (data_[i]) {
delete data_[i];
}
}
template <typename T>
bool GenericVector<T>::write(
FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const {
if (fwrite(&size_reserved_, sizeof(size_reserved_), 1, f) != 1) return false;
if (fwrite(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
if (cb != NULL) {
for (int i = 0; i < size_used_; ++i) {
if (!cb->Run(f, data_[i])) {
delete cb;
return false;
}
}
delete cb;
} else {
if (fwrite(data_, sizeof(T), size_used_, f) != size_used_) return false;
}
return true;
}
template <typename T>
bool GenericVector<T>::read(FILE* f,
TessResultCallback3<bool, FILE*, T*, bool>* cb,
bool swap) {
inT32 reserved;
if (fread(&reserved, sizeof(reserved), 1, f) != 1) return false;
if (swap) Reverse32(&reserved);
reserve(reserved);
if (fread(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
if (swap) Reverse32(&size_used_);
if (cb != NULL) {
for (int i = 0; i < size_used_; ++i) {
if (!cb->Run(f, data_ + i, swap)) {
delete cb;
return false;
}
}
delete cb;
} else {
if (fread(data_, sizeof(T), size_used_, f) != size_used_) return false;
if (swap) {
for (int i = 0; i < size_used_; ++i)
ReverseN(&data_[i], sizeof(T));
}
}
return true;
}
// Writes a vector of simple types to the given file. Assumes that bitwise
// read/write of T will work. Returns false in case of error.
template <typename T>
bool GenericVector<T>::Serialize(FILE* fp) const {
if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false;
if (fwrite(data_, sizeof(*data_), size_used_, fp) != size_used_) return false;
return true;
}
template <typename T>
bool GenericVector<T>::Serialize(tesseract::TFile* fp) const {
if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
if (fp->FWrite(data_, sizeof(*data_), size_used_) != size_used_) return false;
return true;
}
// Reads a vector of simple types from the given file. Assumes that bitwise
// read/write will work with ReverseN according to sizeof(T).
// Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
template <typename T>
bool GenericVector<T>::DeSerialize(bool swap, FILE* fp) {
inT32 reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
reserve(reserved);
size_used_ = reserved;
if (fread(data_, sizeof(T), size_used_, fp) != size_used_) return false;
if (swap) {
for (int i = 0; i < size_used_; ++i)
ReverseN(&data_[i], sizeof(data_[i]));
}
return true;
}
template <typename T>
bool GenericVector<T>::DeSerialize(bool swap, tesseract::TFile* fp) {
inT32 reserved;
if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
if (swap) Reverse32(&reserved);
reserve(reserved);
size_used_ = reserved;
if (fp->FRead(data_, sizeof(T), size_used_) != size_used_) return false;
if (swap) {
for (int i = 0; i < size_used_; ++i)
ReverseN(&data_[i], sizeof(data_[i]));
}
return true;
}
// Writes a vector of classes to the given file. Assumes the existence of
// bool T::Serialize(FILE* fp) const that returns false in case of error.
// Returns false in case of error.
template <typename T>
bool GenericVector<T>::SerializeClasses(FILE* fp) const {
if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false;
for (int i = 0; i < size_used_; ++i) {
if (!data_[i].Serialize(fp)) return false;
}
return true;
}
template <typename T>
bool GenericVector<T>::SerializeClasses(tesseract::TFile* fp) const {
if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
for (int i = 0; i < size_used_; ++i) {
if (!data_[i].Serialize(fp)) return false;
}
return true;
}
// Reads a vector of classes from the given file. Assumes the existence of
// bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
// error. Alse needs T::T() and T::T(constT&), as init_to_size is used in
// this function. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
template <typename T>
bool GenericVector<T>::DeSerializeClasses(bool swap, FILE* fp) {
uinT32 reserved;
if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
if (swap) Reverse32(&reserved);
T empty;
init_to_size(reserved, empty);
for (int i = 0; i < reserved; ++i) {
if (!data_[i].DeSerialize(swap, fp)) return false;
}
return true;
}
template <typename T>
bool GenericVector<T>::DeSerializeClasses(bool swap, tesseract::TFile* fp) {
uinT32 reserved;
if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
if (swap) Reverse32(&reserved);
T empty;
init_to_size(reserved, empty);
for (int i = 0; i < reserved; ++i) {
if (!data_[i].DeSerialize(swap, fp)) return false;
}
return true;
}
// This method clear the current object, then, does a shallow copy of
// its argument, and finally invalidates its argument.
template <typename T>
void GenericVector<T>::move(GenericVector<T>* from) {
this->clear();
this->data_ = from->data_;
this->size_reserved_ = from->size_reserved_;
this->size_used_ = from->size_used_;
this->compare_cb_ = from->compare_cb_;
this->clear_cb_ = from->clear_cb_;
from->data_ = NULL;
from->clear_cb_ = NULL;
from->compare_cb_ = NULL;
from->size_used_ = 0;
from->size_reserved_ = 0;
}
template <typename T>
void GenericVector<T>::sort() {
sort(&tesseract::sort_cmp<T>);
}
// Internal recursive version of choose_nth_item.
// The algorithm used comes from "Algorithms" by Sedgewick:
// http://books.google.com/books/about/Algorithms.html?id=idUdqdDXqnAC
// The principle is to choose a random pivot, and move everything less than
// the pivot to its left, and everything greater than the pivot to the end
// of the array, then recurse on the part that contains the desired index, or
// just return the answer if it is in the equal section in the middle.
// The random pivot guarantees average linear time for the same reason that
// n times vector::push_back takes linear time on average.
// target_index, start and and end are all indices into the full array.
// Seed is a seed for rand_r for thread safety purposes. Its value is
// unimportant as the random numbers do not affect the result except
// between equal answers.
template <typename T>
int GenericVector<T>::choose_nth_item(int target_index, int start, int end,
unsigned int* seed) {
// Number of elements to process.
int num_elements = end - start;
// Trivial cases.
if (num_elements <= 1)
return start;
if (num_elements == 2) {
if (data_[start] < data_[start + 1]) {
return target_index > start ? start + 1 : start;
} else {
return target_index > start ? start : start + 1;
}
}
// Place the pivot at start.
#ifndef rand_r // _MSC_VER, ANDROID
srand(*seed);
#define rand_r(seed) rand()
#endif // _MSC_VER
int pivot = rand_r(seed) % num_elements + start;
swap(pivot, start);
// The invariant condition here is that items [start, next_lesser) are less
// than the pivot (which is at index next_lesser) and items
// [prev_greater, end) are greater than the pivot, with items
// [next_lesser, prev_greater) being equal to the pivot.
int next_lesser = start;
int prev_greater = end;
for (int next_sample = start + 1; next_sample < prev_greater;) {
if (data_[next_sample] < data_[next_lesser]) {
swap(next_lesser++, next_sample++);
} else if (data_[next_sample] == data_[next_lesser]) {
++next_sample;
} else {
swap(--prev_greater, next_sample);
}
}
// Now the invariant is set up, we recurse on just the section that contains
// the desired index.
if (target_index < next_lesser)
return choose_nth_item(target_index, start, next_lesser, seed);
else if (target_index < prev_greater)
return next_lesser; // In equal bracket.
else
return choose_nth_item(target_index, prev_greater, end, seed);
}
#endif // TESSERACT_CCUTIL_GENERICVECTOR_H_
| C++ |
/**********************************************************************
* File: bits16.h (Formerly bits8.h)
* Description: Code for 8 bit field class.
* Author: Phil Cheatle
* Created: Thu Oct 17 10:10:05 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "bits16.h"
/**********************************************************************
* Constructor. Something to get it past the compiler as almost all inlined.
*
**********************************************************************/
BITS16::BITS16( // constructor
uinT16 init) { // initial val
val = init;
}
| C++ |
/**********************************************************************
* File: memry.c (Formerly memory.c)
* Description: Memory allocation with builtin safety checks.
* Author: Ray Smith
* Created: Wed Jan 22 09:43:33 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "memry.h"
#include <stdlib.h>
// With improvements in OS memory allocators, internal memory management
// is no longer required, so all these functions now map to their malloc
// family equivalents.
// TODO(rays) further cleanup by redirecting calls to new and creating proper
// constructors.
char *alloc_string(inT32 count) {
// Round up the amount allocated to a multiple of 4
return static_cast<char*>(malloc((count + 3) & ~3));
}
void free_string(char *string) {
free(string);
}
void* alloc_struct(inT32 count, const char *) {
return malloc(count);
}
void free_struct(void *deadstruct, inT32, const char *) {
free(deadstruct);
}
void *alloc_mem(inT32 count) {
return malloc(static_cast<size_t>(count));
}
void *alloc_big_zeros(inT32 count) {
return calloc(static_cast<size_t>(count), 1);
}
void free_mem(void *oldchunk) {
free(oldchunk);
}
void free_big_mem(void *oldchunk) {
free(oldchunk);
}
| C++ |
///////////////////////////////////////////////////////////////////////
// File: ambigs.h
// Description: Constants, flags, functions for dealing with
// ambiguities (training and recognition).
// Author: Daria Antonova
// Created: Mon Aug 23 11:26:43 PDT 2008
//
// (C) Copyright 2008, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_AMBIGS_H_
#define TESSERACT_CCUTIL_AMBIGS_H_
#include "elst.h"
#include "tprintf.h"
#include "unichar.h"
#include "unicharset.h"
#include "genericvector.h"
#define MAX_AMBIG_SIZE 10
namespace tesseract {
typedef GenericVector<UNICHAR_ID> UnicharIdVector;
static const int kUnigramAmbigsBufferSize = 1000;
static const char kAmbigNgramSeparator[] = { ' ', '\0' };
static const char kAmbigDelimiters[] = "\t ";
static const char kIllegalMsg[] =
"Illegal ambiguity specification on line %d\n";
static const char kIllegalUnicharMsg[] =
"Illegal unichar %s in ambiguity specification\n";
enum AmbigType {
NOT_AMBIG, // the ngram pair is not ambiguous
REPLACE_AMBIG, // ocred ngram should always be substituted with correct
DEFINITE_AMBIG, // add correct ngram to the classifier results (1-1)
SIMILAR_AMBIG, // use pairwise classifier for ocred/correct pair (1-1)
CASE_AMBIG, // this is a case ambiguity (1-1)
AMBIG_TYPE_COUNT // number of enum entries
};
// A collection of utility functions for arrays of UNICHAR_IDs that are
// terminated by INVALID_UNICHAR_ID.
class UnicharIdArrayUtils {
public:
// Compares two arrays of unichar ids. Returns -1 if the length of array1 is
// less than length of array2, if any array1[i] is less than array2[i].
// Returns 0 if the arrays are equal, 1 otherwise.
// The function assumes that the arrays are terminated by INVALID_UNICHAR_ID.
static inline int compare(const UNICHAR_ID array1[],
const UNICHAR_ID array2[]) {
const UNICHAR_ID *ptr1 = array1;
const UNICHAR_ID *ptr2 = array2;
while (*ptr1 != INVALID_UNICHAR_ID && *ptr2 != INVALID_UNICHAR_ID) {
if (*ptr1 != *ptr2) return *ptr1 < *ptr2 ? -1 : 1;
++ptr1;
++ptr2;
}
if (*ptr1 == INVALID_UNICHAR_ID && *ptr2 == INVALID_UNICHAR_ID) return 0;
return *ptr1 == INVALID_UNICHAR_ID ? -1 : 1;
}
// Look uid in the vector of uids. If found, the index of the matched
// element is returned. Otherwise, it returns -1.
static inline int find_in(const UnicharIdVector& uid_vec,
const UNICHAR_ID uid) {
for (int i = 0; i < uid_vec.size(); ++i)
if (uid_vec[i] == uid) return i;
return -1;
}
// Copies UNICHAR_IDs from dst to src. Returns the number of ids copied.
// The function assumes that the arrays are terminated by INVALID_UNICHAR_ID
// and that dst has enough space for all the elements from src.
static inline int copy(const UNICHAR_ID src[], UNICHAR_ID dst[]) {
int i = 0;
do {
dst[i] = src[i];
} while (dst[i++] != INVALID_UNICHAR_ID);
return i - 1;
}
// Prints unichars corresponding to the unichar_ids in the given array.
// The function assumes that array is terminated by INVALID_UNICHAR_ID.
static inline void print(const UNICHAR_ID array[],
const UNICHARSET &unicharset) {
const UNICHAR_ID *ptr = array;
if (*ptr == INVALID_UNICHAR_ID) tprintf("[Empty]");
while (*ptr != INVALID_UNICHAR_ID) {
tprintf("%s ", unicharset.id_to_unichar(*ptr++));
}
tprintf("( ");
ptr = array;
while (*ptr != INVALID_UNICHAR_ID) tprintf("%d ", *ptr++);
tprintf(")\n");
}
};
// AMBIG_SPEC_LIST stores a list of dangerous ambigs that
// start with the same unichar (e.g. r->t rn->m rr1->m).
class AmbigSpec : public ELIST_LINK {
public:
AmbigSpec();
~AmbigSpec() {}
// Comparator function for sorting AmbigSpec_LISTs. The lists will
// be sorted by their wrong_ngram arrays. Example of wrong_ngram vectors
// in a a sorted AmbigSpec_LIST: [9 1 3], [9 3 4], [9 8], [9, 8 1].
static int compare_ambig_specs(const void *spec1, const void *spec2) {
const AmbigSpec *s1 =
*reinterpret_cast<const AmbigSpec * const *>(spec1);
const AmbigSpec *s2 =
*reinterpret_cast<const AmbigSpec * const *>(spec2);
int result = UnicharIdArrayUtils::compare(s1->wrong_ngram, s2->wrong_ngram);
if (result != 0) return result;
return UnicharIdArrayUtils::compare(s1->correct_fragments,
s2->correct_fragments);
}
UNICHAR_ID wrong_ngram[MAX_AMBIG_SIZE + 1];
UNICHAR_ID correct_fragments[MAX_AMBIG_SIZE + 1];
UNICHAR_ID correct_ngram_id;
AmbigType type;
int wrong_ngram_size;
};
ELISTIZEH(AmbigSpec);
// AMBIG_TABLE[i] stores a set of ambiguities whose
// wrong ngram starts with unichar id i.
typedef GenericVector<AmbigSpec_LIST *> UnicharAmbigsVector;
class UnicharAmbigs {
public:
UnicharAmbigs() {}
~UnicharAmbigs() {
replace_ambigs_.delete_data_pointers();
dang_ambigs_.delete_data_pointers();
one_to_one_definite_ambigs_.delete_data_pointers();
}
const UnicharAmbigsVector &dang_ambigs() const { return dang_ambigs_; }
const UnicharAmbigsVector &replace_ambigs() const { return replace_ambigs_; }
// Initializes the ambigs by adding a NULL pointer to each table.
void InitUnicharAmbigs(const UNICHARSET& unicharset,
bool use_ambigs_for_adaption);
// Loads the universal ambigs that are useful for any language.
void LoadUniversal(const UNICHARSET& encoder_set, UNICHARSET* unicharset);
// Fills in two ambiguity tables (replaceable and dangerous) with information
// read from the ambigs file. An ambiguity table is an array of lists.
// The array is indexed by a class id. Each entry in the table provides
// a list of potential ambiguities which can start with the corresponding
// character. For example the ambiguity "rn -> m", would be located in the
// table at index of unicharset.unichar_to_id('r').
// In 1-1 ambiguities (e.g. s -> S, 1 -> I) are recorded in
// one_to_one_definite_ambigs_. This vector is also indexed by the class id
// of the wrong part of the ambiguity and each entry contains a vector of
// unichar ids that are ambiguous to it.
// encoder_set is used to encode the ambiguity strings, undisturbed by new
// unichar_ids that may be created by adding the ambigs.
void LoadUnicharAmbigs(const UNICHARSET& encoder_set,
TFile *ambigs_file, int debug_level,
bool use_ambigs_for_adaption, UNICHARSET *unicharset);
// Returns definite 1-1 ambigs for the given unichar id.
inline const UnicharIdVector *OneToOneDefiniteAmbigs(
UNICHAR_ID unichar_id) const {
if (one_to_one_definite_ambigs_.empty()) return NULL;
return one_to_one_definite_ambigs_[unichar_id];
}
// Returns a pointer to the vector with all unichar ids that appear in the
// 'correct' part of the ambiguity pair when the given unichar id appears
// in the 'wrong' part of the ambiguity. E.g. if DangAmbigs file consist of
// m->rn,rn->m,m->iii, UnicharAmbigsForAdaption() called with unichar id of
// m will return a pointer to a vector with unichar ids of r,n,i.
inline const UnicharIdVector *AmbigsForAdaption(
UNICHAR_ID unichar_id) const {
if (ambigs_for_adaption_.empty()) return NULL;
return ambigs_for_adaption_[unichar_id];
}
// Similar to the above, but return the vector of unichar ids for which
// the given unichar_id is an ambiguity (appears in the 'wrong' part of
// some ambiguity pair).
inline const UnicharIdVector *ReverseAmbigsForAdaption(
UNICHAR_ID unichar_id) const {
if (reverse_ambigs_for_adaption_.empty()) return NULL;
return reverse_ambigs_for_adaption_[unichar_id];
}
private:
bool ParseAmbiguityLine(int line_num, int version, int debug_level,
const UNICHARSET &unicharset, char *buffer,
int *test_ambig_part_size,
UNICHAR_ID *test_unichar_ids,
int *replacement_ambig_part_size,
char *replacement_string, int *type);
bool InsertIntoTable(UnicharAmbigsVector &table,
int test_ambig_part_size, UNICHAR_ID *test_unichar_ids,
int replacement_ambig_part_size,
const char *replacement_string, int type,
AmbigSpec *ambig_spec, UNICHARSET *unicharset);
UnicharAmbigsVector dang_ambigs_;
UnicharAmbigsVector replace_ambigs_;
GenericVector<UnicharIdVector *> one_to_one_definite_ambigs_;
GenericVector<UnicharIdVector *> ambigs_for_adaption_;
GenericVector<UnicharIdVector *> reverse_ambigs_for_adaption_;
};
} // namespace tesseract
#endif // TESSERACT_CCUTIL_AMBIGS_H_
| C++ |
///////////////////////////////////////////////////////////////////////
// File: sorthelper.h
// Description: Generic sort and maxfinding class.
// Author: Ray Smith
// Created: Thu May 20 17:48:21 PDT 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCUTIL_SORTHELPER_H_
#define TESSERACT_CCUTIL_SORTHELPER_H_
#include <stdlib.h>
#include "genericvector.h"
// Generic class to provide functions based on a <value,count> pair.
// T is the value type.
// The class keeps a count of each value and can return the most frequent
// value or a sorted array of the values with counts.
// Note that this class uses linear search for adding. It is better
// to use the STATS class to get the mode of a large number of values
// in a small space. SortHelper is better to get the mode of a small number
// of values from a large space.
// T must have a copy constructor.
template <typename T>
class SortHelper {
public:
// Simple pair class to hold the values and counts.
template<typename PairT> struct SortPair {
PairT value;
int count;
};
// qsort function to sort by decreasing count.
static int SortPairsByCount(const void* v1, const void* v2) {
const SortPair<T>* p1 = reinterpret_cast<const SortPair<T>*>(v1);
const SortPair<T>* p2 = reinterpret_cast<const SortPair<T>*>(v2);
return p2->count - p1->count;
}
// qsort function to sort by decreasing value.
static int SortPairsByValue(const void* v1, const void* v2) {
const SortPair<T>* p1 = reinterpret_cast<const SortPair<T>*>(v1);
const SortPair<T>* p2 = reinterpret_cast<const SortPair<T>*>(v2);
if (p2->value - p1->value < 0) return -1;
if (p2->value - p1->value > 0) return 1;
return 0;
}
// Constructor takes a hint of the array size, but it need not be accurate.
explicit SortHelper(int sizehint) {
counts_.reserve(sizehint);
}
// Add a value that may be a duplicate of an existing value.
// Uses a linear search.
void Add(T value, int count) {
// Linear search for value.
for (int i = 0; i < counts_.size(); ++i) {
if (counts_[i].value == value) {
counts_[i].count += count;
return;
}
}
SortPair<T> new_pair = {value, count};
counts_.push_back(SortPair<T>(new_pair));
}
// Returns the frequency of the most frequent value.
// If max_value is not NULL, returns the most frequent value.
// If the array is empty, returns -MAX_INT32 and max_value is unchanged.
int MaxCount(T* max_value) const {
int best_count = -MAX_INT32;
for (int i = 0; i < counts_.size(); ++i) {
if (counts_[i].count > best_count) {
best_count = counts_[i].count;
if (max_value != NULL)
*max_value = counts_[i].value;
}
}
return best_count;
}
// Returns the data array sorted by decreasing frequency.
const GenericVector<SortPair<T> >& SortByCount() {
counts_.sort(&SortPairsByCount);
return counts_;
}
// Returns the data array sorted by decreasing value.
const GenericVector<SortPair<T> >& SortByValue() {
counts_.sort(&SortPairsByValue);
return counts_;
}
private:
GenericVector<SortPair<T> > counts_;
};
#endif // TESSERACT_CCUTIL_SORTHELPER_H_.
| C++ |
/**********************************************************************
* File: unicodes.h
* Description: Unicode related machinery
* Author: David Eger
* Created: Wed Jun 15 16:37:50 PST 2011
*
* (C) Copyright 2011, Google, Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef TESSERACT_CCUTIL_UNICODES_H__
#define TESSERACT_CCUTIL_UNICODES_H__
namespace tesseract {
extern const char *kUTF8LineSeparator;
extern const char *kUTF8ParagraphSeparator;
extern const char *kLRM; // Left-to-Right Mark
extern const char *kRLM; // Right-to-Left Mark
extern const char *kRLE; // Right-to-Left Embedding
extern const char *kPDF; // Pop Directional Formatting
// The following are confusable internal word punctuation symbols
// which we normalize to the first variant when matching in dawgs.
extern const char *kHyphenLikeUTF8[];
extern const char *kApostropheLikeUTF8[];
} // namespace
#endif // TESSERACT_CCUTIL_UNICODES_H__
| C++ |
///////////////////////////////////////////////////////////////////////
// File: cutil.cpp
// Description: cutil class.
// Author: Samuel Charron
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "cutil_class.h"
namespace tesseract {
CUtil::CUtil() {
}
CUtil::~CUtil() {
}
} // namespace tesseract
| C++ |
/**********************************************************************
* File: callcpp.h
* Description: extern C interface calling C++ from C.
* Author: Ray Smith
* Created: Sun Feb 04 20:39:23 MST 1996
*
* (C) Copyright 1996, Hewlett-Packard Co.
** 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 CALLCPP_H
#define CALLCPP_H
#ifndef __UNIX__
#include <assert.h>
#endif
#include "host.h"
#include "params.h"
#include "unichar.h"
class ScrollView;
typedef enum {
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,
Turqoise,
Dark_TURQUOISE,
Violet,
Wheat,
Green_YELLOW
} C_COL; /*starbase colours */
void cprintf ( //Trace printf
const char *format, ... //special message
);
ScrollView *c_create_window( /*create a window */
const char *name, /*name/title of window */
inT16 xpos, /*coords of window */
inT16 ypos, /*coords of window */
inT16 xsize, /*size of window */
inT16 ysize, /*size of window */
double xmin, /*scrolling limits */
double xmax, /*to stop users */
double ymin, /*getting lost in */
double ymax /*empty space */
);
void c_line_color_index( /*set color */
void *win,
C_COL index);
void c_move( /*move pen */
void *win,
double x,
double y);
void c_draw( /*move pen */
void *win,
double x,
double y);
void c_make_current( /*move pen */
void *win);
void c_clear_window( /*move pen */
void *win);
char window_wait(ScrollView* win);
void reverse32(void *ptr);
void reverse16(void *ptr);
#endif
| C++ |
/**********************************************************************
* File: callcpp.cpp
* Description: extern C interface calling C++ from C.
* Author: Ray Smith
* Created: Sun Feb 04 20:39:23 MST 1996
*
* (C) Copyright 1996, Hewlett-Packard Co.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "errcode.h"
#ifdef __UNIX__
#include <assert.h>
#include <stdarg.h>
#endif
#include <time.h>
#include "memry.h"
#include "scrollview.h"
#include "params.h"
#include "callcpp.h"
#include "tprintf.h"
#include "host.h"
#include "unichar.h"
void
cprintf ( //Trace printf
const char *format, ... //special message
) {
va_list args; //variable args
char msg[1000];
va_start(args, format); //variable list
vsprintf(msg, format, args); //Format into msg
va_end(args);
tprintf ("%s", msg);
}
#ifndef GRAPHICS_DISABLED
ScrollView *c_create_window( /*create a window */
const char *name, /*name/title of window */
inT16 xpos, /*coords of window */
inT16 ypos, /*coords of window */
inT16 xsize, /*size of window */
inT16 ysize, /*size of window */
double xmin, /*scrolling limits */
double xmax, /*to stop users */
double ymin, /*getting lost in */
double ymax /*empty space */
) {
return new ScrollView(name, xpos, ypos, xsize, ysize, xmax - xmin, ymax - ymin, true);
}
void c_line_color_index( /*set color */
void *win,
C_COL index) {
// The colors are the same as the SV ones except that SV has COLOR:NONE --> offset of 1
ScrollView* window = (ScrollView*) win;
window->Pen((ScrollView::Color) (index + 1));
}
void c_move( /*move pen */
void *win,
double x,
double y) {
ScrollView* window = (ScrollView*) win;
window->SetCursor((int) x, (int) y);
}
void c_draw( /*move pen */
void *win,
double x,
double y) {
ScrollView* window = (ScrollView*) win;
window->DrawTo((int) x, (int) y);
}
void c_make_current( /*move pen */
void *win) {
ScrollView* window = (ScrollView*) win;
window->Update();
}
void c_clear_window( /*move pen */
void *win) {
ScrollView* window = (ScrollView*) win;
window->Clear();
}
char window_wait(ScrollView* win) {
SVEvent* ev;
// Wait till an input or click event (all others are thrown away)
char ret = '\0';
SVEventType ev_type = SVET_ANY;
do {
ev = win->AwaitEvent(SVET_ANY);
ev_type = ev->type;
if (ev_type == SVET_INPUT)
ret = ev->parameter[0];
delete ev;
} while (ev_type != SVET_INPUT && ev_type != SVET_CLICK);
return ret;
}
#endif
void reverse32(void *ptr) {
char tmp;
char *cptr = (char *) ptr;
tmp = *cptr;
*cptr = *(cptr + 3);
*(cptr + 3) = tmp;
tmp = *(cptr + 1);
*(cptr + 1) = *(cptr + 2);
*(cptr + 2) = tmp;
}
void reverse16(void *ptr) {
char tmp;
char *cptr = (char *) ptr;
tmp = *cptr;
*cptr = *(cptr + 1);
*(cptr + 1) = tmp;
}
| C++ |
/******************************************************************************
** Filename: bitvec.c
** Purpose: Routines for manipulating bit vectors
** Author: Dan Johnson
** History: Thu Mar 15 10:37:27 1990, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/*-----------------------------------------------------------------------------
Include Files and Type Defines
-----------------------------------------------------------------------------*/
#include "bitvec.h"
#include <stdio.h>
#include "emalloc.h"
#include "freelist.h"
#include "tprintf.h"
/*-----------------------------------------------------------------------------
Public Code
-----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
* This routine uses realloc to increase the size of
* the specified bit vector.
*
* Globals:
* - none
*
* @param Vector bit vector to be expanded
* @param NewNumBits new size of bit vector
*
* @return New expanded bit vector.
* @note Exceptions: none
* @note History: Fri Nov 16 10:11:16 1990, DSJ, Created.
*/
BIT_VECTOR ExpandBitVector(BIT_VECTOR Vector, int NewNumBits) {
return ((BIT_VECTOR) Erealloc(Vector,
sizeof(Vector[0]) * WordsInVectorOfSize(NewNumBits)));
} /* ExpandBitVector */
/*---------------------------------------------------------------------------*/
void FreeBitVector(BIT_VECTOR BitVector) {
/**
* This routine frees a bit vector. It also decrements
* the global counter that keeps track of the number of
* bit vectors allocated. If BitVector is NULL, then
* the count is printed to stderr.
*
* Globals:
* - BitVectorCount count of number of bit vectors allocated
*
* @param BitVector bit vector to be freed
*
* @note Exceptions: none
* @note History: Tue Oct 23 16:46:09 1990, DSJ, Created.
*/
if (BitVector) {
Efree(BitVector);
}
} /* FreeBitVector */
/*---------------------------------------------------------------------------*/
/**
* Allocate and return a new bit vector large enough to
* hold the specified number of bits.
*
* Globals:
* - BitVectorCount number of bit vectors allocated
*
* @param NumBits number of bits in new bit vector
*
* @return New bit vector.
* @note Exceptions: none
* @note History: Tue Oct 23 16:51:27 1990, DSJ, Created.
*/
BIT_VECTOR NewBitVector(int NumBits) {
return ((BIT_VECTOR) Emalloc(sizeof(uinT32) *
WordsInVectorOfSize(NumBits)));
} /* NewBitVector */
| C++ |
///////////////////////////////////////////////////////////////////////
// File: cutil.h
// Description: cutil class.
// Author: Samuel Charron
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CUTIL_CUTIL_CLASS_H__
#define TESSERACT_CUTIL_CUTIL_CLASS_H__
#include "ccutil.h"
#include "const.h"
#include "strngs.h"
namespace tesseract {
class CUtil : public CCUtil {
public:
CUtil();
~CUtil();
void read_variables(const char *filename, bool global_only);
};
} // namespace tesseract
#endif // TESSERACT_CUTIL_CUTIL_CLASS_H__
| C++ |
/******************************************************************************
** Filename:
emalloc.c
** Purpose:
Routines for trapping memory allocation errors.
** Author:
Dan Johnson
HP-UX 6.2
HP-UX 6.2
** History:
4/3/89, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/**----------------------------------------------------------------------------
Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "emalloc.h"
#include "danerror.h"
#include <stdlib.h>
/**----------------------------------------------------------------------------
Public Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
void *Emalloc(int Size) {
/*
** Parameters:
** Size
number of bytes of memory to be allocated
** Globals: none
** Operation:
** This routine attempts to allocate the specified number of
** bytes. If the memory can be allocated, a pointer to the
** memory is returned. If the memory cannot be allocated, or
** if the allocation request is negative or zero,
** an error is trapped.
** Return: Pointer to allocated memory.
** Exceptions: NOTENOUGHMEMORY
unable to allocate Size bytes
** ILLEGALMALLOCREQUEST
negative or zero request size
** History: 4/3/89, DSJ, Created.
*/
void *Buffer;
if (Size <= 0)
DoError (ILLEGALMALLOCREQUEST, "Illegal malloc request size");
Buffer = (void *) malloc (Size);
if (Buffer == NULL) {
DoError (NOTENOUGHMEMORY, "Not enough memory");
return (NULL);
}
else
return (Buffer);
} /* Emalloc */
/*---------------------------------------------------------------------------*/
void *Erealloc(void *ptr, int size) {
void *Buffer;
if (size < 0 || (size == 0 && ptr == NULL))
DoError (ILLEGALMALLOCREQUEST, "Illegal realloc request size");
Buffer = (void *) realloc (ptr, size);
if (Buffer == NULL && size != 0)
DoError (NOTENOUGHMEMORY, "Not enough memory");
return (Buffer);
} /* Erealloc */
/*---------------------------------------------------------------------------*/
void Efree(void *ptr) {
if (ptr == NULL)
DoError (ILLEGALMALLOCREQUEST, "Attempted to free NULL ptr");
free(ptr);
} /* Efree */
| C++ |
/******************************************************************************
** Filename: efio.c
** Purpose: Utility I/O routines
** Author: Dan Johnson
** History: 5/21/89, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/**----------------------------------------------------------------------------
Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "efio.h"
#include "danerror.h"
#include <stdio.h>
#include <string.h>
#define MAXERRORMESSAGE 256
/**----------------------------------------------------------------------------
Public Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
FILE *Efopen(const char *Name, const char *Mode) {
/*
** Parameters:
** Name name of file to be opened
** Mode mode to be used to open file
** Globals:
** None
** Operation:
** This routine attempts to open the specified file in the
** specified mode. If the file can be opened, a pointer to
** the open file is returned. If the file cannot be opened,
** an error is trapped.
** Return:
** Pointer to open file.
** Exceptions:
** FOPENERROR unable to open specified file
** History:
** 5/21/89, DSJ, Created.
*/
FILE *File;
char ErrorMessage[MAXERRORMESSAGE];
File = fopen (Name, Mode);
if (File == NULL) {
sprintf (ErrorMessage, "Unable to open %s", Name);
DoError(FOPENERROR, ErrorMessage);
return (NULL);
}
else
return (File);
} /* Efopen */
| C++ |
/**************************************************************************
** 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 "freelist.h"
#include <stdlib.h>
// With improvements in OS memory allocators, internal memory management is
// no longer required, so these functions all map to their malloc-family
// equivalents.
int *memalloc(int size) {
return static_cast<int*>(malloc(static_cast<size_t>(size)));
}
int *memrealloc(void *ptr, int size, int oldsize) {
return static_cast<int*>(realloc(ptr, static_cast<size_t>(size)));
}
void memfree(void *element) {
free(element);
}
| C++ |
/******************************************************************************
** Filename: danerror.c
** Purpose: Routines for managing error trapping
** Author: Dan Johnson
** History: 3/17/89, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/**----------------------------------------------------------------------------
Include Files and Type Defines
----------------------------------------------------------------------------**/
#include "host.h"
#include "danerror.h"
#include "tprintf.h"
#include "globaloc.h"
#ifdef __UNIX__
#include "assert.h"
#endif
#include <stdio.h>
/*---------------------------------------------------------------------------*/
void DoError(int Error, const char *Message) {
/*
** Parameters:
** Error error number which is to be trapped
** Message pointer to a string to be printed as an error message
** Globals:
** ErrorTrapStack stack of error traps
** CurrentTrapDepth number of traps on the stack
** Operation:
** This routine prints the specified error message to stderr.
** It then jumps to the current error trap. If the error trap
** stack is empty, the calling program is terminated with a
** fatal error message.
** Return:
** None - this routine does not return.
** Exceptions:
** Empty error trap stack terminates the calling program.
** History:
** 4/3/89, DSJ, Created.
*/
if (Message != NULL) {
tprintf("\nError: %s!\n", Message);
}
err_exit();
} /* DoError */
| 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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_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: 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: 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: 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: 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: 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_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: 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: 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: 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: 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: 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_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: 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: 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: 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: 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: 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: 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: 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: 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: 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.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_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: 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: 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: 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: 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: 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_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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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, ¶m_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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: baseapi.h
// Description: Simple API for calling tesseract.
// Author: Ray Smith
// Created: Fri Oct 06 15:35:01 PDT 2006
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_BASEAPI_H__
#define TESSERACT_API_BASEAPI_H__
#define TESSERACT_VERSION_STR "3.04.00"
#define TESSERACT_VERSION 0x030400
#define MAKE_VERSION(major, minor, patch) (((major) << 16) | ((minor) << 8) | \
(patch))
#include <stdio.h>
// To avoid collision with other typenames include the ABSOLUTE MINIMUM
// complexity of includes here. Use forward declarations wherever possible
// and hide includes of complex types in baseapi.cpp.
#include "platform.h"
#include "apitypes.h"
#include "thresholder.h"
#include "unichar.h"
#include "tesscallback.h"
#include "publictypes.h"
#include "pageiterator.h"
#include "resultiterator.h"
template <typename T> class GenericVector;
class PAGE_RES;
class PAGE_RES_IT;
class ParagraphModel;
struct BlamerBundle;
class BLOCK_LIST;
class DENORM;
class MATRIX;
class ROW;
class STRING;
class WERD;
struct Pix;
struct Box;
struct Pixa;
struct Boxa;
class ETEXT_DESC;
struct OSResults;
class TBOX;
class UNICHARSET;
class WERD_CHOICE_LIST;
struct INT_FEATURE_STRUCT;
typedef INT_FEATURE_STRUCT *INT_FEATURE;
struct TBLOB;
namespace tesseract {
class CubeRecoContext;
class Dawg;
class Dict;
class EquationDetect;
class PageIterator;
class LTRResultIterator;
class ResultIterator;
class MutableIterator;
class TessResultRenderer;
class Tesseract;
class Trie;
class Wordrec;
typedef int (Dict::*DictFunc)(void* void_dawg_args,
UNICHAR_ID unichar_id, bool word_end) const;
typedef double (Dict::*ProbabilityInContextFunc)(const char* lang,
const char* context,
int context_bytes,
const char* character,
int character_bytes);
typedef float (Dict::*ParamsModelClassifyFunc)(
const char *lang, void *path);
typedef void (Wordrec::*FillLatticeFunc)(const MATRIX &ratings,
const WERD_CHOICE_LIST &best_choices,
const UNICHARSET &unicharset,
BlamerBundle *blamer_bundle);
typedef TessCallback4<const UNICHARSET &, int, PageIterator *, Pix *>
TruthCallback;
/**
* Base class for all tesseract APIs.
* Specific classes can add ability to work on different inputs or produce
* different outputs.
* This class is mostly an interface layer on top of the Tesseract instance
* class to hide the data types so that users of this class don't have to
* include any other Tesseract headers.
*/
class TESS_API TessBaseAPI {
public:
TessBaseAPI();
virtual ~TessBaseAPI();
/**
* Returns the version identifier as a static string. Do not delete.
*/
static const char* Version();
/**
* If compiled with OpenCL AND an available OpenCL
* device is deemed faster than serial code, then
* "device" is populated with the cl_device_id
* and returns sizeof(cl_device_id)
* otherwise *device=NULL and returns 0.
*/
static size_t getOpenCLDevice(void **device);
/**
* Writes the thresholded image to stderr as a PBM file on receipt of a
* SIGSEGV, SIGFPE, or SIGBUS signal. (Linux/Unix only).
*/
static void CatchSignals();
/**
* Set the name of the input file. Needed for training and
* reading a UNLV zone file, and for searchable PDF output.
*/
void SetInputName(const char* name);
/**
* These functions are required for searchable PDF output.
* We need our hands on the input file so that we can include
* it in the PDF without transcoding. If that is not possible,
* we need the original image. Finally, resolution metadata
* is stored in the PDF so we need that as well.
*/
const char* GetInputName();
void SetInputImage(Pix *pix);
Pix* GetInputImage();
int GetSourceYResolution();
const char* GetDatapath();
/** Set the name of the bonus output files. Needed only for debugging. */
void SetOutputName(const char* name);
/**
* Set the value of an internal "parameter."
* Supply the name of the parameter and the value as a string, just as
* you would in a config file.
* Returns false if the name lookup failed.
* Eg SetVariable("tessedit_char_blacklist", "xyz"); to ignore x, y and z.
* Or SetVariable("classify_bln_numeric_mode", "1"); to set numeric-only mode.
* SetVariable may be used before Init, but settings will revert to
* defaults on End().
*
* Note: Must be called after Init(). Only works for non-init variables
* (init variables should be passed to Init()).
*/
bool SetVariable(const char* name, const char* value);
bool SetDebugVariable(const char* name, const char* value);
/**
* Returns true if the parameter was found among Tesseract parameters.
* Fills in value with the value of the parameter.
*/
bool GetIntVariable(const char *name, int *value) const;
bool GetBoolVariable(const char *name, bool *value) const;
bool GetDoubleVariable(const char *name, double *value) const;
/**
* Returns the pointer to the string that represents the value of the
* parameter if it was found among Tesseract parameters.
*/
const char *GetStringVariable(const char *name) const;
/**
* Print Tesseract parameters to the given file.
*/
void PrintVariables(FILE *fp) const;
/**
* Get value of named variable as a string, if it exists.
*/
bool GetVariableAsString(const char *name, STRING *val);
/**
* Instances are now mostly thread-safe and totally independent,
* but some global parameters remain. Basically it is safe to use multiple
* TessBaseAPIs in different threads in parallel, UNLESS:
* you use SetVariable on some of the Params in classify and textord.
* If you do, then the effect will be to change it for all your instances.
*
* Start tesseract. Returns zero on success and -1 on failure.
* NOTE that the only members that may be called before Init are those
* listed above here in the class definition.
*
* The datapath must be the name of the parent directory of tessdata and
* must end in / . Any name after the last / will be stripped.
* The language is (usually) an ISO 639-3 string or NULL will default to eng.
* It is entirely safe (and eventually will be efficient too) to call
* Init multiple times on the same instance to change language, or just
* to reset the classifier.
* The language may be a string of the form [~]<lang>[+[~]<lang>]* indicating
* that multiple languages are to be loaded. Eg hin+eng will load Hindi and
* English. Languages may specify internally that they want to be loaded
* with one or more other languages, so the ~ sign is available to override
* that. Eg if hin were set to load eng by default, then hin+~eng would force
* loading only hin. The number of loaded languages is limited only by
* memory, with the caveat that loading additional languages will impact
* both speed and accuracy, as there is more work to do to decide on the
* applicable language, and there is more chance of hallucinating incorrect
* words.
* WARNING: On changing languages, all Tesseract parameters are reset
* back to their default values. (Which may vary between languages.)
* If you have a rare need to set a Variable that controls
* initialization for a second call to Init you should explicitly
* call End() and then use SetVariable before Init. This is only a very
* rare use case, since there are very few uses that require any parameters
* to be set before Init.
*
* If set_only_non_debug_params is true, only params that do not contain
* "debug" in the name will be set.
*/
int Init(const char* datapath, const char* language, OcrEngineMode mode,
char **configs, int configs_size,
const GenericVector<STRING> *vars_vec,
const GenericVector<STRING> *vars_values,
bool set_only_non_debug_params);
int Init(const char* datapath, const char* language, OcrEngineMode oem) {
return Init(datapath, language, oem, NULL, 0, NULL, NULL, false);
}
int Init(const char* datapath, const char* language) {
return Init(datapath, language, OEM_DEFAULT, NULL, 0, NULL, NULL, false);
}
/**
* Returns the languages string used in the last valid initialization.
* If the last initialization specified "deu+hin" then that will be
* returned. If hin loaded eng automatically as well, then that will
* not be included in this list. To find the languages actually
* loaded use GetLoadedLanguagesAsVector.
* The returned string should NOT be deleted.
*/
const char* GetInitLanguagesAsString() const;
/**
* Returns the loaded languages in the vector of STRINGs.
* Includes all languages loaded by the last Init, including those loaded
* as dependencies of other loaded languages.
*/
void GetLoadedLanguagesAsVector(GenericVector<STRING>* langs) const;
/**
* Returns the available languages in the vector of STRINGs.
*/
void GetAvailableLanguagesAsVector(GenericVector<STRING>* langs) const;
/**
* Init only the lang model component of Tesseract. The only functions
* that work after this init are SetVariable and IsValidWord.
* WARNING: temporary! This function will be removed from here and placed
* in a separate API at some future time.
*/
int InitLangMod(const char* datapath, const char* language);
/**
* Init only for page layout analysis. Use only for calls to SetImage and
* AnalysePage. Calls that attempt recognition will generate an error.
*/
void InitForAnalysePage();
/**
* Read a "config" file containing a set of param, value pairs.
* Searches the standard places: tessdata/configs, tessdata/tessconfigs
* and also accepts a relative or absolute path name.
* Note: only non-init params will be set (init params are set by Init()).
*/
void ReadConfigFile(const char* filename);
/** Same as above, but only set debug params from the given config file. */
void ReadDebugConfigFile(const char* filename);
/**
* Set the current page segmentation mode. Defaults to PSM_SINGLE_BLOCK.
* The mode is stored as an IntParam so it can also be modified by
* ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string).
*/
void SetPageSegMode(PageSegMode mode);
/** Return the current page segmentation mode. */
PageSegMode GetPageSegMode() const;
/**
* Recognize a rectangle from an image and return the result as a string.
* May be called many times for a single Init.
* Currently has no error checking.
* Greyscale of 8 and color of 24 or 32 bits per pixel may be given.
* Palette color images will not work properly and must be converted to
* 24 bit.
* Binary images of 1 bit per pixel may also be given but they must be
* byte packed with the MSB of the first byte being the first pixel, and a
* 1 represents WHITE. For binary images set bytes_per_pixel=0.
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
*
* Note that TesseractRect is the simplified convenience interface.
* For advanced uses, use SetImage, (optionally) SetRectangle, Recognize,
* and one or more of the Get*Text functions below.
*/
char* TesseractRect(const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
int left, int top, int width, int height);
/**
* Call between pages or documents etc to free up memory and forget
* adaptive data.
*/
void ClearAdaptiveClassifier();
/**
* @defgroup AdvancedAPI Advanced API
* The following methods break TesseractRect into pieces, so you can
* get hold of the thresholded image, get the text in different formats,
* get bounding boxes, confidences etc.
*/
/* @{ */
/**
* Provide an image for Tesseract to recognize. Format is as
* TesseractRect above. Does not copy the image buffer, or take
* ownership. The source image may be destroyed after Recognize is called,
* either explicitly or implicitly via one of the Get*Text functions.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*/
void SetImage(const unsigned char* imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line);
/**
* Provide an image for Tesseract to recognize. As with SetImage above,
* Tesseract doesn't take a copy or ownership or pixDestroy the image, so
* it must persist until after Recognize.
* Pix vs raw, which to use?
* Use Pix where possible. A future version of Tesseract may choose to use Pix
* as its internal representation and discard IMAGE altogether.
* Because of that, an implementation that sources and targets Pix may end up
* with less copies than an implementation that does not.
*/
void SetImage(Pix* pix);
/**
* Set the resolution of the source image in pixels per inch so font size
* information can be calculated in results. Call this after SetImage().
*/
void SetSourceResolution(int ppi);
/**
* Restrict recognition to a sub-rectangle of the image. Call after SetImage.
* Each SetRectangle clears the recogntion results so multiple rectangles
* can be recognized with the same image.
*/
void SetRectangle(int left, int top, int width, int height);
/**
* In extreme cases only, usually with a subclass of Thresholder, it
* is possible to provide a different Thresholder. The Thresholder may
* be preloaded with an image, settings etc, or they may be set after.
* Note that Tesseract takes ownership of the Thresholder and will
* delete it when it it is replaced or the API is destructed.
*/
void SetThresholder(ImageThresholder* thresholder) {
if (thresholder_ != NULL)
delete thresholder_;
thresholder_ = thresholder;
ClearResults();
}
/**
* Get a copy of the internal thresholded image from Tesseract.
* Caller takes ownership of the Pix and must pixDestroy it.
* May be called any time after SetImage, or after TesseractRect.
*/
Pix* GetThresholdedImage();
/**
* Get the result of page layout analysis as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* GetRegions(Pixa** pixa);
/**
* Get the textlines as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If raw_image is true, then extract from the original image instead of the
* thresholded image and pad by raw_padding pixels.
* If blockids is not NULL, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
* If paraids is not NULL, the paragraph-id of each line within its block is
* also returned as an array of one element per line. delete [] after use.
*/
Boxa* GetTextlines(const bool raw_image, const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
/*
Helper method to extract from the thresholded image. (most common usage)
*/
Boxa* GetTextlines(Pixa** pixa, int** blockids) {
return GetTextlines(false, 0, pixa, blockids, NULL);
}
/**
* Get textlines and strips of image regions as a leptonica-style Boxa, Pixa
* pair, in reading order. Enables downstream handling of non-rectangular
* regions.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
*/
Boxa* GetStrips(Pixa** pixa, int** blockids);
/**
* Get the words as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* GetWords(Pixa** pixa);
/**
* Gets the individual connected (text) components (created
* after pages segmentation step, but before recognition)
* as a leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* Note: the caller is responsible for calling boxaDestroy()
* on the returned Boxa array and pixaDestroy() on cc array.
*/
Boxa* GetConnectedComponents(Pixa** cc);
/**
* Get the given level kind of components (block, textline, word etc.) as a
* leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each component is also returned
* as an array of one element per component. delete [] after use.
* If blockids is not NULL, the paragraph-id of each component with its block
* is also returned as an array of one element per component. delete [] after
* use.
* If raw_image is true, then portions of the original image are extracted
* instead of the thresholded image and padded with raw_padding.
* If text_only is true, then only text components are returned.
*/
Boxa* GetComponentImages(const PageIteratorLevel level,
const bool text_only, const bool raw_image,
const int raw_padding,
Pixa** pixa, int** blockids, int** paraids);
// Helper function to get binary images with no padding (most common usage).
Boxa* GetComponentImages(const PageIteratorLevel level,
const bool text_only,
Pixa** pixa, int** blockids) {
return GetComponentImages(level, text_only, false, 0, pixa, blockids, NULL);
}
/**
* Returns the scale factor of the thresholded image that would be returned by
* GetThresholdedImage() and the various GetX() methods that call
* GetComponentImages().
* Returns 0 if no thresholder has been set.
*/
int GetThresholdedImageScaleFactor() const;
/**
* Dump the internal binary image to a PGM file.
* @deprecated Use GetThresholdedImage and write the image using pixWrite
* instead if possible.
*/
void DumpPGM(const char* filename);
/**
* Runs page layout analysis in the mode set by SetPageSegMode.
* May optionally be called prior to Recognize to get access to just
* the page layout results. Returns an iterator to the results.
* If merge_similar_words is true, words are combined where suitable for use
* with a line recognizer. Use if you want to use AnalyseLayout to find the
* textlines, and then want to process textline fragments with an external
* line recognizer.
* Returns NULL on error or an empty page.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
PageIterator* AnalyseLayout() {
return AnalyseLayout(false);
}
PageIterator* AnalyseLayout(bool merge_similar_words);
/**
* Recognize the image from SetAndThresholdImage, generating Tesseract
* internal structures. Returns 0 on success.
* Optional. The Get*Text functions below will call Recognize if needed.
* After Recognize, the output is kept internally until the next SetImage.
*/
int Recognize(ETEXT_DESC* monitor);
/**
* Methods to retrieve information after SetAndThresholdImage(),
* Recognize() or TesseractRect(). (Recognize is called implicitly if needed.)
*/
/** Variant on Recognize used for testing chopper. */
int RecognizeForChopTest(ETEXT_DESC* monitor);
/**
* Turns images into symbolic text.
*
* filename can point to a single image, a multi-page TIFF,
* or a plain text list of image filenames.
*
* retry_config is useful for debugging. If not NULL, you can fall
* back to an alternate configuration if a page fails for some
* reason.
*
* timeout_millisec terminates processing if any single page
* takes too long. Set to 0 for unlimited time.
*
* renderer is responible for creating the output. For example,
* use the TessTextRenderer if you want plaintext output, or
* the TessPDFRender to produce searchable PDF.
*
* If tessedit_page_number is non-negative, will only process that
* single page. Works for multi-page tiff file, or filelist.
*
* Returns true if successful, false on error.
*/
bool ProcessPages(const char* filename,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer);
/**
* Turn a single image into symbolic text.
*
* The pix is the image processed. filename and page_index are
* metadata used by side-effect processes, such as reading a box
* file or formatting as hOCR.
*
* See ProcessPages for desciptions of other parameters.
*/
bool ProcessPage(Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer);
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
* Recognize. The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
ResultIterator* GetIterator();
/**
* Get a mutable iterator to the results of LayoutAnalysis and/or Recognize.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
MutableIterator* GetMutableIterator();
/**
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
*/
char* GetUTF8Text();
/**
* Make a HTML-formatted string with hOCR markup from the internal
* data structures.
* page_number is 0-based but will appear in the output as 1-based.
*/
char* GetHOCRText(int page_number);
/**
* The recognized text is returned as a char* which is coded in the same
* format as a box file used in training. Returned string must be freed with
* the delete [] operator.
* Constructs coordinates in the original image - not just the rectangle.
* page_number is a 0-based page index that will appear in the box file.
*/
char* GetBoxText(int page_number);
/**
* The recognized text is returned as a char* which is coded
* as UNLV format Latin-1 with specific reject and suspect codes
* and must be freed with the delete [] operator.
*/
char* GetUNLVText();
/** Returns the (average) confidence value between 0 and 100. */
int MeanTextConf();
/**
* Returns all word confidences (between 0 and 100) in an array, terminated
* by -1. The calling function must delete [] after use.
* The number of confidences should correspond to the number of space-
* delimited words in GetUTF8Text.
*/
int* AllWordConfidences();
/**
* Applies the given word to the adaptive classifier if possible.
* The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can
* tell the boundaries of the graphemes.
* Assumes that SetImage/SetRectangle have been used to set the image
* to the given word. The mode arg should be PSM_SINGLE_WORD or
* PSM_CIRCLE_WORD, as that will be used to control layout analysis.
* The currently set PageSegMode is preserved.
* Returns false if adaption was not possible for some reason.
*/
bool AdaptToWordStr(PageSegMode mode, const char* wordstr);
/**
* Free up recognition results and any stored image data, without actually
* freeing any recognition data that would be time-consuming to reload.
* Afterwards, you must call SetImage or TesseractRect before doing
* any Recognize or Get* operation.
*/
void Clear();
/**
* Close down tesseract and free up all memory. End() is equivalent to
* destructing and reconstructing your TessBaseAPI.
* Once End() has been used, none of the other API functions may be used
* other than Init and anything declared above it in the class definition.
*/
void End();
/**
* Clear any library-level memory caches.
* There are a variety of expensive-to-load constant data structures (mostly
* language dictionaries) that are cached globally -- surviving the Init()
* and End() of individual TessBaseAPI's. This function allows the clearing
* of these caches.
**/
static void ClearPersistentCache();
/**
* Check whether a word is valid according to Tesseract's language model
* @return 0 if the word is invalid, non-zero if valid.
* @warning temporary! This function will be removed from here and placed
* in a separate API at some future time.
*/
int IsValidWord(const char *word);
// Returns true if utf8_character is defined in the UniCharset.
bool IsValidCharacter(const char *utf8_character);
bool GetTextDirection(int* out_offset, float* out_slope);
/** Sets Dict::letter_is_okay_ function to point to the given function. */
void SetDictFunc(DictFunc f);
/** Sets Dict::probability_in_context_ function to point to the given
* function.
*/
void SetProbabilityInContextFunc(ProbabilityInContextFunc f);
/** Sets Wordrec::fill_lattice_ function to point to the given function. */
void SetFillLatticeFunc(FillLatticeFunc f);
/**
* Estimates the Orientation And Script of the image.
* @return true if the image was processed successfully.
*/
bool DetectOS(OSResults*);
/** This method returns the features associated with the input image. */
void GetFeaturesForBlob(TBLOB* blob, INT_FEATURE_STRUCT* int_features,
int* num_features, int* feature_outline_index);
/**
* This method returns the row to which a box of specified dimensions would
* belong. If no good match is found, it returns NULL.
*/
static ROW* FindRowForBox(BLOCK_LIST* blocks, int left, int top,
int right, int bottom);
/**
* Method to run adaptive classifier on a blob.
* It returns at max num_max_matches results.
*/
void RunAdaptiveClassifier(TBLOB* blob,
int num_max_matches,
int* unichar_ids,
float* ratings,
int* num_matches_returned);
/** This method returns the string form of the specified unichar. */
const char* GetUnichar(int unichar_id);
/** Return the pointer to the i-th dawg loaded into tesseract_ object. */
const Dawg *GetDawg(int i) const;
/** Return the number of dawgs loaded into tesseract_ object. */
int NumDawgs() const;
/** Returns a ROW object created from the input row specification. */
static ROW *MakeTessOCRRow(float baseline, float xheight,
float descender, float ascender);
/** Returns a TBLOB corresponding to the entire input image. */
static TBLOB *MakeTBLOB(Pix *pix);
/**
* This method baseline normalizes a TBLOB in-place. The input row is used
* for normalization. The denorm is an optional parameter in which the
* normalization-antidote is returned.
*/
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode);
Tesseract* const tesseract() const {
return tesseract_;
}
OcrEngineMode const oem() const {
return last_oem_requested_;
}
void InitTruthCallback(TruthCallback *cb) { truth_cb_ = cb; }
/** Return a pointer to underlying CubeRecoContext object if present. */
CubeRecoContext *GetCubeRecoContext() const;
void set_min_orientation_margin(double margin);
/**
* Return text orientation of each block as determined by an earlier run
* of layout analysis.
*/
void GetBlockTextOrientations(int** block_orientation,
bool** vertical_writing);
/** Find lines from the image making the BLOCK_LIST. */
BLOCK_LIST* FindLinesCreateBlockList();
/**
* Delete a block list.
* This is to keep BLOCK_LIST pointer opaque
* and let go of including the other headers.
*/
static void DeleteBlockList(BLOCK_LIST* block_list);
/* @} */
protected:
/** Common code for setting the image. Returns true if Init has been called. */
TESS_LOCAL bool InternalSetImage();
/**
* Run the thresholder to make the thresholded image. If pix is not NULL,
* the source is thresholded to pix instead of the internal IMAGE.
*/
TESS_LOCAL virtual void Threshold(Pix** pix);
/**
* Find lines from the image making the BLOCK_LIST.
* @return 0 on success.
*/
TESS_LOCAL int FindLines();
/** Delete the pageres and block list ready for a new page. */
void ClearResults();
/**
* Return an LTR Result Iterator -- used only for training, as we really want
* to ignore all BiDi smarts at that point.
* delete once you're done with it.
*/
TESS_LOCAL LTRResultIterator* GetLTRIterator();
/**
* Return the length of the output text string, as UTF8, assuming
* one newline per line and one per block, with a terminator,
* and assuming a single character reject marker for each rejected character.
* Also return the number of recognized blobs in blob_count.
*/
TESS_LOCAL int TextLength(int* blob_count);
/** @defgroup ocropusAddOns ocropus add-ons */
/* @{ */
/**
* Adapt to recognize the current image as the given character.
* The image must be preloaded and be just an image of a single character.
*/
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr,
int length,
float baseline,
float xheight,
float descender,
float ascender);
/** Recognize text doing one pass only, using settings for a given pass. */
TESS_LOCAL PAGE_RES* RecognitionPass1(BLOCK_LIST* block_list);
TESS_LOCAL PAGE_RES* RecognitionPass2(BLOCK_LIST* block_list,
PAGE_RES* pass1_result);
//// paragraphs.cpp ////////////////////////////////////////////////////
TESS_LOCAL void DetectParagraphs(bool after_text_recognition);
/**
* Extract the OCR results, costs (penalty points for uncertainty),
* and the bounding boxes of the characters.
*/
TESS_LOCAL static int TesseractExtractResult(char** text,
int** lengths,
float** costs,
int** x0,
int** y0,
int** x1,
int** y1,
PAGE_RES* page_res);
TESS_LOCAL const PAGE_RES* GetPageRes() const {
return page_res_;
};
/* @} */
protected:
Tesseract* tesseract_; ///< The underlying data object.
Tesseract* osd_tesseract_; ///< For orientation & script detection.
EquationDetect* equ_detect_; ///<The equation detector.
ImageThresholder* thresholder_; ///< Image thresholding module.
GenericVector<ParagraphModel *>* paragraph_models_;
BLOCK_LIST* block_list_; ///< The page layout.
PAGE_RES* page_res_; ///< The page-level data.
STRING* input_file_; ///< Name used by training code.
Pix* input_image_; ///< Image used for searchable PDF
STRING* output_file_; ///< Name used by debug code.
STRING* datapath_; ///< Current location of tessdata.
STRING* language_; ///< Last initialized language.
OcrEngineMode last_oem_requested_; ///< Last ocr language mode requested.
bool recognition_done_; ///< page_res_ contains recognition data.
TruthCallback *truth_cb_; /// fxn for setting truth_* in WERD_RES
/**
* @defgroup ThresholderParams Thresholder Parameters
* Parameters saved from the Thresholder. Needed to rebuild coordinates.
*/
/* @{ */
int rect_left_;
int rect_top_;
int rect_width_;
int rect_height_;
int image_width_;
int image_height_;
/* @} */
private:
// A list of image filenames gets special consideration
bool ProcessPagesFileList(FILE *fp,
STRING *buf,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number);
// TIFF supports multipage so gets special consideration
bool ProcessPagesMultipageTiff(const unsigned char *data,
size_t size,
const char* filename,
const char* retry_config,
int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number);
}; // class TessBaseAPI.
/** Escape a char string - remove &<>"' with HTML codes. */
STRING HOcrEscape(const char* text);
} // namespace tesseract.
#endif // TESSERACT_API_BASEAPI_H__
| C++ |
#ifndef TESS_CAPI_INCLUDE_BASEAPI
# define TESS_CAPI_INCLUDE_BASEAPI
#endif
#include "capi.h"
#include "genericvector.h"
#include "strngs.h"
TESS_API const char* TESS_CALL TessVersion()
{
return TessBaseAPI::Version();
}
TESS_API void TESS_CALL TessDeleteText(char* text)
{
delete [] text;
}
TESS_API void TESS_CALL TessDeleteTextArray(char** arr)
{
for (char** pos = arr; *pos != NULL; ++pos)
delete [] *pos;
delete [] arr;
}
TESS_API void TESS_CALL TessDeleteIntArray(int* arr)
{
delete [] arr;
}
TESS_API void TESS_CALL TessDeleteBlockList(BLOCK_LIST* block_list)
{
TessBaseAPI::DeleteBlockList(block_list);
}
TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase)
{
return new TessTextRenderer(outputbase);
}
TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate(const char* outputbase)
{
return new TessHOcrRenderer(outputbase);
}
TESS_API TessResultRenderer* TESS_CALL TessHOcrRendererCreate2(const char* outputbase, BOOL font_info)
{
return new TessHOcrRenderer(outputbase, font_info);
}
TESS_API TessResultRenderer* TESS_CALL TessPDFRendererCreate(const char* outputbase, const char* datadir)
{
return new TessPDFRenderer(outputbase, datadir);
}
TESS_API TessResultRenderer* TESS_CALL TessUnlvRendererCreate(const char* outputbase)
{
return new TessUnlvRenderer(outputbase);
}
TESS_API TessResultRenderer* TESS_CALL TessBoxTextRendererCreate(const char* outputbase)
{
return new TessBoxTextRenderer(outputbase);
}
TESS_API void TESS_CALL TessDeleteResultRenderer(TessResultRenderer* renderer)
{
delete [] renderer;
}
TESS_API void TESS_CALL TessResultRendererInsert(TessResultRenderer* renderer, TessResultRenderer* next)
{
renderer->insert(next);
}
TESS_API TessResultRenderer* TESS_CALL TessResultRendererNext(TessResultRenderer* renderer)
{
return renderer->next();
}
TESS_API BOOL TESS_CALL TessResultRendererBeginDocument(TessResultRenderer* renderer, const char* title)
{
return renderer->BeginDocument(title);
}
TESS_API BOOL TESS_CALL TessResultRendererAddImage(TessResultRenderer* renderer, TessBaseAPI* api)
{
return renderer->AddImage(api);
}
TESS_API BOOL TESS_CALL TessResultRendererEndDocument(TessResultRenderer* renderer)
{
return renderer->EndDocument();
}
TESS_API const char* TESS_CALL TessResultRendererExtention(TessResultRenderer* renderer)
{
return renderer->file_extension();
}
TESS_API const char* TESS_CALL TessResultRendererTitle(TessResultRenderer* renderer)
{
return renderer->title();
}
TESS_API int TESS_CALL TessResultRendererImageNum(TessResultRenderer* renderer)
{
return renderer->imagenum();
}
TESS_API TessBaseAPI* TESS_CALL TessBaseAPICreate()
{
return new TessBaseAPI;
}
TESS_API void TESS_CALL TessBaseAPIDelete(TessBaseAPI* handle)
{
delete handle;
}
TESS_API size_t TESS_CALL TessBaseAPIGetOpenCLDevice(TessBaseAPI* handle, void **device)
{
return handle->getOpenCLDevice(device);
}
TESS_API void TESS_CALL TessBaseAPISetInputName(TessBaseAPI* handle, const char* name)
{
handle->SetInputName(name);
}
TESS_API const char* TESS_CALL TessBaseAPIGetInputName(TessBaseAPI* handle)
{
return handle->GetInputName();
}
TESS_API void TESS_CALL TessBaseAPISetInputImage(TessBaseAPI* handle, Pix* pix)
{
handle->SetInputImage(pix);
}
TESS_API Pix* TESS_CALL TessBaseAPIGetInputImage(TessBaseAPI* handle)
{
return handle->GetInputImage();
}
TESS_API int TESS_CALL TessBaseAPIGetSourceYResolution(TessBaseAPI* handle)
{
return handle->GetSourceYResolution();
}
TESS_API const char* TESS_CALL TessBaseAPIGetDatapath(TessBaseAPI* handle)
{
return handle->GetDatapath();
}
TESS_API void TESS_CALL TessBaseAPISetOutputName(TessBaseAPI* handle, const char* name)
{
handle->SetOutputName(name);
}
TESS_API BOOL TESS_CALL TessBaseAPISetVariable(TessBaseAPI* handle, const char* name, const char* value)
{
return handle->SetVariable(name, value) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessBaseAPISetDebugVariable(TessBaseAPI* handle, const char* name, const char* value)
{
return handle->SetVariable(name, value) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessBaseAPIGetIntVariable(const TessBaseAPI* handle, const char* name, int* value)
{
return handle->GetIntVariable(name, value) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessBaseAPIGetBoolVariable(const TessBaseAPI* handle, const char* name, BOOL* value)
{
bool boolValue;
if (handle->GetBoolVariable(name, &boolValue))
{
*value = boolValue ? TRUE : FALSE;
return TRUE;
}
else
{
return FALSE;
}
}
TESS_API BOOL TESS_CALL TessBaseAPIGetDoubleVariable(const TessBaseAPI* handle, const char* name, double* value)
{
return handle->GetDoubleVariable(name, value) ? TRUE : FALSE;
}
TESS_API const char* TESS_CALL TessBaseAPIGetStringVariable(const TessBaseAPI* handle, const char* name)
{
return handle->GetStringVariable(name);
}
TESS_API void TESS_CALL TessBaseAPIPrintVariables(const TessBaseAPI* handle, FILE* fp)
{
handle->PrintVariables(fp);
}
TESS_API BOOL TESS_CALL TessBaseAPIPrintVariablesToFile(const TessBaseAPI* handle, const char* filename)
{
FILE* fp = fopen(filename, "w");
if (fp != NULL)
{
handle->PrintVariables(fp);
fclose(fp);
return TRUE;
}
return FALSE;
}
TESS_API BOOL TESS_CALL TessBaseAPIGetVariableAsString(TessBaseAPI* handle, const char* name, STRING* val)
{
return handle->GetVariableAsString(name, val) ? TRUE : FALSE;
}
TESS_API int TESS_CALL TessBaseAPIInit4(TessBaseAPI* handle, const char* datapath, const char* language,
TessOcrEngineMode mode, char** configs, int configs_size,
char** vars_vec, char** vars_values, size_t vars_vec_size,
BOOL set_only_non_debug_params)
{
GenericVector<STRING> varNames;
GenericVector<STRING> varValues;
if (vars_vec != NULL && vars_values != NULL) {
for (size_t i = 0; i < vars_vec_size; i++) {
varNames.push_back(STRING(vars_vec[i]));
varValues.push_back(STRING(vars_values[i]));
}
}
return handle->Init(datapath, language, mode, configs, configs_size, &varNames, &varValues, set_only_non_debug_params);
}
TESS_API int TESS_CALL TessBaseAPIInit1(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem,
char** configs, int configs_size)
{
return handle->Init(datapath, language, oem, configs, configs_size, NULL, NULL, false);
}
TESS_API int TESS_CALL TessBaseAPIInit2(TessBaseAPI* handle, const char* datapath, const char* language, TessOcrEngineMode oem)
{
return handle->Init(datapath, language, oem);
}
TESS_API int TESS_CALL TessBaseAPIInit3(TessBaseAPI* handle, const char* datapath, const char* language)
{
return handle->Init(datapath, language);
}
TESS_API const char* TESS_CALL TessBaseAPIGetInitLanguagesAsString(const TessBaseAPI* handle)
{
return handle->GetInitLanguagesAsString();
}
TESS_API char** TESS_CALL TessBaseAPIGetLoadedLanguagesAsVector(const TessBaseAPI* handle)
{
GenericVector<STRING> languages;
handle->GetLoadedLanguagesAsVector(&languages);
char** arr = new char*[languages.size() + 1];
for (int index = 0; index < languages.size(); ++index)
arr[index] = languages[index].strdup();
arr[languages.size()] = NULL;
return arr;
}
TESS_API char** TESS_CALL TessBaseAPIGetAvailableLanguagesAsVector(const TessBaseAPI* handle)
{
GenericVector<STRING> languages;
handle->GetAvailableLanguagesAsVector(&languages);
char** arr = new char*[languages.size() + 1];
for (int index = 0; index < languages.size(); ++index)
arr[index] = languages[index].strdup();
arr[languages.size()] = NULL;
return arr;
}
TESS_API int TESS_CALL TessBaseAPIInitLangMod(TessBaseAPI* handle, const char* datapath, const char* language)
{
return handle->InitLangMod(datapath, language);
}
TESS_API void TESS_CALL TessBaseAPIInitForAnalysePage(TessBaseAPI* handle)
{
handle->InitForAnalysePage();
}
TESS_API void TESS_CALL TessBaseAPIReadConfigFile(TessBaseAPI* handle, const char* filename)
{
handle->ReadConfigFile(filename);
}
TESS_API void TESS_CALL TessBaseAPIReadDebugConfigFile(TessBaseAPI* handle, const char* filename)
{
handle->ReadDebugConfigFile(filename);
}
TESS_API void TESS_CALL TessBaseAPISetPageSegMode(TessBaseAPI* handle, TessPageSegMode mode)
{
handle->SetPageSegMode(mode);
}
TESS_API TessPageSegMode TESS_CALL TessBaseAPIGetPageSegMode(const TessBaseAPI* handle)
{
return handle->GetPageSegMode();
}
TESS_API char* TESS_CALL TessBaseAPIRect(TessBaseAPI* handle, const unsigned char* imagedata,
int bytes_per_pixel, int bytes_per_line,
int left, int top, int width, int height)
{
return handle->TesseractRect(imagedata, bytes_per_pixel, bytes_per_line, left, top, width, height);
}
TESS_API void TESS_CALL TessBaseAPIClearAdaptiveClassifier(TessBaseAPI* handle)
{
handle->ClearAdaptiveClassifier();
}
TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line)
{
handle->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line);
}
TESS_API void TESS_CALL TessBaseAPISetImage2(TessBaseAPI* handle, struct Pix* pix)
{
return handle->SetImage(pix);
}
TESS_API void TESS_CALL TessBaseAPISetSourceResolution(TessBaseAPI* handle, int ppi)
{
handle->SetSourceResolution(ppi);
}
TESS_API void TESS_CALL TessBaseAPISetRectangle(TessBaseAPI* handle, int left, int top, int width, int height)
{
handle->SetRectangle(left, top, width, height);
}
TESS_API void TESS_CALL TessBaseAPISetThresholder(TessBaseAPI* handle, TessImageThresholder* thresholder)
{
handle->SetThresholder(thresholder);
}
TESS_API struct Pix* TESS_CALL TessBaseAPIGetThresholdedImage(TessBaseAPI* handle)
{
return handle->GetThresholdedImage();
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetRegions(TessBaseAPI* handle, struct Pixa** pixa)
{
return handle->GetRegions(pixa);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines(TessBaseAPI* handle, struct Pixa** pixa, int** blockids)
{
return handle->GetTextlines(pixa, blockids);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetTextlines1(TessBaseAPI* handle, const BOOL raw_image, const int raw_padding,
struct Pixa** pixa, int** blockids, int** paraids)
{
return handle->GetTextlines(raw_image, raw_padding, pixa, blockids, paraids);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetStrips(TessBaseAPI* handle, struct Pixa** pixa, int** blockids)
{
return handle->GetStrips(pixa, blockids);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetWords(TessBaseAPI* handle, struct Pixa** pixa)
{
return handle->GetWords(pixa);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetConnectedComponents(TessBaseAPI* handle, struct Pixa** cc)
{
return handle->GetConnectedComponents(cc);
}
TESS_API struct Boxa* TESS_CALL TessBaseAPIGetComponentImages(TessBaseAPI* handle, TessPageIteratorLevel level, BOOL text_only, struct Pixa** pixa, int** blockids)
{
return handle->GetComponentImages(level, text_only != FALSE, pixa, blockids);
}
TESS_API struct Boxa*
TESS_CALL TessBaseAPIGetComponentImages1( TessBaseAPI* handle, const TessPageIteratorLevel level, const BOOL text_only,
const BOOL raw_image, const int raw_padding,
struct Pixa** pixa, int** blockids, int** paraids)
{
return handle->GetComponentImages(level, text_only != FALSE, raw_image, raw_padding, pixa, blockids, paraids);
}
TESS_API int TESS_CALL TessBaseAPIGetThresholdedImageScaleFactor(const TessBaseAPI* handle)
{
return handle->GetThresholdedImageScaleFactor();
}
TESS_API void TESS_CALL TessBaseAPIDumpPGM(TessBaseAPI* handle, const char* filename)
{
handle->DumpPGM(filename);
}
TESS_API TessPageIterator* TESS_CALL TessBaseAPIAnalyseLayout(TessBaseAPI* handle)
{
return handle->AnalyseLayout();
}
TESS_API int TESS_CALL TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor)
{
return handle->Recognize(monitor);
}
TESS_API int TESS_CALL TessBaseAPIRecognizeForChopTest(TessBaseAPI* handle, ETEXT_DESC* monitor)
{
return handle->RecognizeForChopTest(monitor);
}
TESS_API BOOL TESS_CALL TessBaseAPIProcessPages(TessBaseAPI* handle, const char* filename, const char* retry_config,
int timeout_millisec, TessResultRenderer* renderer)
{
if (handle->ProcessPages(filename, retry_config, timeout_millisec, renderer))
return TRUE;
else
return FALSE;
}
TESS_API BOOL TESS_CALL TessBaseAPIProcessPage(TessBaseAPI* handle, struct Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec, TessResultRenderer* renderer)
{
if (handle->ProcessPage(pix, page_index, filename, retry_config, timeout_millisec, renderer))
return TRUE;
else
return FALSE;
}
TESS_API TessResultIterator* TESS_CALL TessBaseAPIGetIterator(TessBaseAPI* handle)
{
return handle->GetIterator();
}
TESS_API TessMutableIterator* TESS_CALL TessBaseAPIGetMutableIterator(TessBaseAPI* handle)
{
return handle->GetMutableIterator();
}
TESS_API char* TESS_CALL TessBaseAPIGetUTF8Text(TessBaseAPI* handle)
{
return handle->GetUTF8Text();
}
TESS_API char* TESS_CALL TessBaseAPIGetHOCRText(TessBaseAPI* handle, int page_number)
{
return handle->GetHOCRText(page_number);
}
TESS_API char* TESS_CALL TessBaseAPIGetBoxText(TessBaseAPI* handle, int page_number)
{
return handle->GetBoxText(page_number);
}
TESS_API char* TESS_CALL TessBaseAPIGetUNLVText(TessBaseAPI* handle)
{
return handle->GetUNLVText();
}
TESS_API int TESS_CALL TessBaseAPIMeanTextConf(TessBaseAPI* handle)
{
return handle->MeanTextConf();
}
TESS_API int* TESS_CALL TessBaseAPIAllWordConfidences(TessBaseAPI* handle)
{
return handle->AllWordConfidences();
}
TESS_API BOOL TESS_CALL TessBaseAPIAdaptToWordStr(TessBaseAPI* handle, TessPageSegMode mode, const char* wordstr)
{
return handle->AdaptToWordStr(mode, wordstr) ? TRUE : FALSE;
}
TESS_API void TESS_CALL TessBaseAPIClear(TessBaseAPI* handle)
{
handle->Clear();
}
TESS_API void TESS_CALL TessBaseAPIEnd(TessBaseAPI* handle)
{
handle->End();
}
TESS_API int TESS_CALL TessBaseAPIIsValidWord(TessBaseAPI* handle, const char* word)
{
return handle->IsValidWord(word);
}
TESS_API BOOL TESS_CALL TessBaseAPIGetTextDirection(TessBaseAPI* handle, int* out_offset, float* out_slope)
{
return handle->GetTextDirection(out_offset, out_slope) ? TRUE : FALSE;
}
TESS_API void TESS_CALL TessBaseAPISetDictFunc(TessBaseAPI* handle, TessDictFunc f)
{
handle->SetDictFunc(f);
}
TESS_API void TESS_CALL TessBaseAPIClearPersistentCache(TessBaseAPI* handle)
{
handle->ClearPersistentCache();
}
TESS_API void TESS_CALL TessBaseAPISetProbabilityInContextFunc(TessBaseAPI* handle, TessProbabilityInContextFunc f)
{
handle->SetProbabilityInContextFunc(f);
}
TESS_API BOOL TESS_CALL TessBaseAPIDetectOS(TessBaseAPI* handle, OSResults* results)
{
return handle->DetectOS(results) ? TRUE : FALSE;
}
TESS_API void TESS_CALL TessBaseAPIGetFeaturesForBlob(TessBaseAPI* handle, TBLOB* blob, INT_FEATURE_STRUCT* int_features,
int* num_features, int* FeatureOutlineIndex)
{
handle->GetFeaturesForBlob(blob, int_features, num_features, FeatureOutlineIndex);
}
TESS_API ROW* TESS_CALL TessFindRowForBox(BLOCK_LIST* blocks, int left, int top, int right, int bottom)
{
return TessBaseAPI::FindRowForBox(blocks, left, top, right, bottom);
}
TESS_API void TESS_CALL TessBaseAPIRunAdaptiveClassifier(TessBaseAPI* handle, TBLOB* blob, int num_max_matches,
int* unichar_ids, float* ratings, int* num_matches_returned)
{
handle->RunAdaptiveClassifier(blob, num_max_matches, unichar_ids, ratings, num_matches_returned);
}
TESS_API const char* TESS_CALL TessBaseAPIGetUnichar(TessBaseAPI* handle, int unichar_id)
{
return handle->GetUnichar(unichar_id);
}
TESS_API const TessDawg* TESS_CALL TessBaseAPIGetDawg(const TessBaseAPI* handle, int i)
{
return handle->GetDawg(i);
}
TESS_API int TESS_CALL TessBaseAPINumDawgs(const TessBaseAPI* handle)
{
return handle->NumDawgs();
}
TESS_API ROW* TESS_CALL TessMakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
{
return TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender);
}
TESS_API TBLOB* TESS_CALL TessMakeTBLOB(struct Pix* pix)
{
return TessBaseAPI::MakeTBLOB(pix);
}
TESS_API void TESS_CALL TessNormalizeTBLOB(TBLOB* tblob, ROW* row, BOOL numeric_mode)
{
TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode != FALSE);
}
TESS_API TessOcrEngineMode TESS_CALL TessBaseAPIOem(const TessBaseAPI* handle)
{
return handle->oem();
}
TESS_API void TESS_CALL TessBaseAPIInitTruthCallback(TessBaseAPI* handle, TessTruthCallback* cb)
{
handle->InitTruthCallback(cb);
}
TESS_API TessCubeRecoContext* TESS_CALL TessBaseAPIGetCubeRecoContext(const TessBaseAPI* handle)
{
return handle->GetCubeRecoContext();
}
TESS_API void TESS_CALL TessBaseAPISetMinOrientationMargin(TessBaseAPI* handle, double margin)
{
handle->set_min_orientation_margin(margin);
}
TESS_API void TESS_CALL TessBaseGetBlockTextOrientations(TessBaseAPI* handle, int** block_orientation, bool** vertical_writing)
{
handle->GetBlockTextOrientations(block_orientation, vertical_writing);
}
TESS_API BLOCK_LIST* TESS_CALL TessBaseAPIFindLinesCreateBlockList(TessBaseAPI* handle)
{
return handle->FindLinesCreateBlockList();
}
TESS_API void TESS_CALL TessPageIteratorDelete(TessPageIterator* handle)
{
delete handle;
}
TESS_API TessPageIterator* TESS_CALL TessPageIteratorCopy(const TessPageIterator* handle)
{
return new TessPageIterator(*handle);
}
TESS_API void TESS_CALL TessPageIteratorBegin(TessPageIterator* handle)
{
handle->Begin();
}
TESS_API BOOL TESS_CALL TessPageIteratorNext(TessPageIterator* handle, TessPageIteratorLevel level)
{
return handle->Next(level) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessPageIteratorIsAtBeginningOf(const TessPageIterator* handle, TessPageIteratorLevel level)
{
return handle->IsAtBeginningOf(level) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessPageIteratorIsAtFinalElement(const TessPageIterator* handle, TessPageIteratorLevel level,
TessPageIteratorLevel element)
{
return handle->IsAtFinalElement(level, element) ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessPageIteratorBoundingBox(const TessPageIterator* handle, TessPageIteratorLevel level,
int* left, int* top, int* right, int* bottom)
{
return handle->BoundingBox(level, left, top, right, bottom) ? TRUE : FALSE;
}
TESS_API TessPolyBlockType TESS_CALL TessPageIteratorBlockType(const TessPageIterator* handle)
{
return handle->BlockType();
}
TESS_API struct Pix* TESS_CALL TessPageIteratorGetBinaryImage(const TessPageIterator* handle, TessPageIteratorLevel level)
{
return handle->GetBinaryImage(level);
}
TESS_API struct Pix* TESS_CALL TessPageIteratorGetImage(const TessPageIterator* handle, TessPageIteratorLevel level, int padding,
struct Pix* original_image, int* left, int* top)
{
return handle->GetImage(level, padding, original_image, left, top);
}
TESS_API BOOL TESS_CALL TessPageIteratorBaseline(const TessPageIterator* handle, TessPageIteratorLevel level,
int* x1, int* y1, int* x2, int* y2)
{
return handle->Baseline(level, x1, y1, x2, y2) ? TRUE : FALSE;
}
TESS_API void TESS_CALL TessPageIteratorOrientation(TessPageIterator* handle, TessOrientation* orientation,
TessWritingDirection* writing_direction, TessTextlineOrder* textline_order,
float* deskew_angle)
{
handle->Orientation(orientation, writing_direction, textline_order, deskew_angle);
}
TESS_API void TESS_CALL TessResultIteratorDelete(TessResultIterator* handle)
{
delete handle;
}
TESS_API TessResultIterator* TESS_CALL TessResultIteratorCopy(const TessResultIterator* handle)
{
return new TessResultIterator(*handle);
}
TESS_API TessPageIterator* TESS_CALL TessResultIteratorGetPageIterator(TessResultIterator* handle)
{
return handle;
}
TESS_API const TessPageIterator* TESS_CALL TessResultIteratorGetPageIteratorConst(const TessResultIterator* handle)
{
return handle;
}
TESS_API const TessChoiceIterator* TESS_CALL TessResultIteratorGetChoiceIterator(const TessResultIterator* handle)
{
return new TessChoiceIterator(*handle);
}
TESS_API BOOL TESS_CALL TessResultIteratorNext(TessResultIterator* handle, TessPageIteratorLevel level)
{
return handle->Next(level);
}
TESS_API char* TESS_CALL TessResultIteratorGetUTF8Text(const TessResultIterator* handle, TessPageIteratorLevel level)
{
return handle->GetUTF8Text(level);
}
TESS_API float TESS_CALL TessResultIteratorConfidence(const TessResultIterator* handle, TessPageIteratorLevel level)
{
return handle->Confidence(level);
}
TESS_API const char* TESS_CALL TessResultIteratorWordRecognitionLanguage(const TessResultIterator* handle)
{
return handle->WordRecognitionLanguage();
}
TESS_API const char* TESS_CALL TessResultIteratorWordFontAttributes(const TessResultIterator* handle, BOOL* is_bold, BOOL* is_italic,
BOOL* is_underlined, BOOL* is_monospace, BOOL* is_serif,
BOOL* is_smallcaps, int* pointsize, int* font_id)
{
bool bool_is_bold, bool_is_italic, bool_is_underlined, bool_is_monospace, bool_is_serif, bool_is_smallcaps;
const char* ret = handle->WordFontAttributes(&bool_is_bold, &bool_is_italic, &bool_is_underlined, &bool_is_monospace, &bool_is_serif,
&bool_is_smallcaps, pointsize, font_id);
if (is_bold)
*is_bold = bool_is_bold ? TRUE : FALSE;
if (is_italic)
*is_italic = bool_is_italic ? TRUE : FALSE;
if (is_underlined)
*is_underlined = bool_is_underlined ? TRUE : FALSE;
if (is_monospace)
*is_monospace = bool_is_monospace ? TRUE : FALSE;
if (is_serif)
*is_serif = bool_is_serif ? TRUE : FALSE;
if (is_smallcaps)
*is_smallcaps = bool_is_smallcaps ? TRUE : FALSE;
return ret;
}
TESS_API BOOL TESS_CALL TessResultIteratorWordIsFromDictionary(const TessResultIterator* handle)
{
return handle->WordIsFromDictionary() ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessResultIteratorWordIsNumeric(const TessResultIterator* handle)
{
return handle->WordIsNumeric() ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSuperscript(const TessResultIterator* handle)
{
return handle->SymbolIsSuperscript() ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsSubscript(const TessResultIterator* handle)
{
return handle->SymbolIsSubscript() ? TRUE : FALSE;
}
TESS_API BOOL TESS_CALL TessResultIteratorSymbolIsDropcap(const TessResultIterator* handle)
{
return handle->SymbolIsDropcap() ? TRUE : FALSE;
}
TESS_API void TESS_CALL TessChoiceIteratorDelete(TessChoiceIterator* handle)
{
delete handle;
}
TESS_API BOOL TESS_CALL TessChoiceIteratorNext(TessChoiceIterator* handle)
{
return handle->Next();
}
TESS_API const char* TESS_CALL TessChoiceIteratorGetUTF8Text(const TessChoiceIterator* handle)
{
return handle->GetUTF8Text();
}
TESS_API float TESS_CALL TessChoiceIteratorConfidence(const TessChoiceIterator* handle)
{
return handle->Confidence();
}
| C++ |
/**********************************************************************
* File: tessedit.cpp (Formerly tessedit.c)
* Description: Main program for merge of tess and editor.
* Author: Ray Smith
* Created: Tue Jan 07 15:21:46 GMT 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include <iostream>
#include "allheaders.h"
#include "baseapi.h"
#include "basedir.h"
#include "renderer.h"
#include "strngs.h"
#include "tprintf.h"
#include "openclwrapper.h"
#include "osdetect.h"
/**********************************************************************
* main()
*
**********************************************************************/
int main(int argc, char **argv) {
if ((argc == 2 && strcmp(argv[1], "-v") == 0) ||
(argc == 2 && strcmp(argv[1], "--version") == 0)) {
char *versionStrP;
fprintf(stderr, "tesseract %s\n", tesseract::TessBaseAPI::Version());
versionStrP = getLeptonicaVersion();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
versionStrP = getImagelibVersions();
fprintf(stderr, " %s\n", versionStrP);
lept_free(versionStrP);
#ifdef USE_OPENCL
cl_platform_id platform;
cl_uint num_platforms;
cl_device_id devices[2];
cl_uint num_devices;
char info[256];
int i;
fprintf(stderr, " OpenCL info:\n");
clGetPlatformIDs(1, &platform, &num_platforms);
fprintf(stderr, " Found %d platforms.\n", num_platforms);
clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, info, 0);
fprintf(stderr, " Platform name: %s.\n", info);
clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 256, info, 0);
fprintf(stderr, " Version: %s.\n", info);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 2, devices, &num_devices);
fprintf(stderr, " Found %d devices.\n", num_devices);
for (i = 0; i < num_devices; ++i) {
clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 256, info, 0);
fprintf(stderr, " Device %d name: %s.\n", i+1, info);
}
#endif
exit(0);
}
// Make the order of args a bit more forgiving than it used to be.
const char* lang = "eng";
const char* image = NULL;
const char* outputbase = NULL;
const char* datapath = NULL;
bool noocr = false;
bool list_langs = false;
bool print_parameters = false;
GenericVector<STRING> vars_vec, vars_values;
tesseract::PageSegMode pagesegmode = tesseract::PSM_AUTO;
int arg = 1;
while (arg < argc && (outputbase == NULL || argv[arg][0] == '-')) {
if (strcmp(argv[arg], "-l") == 0 && arg + 1 < argc) {
lang = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--tessdata-dir") == 0 && arg + 1 < argc) {
datapath = argv[arg + 1];
++arg;
} else if (strcmp(argv[arg], "--user-words") == 0 && arg + 1 < argc) {
vars_vec.push_back("user_words_file");
vars_values.push_back(argv[arg + 1]);
++arg;
} else if (strcmp(argv[arg], "--user-patterns") == 0 && arg + 1 < argc) {
vars_vec.push_back("user_patterns_file");
vars_values.push_back(argv[arg + 1]);
++arg;
} else if (strcmp(argv[arg], "--list-langs") == 0) {
noocr = true;
list_langs = true;
} else if (strcmp(argv[arg], "-psm") == 0 && arg + 1 < argc) {
pagesegmode = static_cast<tesseract::PageSegMode>(atoi(argv[arg + 1]));
++arg;
} else if (strcmp(argv[arg], "--print-parameters") == 0) {
noocr = true;
print_parameters = true;
} else if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
// handled properly after api init
++arg;
} else if (image == NULL) {
image = argv[arg];
} else if (outputbase == NULL) {
outputbase = argv[arg];
}
++arg;
}
if (argc == 2 && strcmp(argv[1], "--list-langs") == 0) {
list_langs = true;
noocr = true;
}
if (outputbase == NULL && noocr == false) {
fprintf(stderr, "Usage:\n %s imagename|stdin outputbase|stdout "
"[options...] [configfile...]\n\n", argv[0]);
fprintf(stderr, "OCR options:\n");
fprintf(stderr, " --tessdata-dir /path\tspecify the location of tessdata"
" path\n");
fprintf(stderr, " --user-words /path/to/file\tspecify the location of user"
" words file\n");
fprintf(stderr, " --user-patterns /path/to/file\tspecify the location of"
" user patterns file\n");
fprintf(stderr, " -l lang[+lang]\tspecify language(s) used for OCR\n");
fprintf(stderr, " -c configvar=value\tset value for control parameter.\n"
"\t\t\tMultiple -c arguments are allowed.\n");
fprintf(stderr, " -psm pagesegmode\tspecify page segmentation mode.\n");
fprintf(stderr, "These options must occur before any configfile.\n\n");
fprintf(stderr,
"pagesegmode values are:\n"
" 0 = Orientation and script detection (OSD) only.\n"
" 1 = Automatic page segmentation with OSD.\n"
" 2 = Automatic page segmentation, but no OSD, or OCR\n"
" 3 = Fully automatic page segmentation, but no OSD. (Default)\n"
" 4 = Assume a single column of text of variable sizes.\n"
" 5 = Assume a single uniform block of vertically aligned text.\n"
" 6 = Assume a single uniform block of text.\n"
" 7 = Treat the image as a single text line.\n"
" 8 = Treat the image as a single word.\n"
" 9 = Treat the image as a single word in a circle.\n"
" 10 = Treat the image as a single character.\n\n");
fprintf(stderr, "Single options:\n");
fprintf(stderr, " -v --version: version info\n");
fprintf(stderr, " --list-langs: list available languages for tesseract "
"engine. Can be used with --tessdata-dir.\n");
fprintf(stderr, " --print-parameters: print tesseract parameters to the "
"stdout.\n");
exit(1);
}
if (outputbase != NULL && strcmp(outputbase, "-") &&
strcmp(outputbase, "stdout")) {
tprintf("Tesseract Open Source OCR Engine v%s with Leptonica\n",
tesseract::TessBaseAPI::Version());
}
PERF_COUNT_START("Tesseract:main")
tesseract::TessBaseAPI api;
api.SetOutputName(outputbase);
int rc = api.Init(datapath, lang, tesseract::OEM_DEFAULT,
&(argv[arg]), argc - arg, &vars_vec, &vars_values, false);
if (rc) {
fprintf(stderr, "Could not initialize tesseract.\n");
exit(1);
}
char opt1[255], opt2[255];
for (arg = 0; arg < argc; arg++) {
if (strcmp(argv[arg], "-c") == 0 && arg + 1 < argc) {
strncpy(opt1, argv[arg + 1], 255);
char *p = strchr(opt1, '=');
if (!p) {
fprintf(stderr, "Missing = in configvar assignment\n");
exit(1);
}
*p = 0;
strncpy(opt2, strchr(argv[arg + 1], '=') + 1, 255);
opt2[254] = 0;
++arg;
if (!api.SetVariable(opt1, opt2)) {
fprintf(stderr, "Could not set option: %s=%s\n", opt1, opt2);
}
}
}
if (list_langs) {
GenericVector<STRING> languages;
api.GetAvailableLanguagesAsVector(&languages);
fprintf(stderr, "List of available languages (%d):\n",
languages.size());
for (int index = 0; index < languages.size(); ++index) {
STRING& string = languages[index];
fprintf(stderr, "%s\n", string.string());
}
api.End();
exit(0);
}
if (print_parameters) {
FILE* fout = stdout;
fprintf(stdout, "Tesseract parameters:\n");
api.PrintVariables(fout);
api.End();
exit(0);
}
// We have 2 possible sources of pagesegmode: a config file and
// the command line. For backwards compatability reasons, the
// default in tesseract is tesseract::PSM_SINGLE_BLOCK, but the
// default for this program is tesseract::PSM_AUTO. We will let
// the config file take priority, so the command-line default
// can take priority over the tesseract default, so we use the
// value from the command line only if the retrieved mode
// is still tesseract::PSM_SINGLE_BLOCK, indicating no change
// in any config file. Therefore the only way to force
// tesseract::PSM_SINGLE_BLOCK is from the command line.
// It would be simpler if we could set the value before Init,
// but that doesn't work.
if (api.GetPageSegMode() == tesseract::PSM_SINGLE_BLOCK)
api.SetPageSegMode(pagesegmode);
if (pagesegmode == tesseract::PSM_AUTO_ONLY ||
pagesegmode == tesseract::PSM_OSD_ONLY) {
int ret_val = 0;
Pix* pixs = pixRead(image);
if (!pixs) {
fprintf(stderr, "Cannot open input file: %s\n", image);
exit(2);
}
api.SetImage(pixs);
if (pagesegmode == tesseract::PSM_OSD_ONLY) {
OSResults osr;
if (api.DetectOS(&osr)) {
int orient = osr.best_result.orientation_id;
int script_id = osr.get_best_script(orient);
float orient_oco = osr.best_result.oconfidence;
float orient_sco = osr.best_result.sconfidence;
tprintf("Orientation: %d\nOrientation in degrees: %d\n" \
"Orientation confidence: %.2f\n" \
"Script: %d\nScript confidence: %.2f\n",
orient, OrientationIdToValue(orient), orient_oco,
script_id, orient_sco);
} else {
ret_val = 1;
}
} else {
tesseract::Orientation orientation;
tesseract::WritingDirection direction;
tesseract::TextlineOrder order;
float deskew_angle;
tesseract::PageIterator* it = api.AnalyseLayout();
if (it) {
it->Orientation(&orientation, &direction, &order, &deskew_angle);
tprintf("Orientation: %d\nWritingDirection: %d\nTextlineOrder: %d\n" \
"Deskew angle: %.4f\n",
orientation, direction, order, deskew_angle);
} else {
ret_val = 1;
}
delete it;
}
pixDestroy(&pixs);
exit(ret_val);
}
bool b;
tesseract::PointerVector<tesseract::TessResultRenderer> renderers;
api.GetBoolVariable("tessedit_create_hocr", &b);
if (b) {
bool font_info;
api.GetBoolVariable("hocr_font_info", &font_info);
renderers.push_back(new tesseract::TessHOcrRenderer(outputbase, font_info));
}
api.GetBoolVariable("tessedit_create_pdf", &b);
if (b) {
renderers.push_back(new tesseract::TessPDFRenderer(outputbase,
api.GetDatapath()));
}
api.GetBoolVariable("tessedit_write_unlv", &b);
if (b) renderers.push_back(new tesseract::TessUnlvRenderer(outputbase));
api.GetBoolVariable("tessedit_create_boxfile", &b);
if (b) renderers.push_back(new tesseract::TessBoxTextRenderer(outputbase));
api.GetBoolVariable("tessedit_create_txt", &b);
if (b) renderers.push_back(new tesseract::TessTextRenderer(outputbase));
if (!renderers.empty()) {
// Since the PointerVector auto-deletes, null-out the renderers that are
// added to the root, and leave the root in the vector.
for (int r = 1; r < renderers.size(); ++r) {
renderers[0]->insert(renderers[r]);
renderers[r] = NULL;
}
if (!api.ProcessPages(image, NULL, 0, renderers[0])) {
fprintf(stderr, "Error during processing.\n");
exit(1);
}
}
PERF_COUNT_END
return 0; // Normal exit
}
| C++ |
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "baseapi.h"
#include "renderer.h"
#include "math.h"
#include "strngs.h"
#include "cube_utils.h"
#include "allheaders.h"
#ifdef _MSC_VER
#include "mathfix.h"
#endif
namespace tesseract {
// Use for PDF object fragments. Must be large enough
// to hold a colormap with 256 colors in the verbose
// PDF representation.
const int kBasicBufSize = 2048;
// If the font is 10 pts, nominal character width is 5 pts
const int kCharWidth = 2;
/**********************************************************************
* PDF Renderer interface implementation
**********************************************************************/
TessPDFRenderer::TessPDFRenderer(const char* outputbase, const char *datadir)
: TessResultRenderer(outputbase, "pdf") {
obj_ = 0;
datadir_ = datadir;
offsets_.push_back(0);
}
void TessPDFRenderer::AppendPDFObjectDIY(size_t objectsize) {
offsets_.push_back(objectsize + offsets_.back());
obj_++;
}
void TessPDFRenderer::AppendPDFObject(const char *data) {
AppendPDFObjectDIY(strlen(data));
AppendString((const char *)data);
}
// Helper function to prevent us from accidentaly writing
// scientific notation to an HOCR or PDF file. Besides, three
// decimal points are all you really need.
double prec(double x) {
double kPrecision = 1000.0;
double a = round(x * kPrecision) / kPrecision;
if (a == -0)
return 0;
return a;
}
long dist2(int x1, int y1, int x2, int y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
// Viewers like evince can get really confused during copy-paste when
// the baseline wanders around. So I've decided to project every word
// onto the (straight) line baseline. All numbers are in the native
// PDF coordinate system, which has the origin in the bottom left and
// the unit is points, which is 1/72 inch. Tesseract reports baselines
// left-to-right no matter what the reading order is. We need the
// word baseline in reading order, so we do that conversion here. Returns
// the word's baseline origin and length.
void GetWordBaseline(int writing_direction, int ppi, int height,
int word_x1, int word_y1, int word_x2, int word_y2,
int line_x1, int line_y1, int line_x2, int line_y2,
double *x0, double *y0, double *length) {
if (writing_direction == WRITING_DIRECTION_RIGHT_TO_LEFT) {
Swap(&word_x1, &word_x2);
Swap(&word_y1, &word_y2);
}
double word_length;
double x, y;
{
int px = word_x1;
int py = word_y1;
double l2 = dist2(line_x1, line_y1, line_x2, line_y2);
if (l2 == 0) {
x = line_x1;
y = line_y1;
} else {
double t = ((px - line_x2) * (line_x2 - line_x1) +
(py - line_y2) * (line_y2 - line_y1)) / l2;
x = line_x2 + t * (line_x2 - line_x1);
y = line_y2 + t * (line_y2 - line_y1);
}
word_length = sqrt(static_cast<double>(dist2(word_x1, word_y1,
word_x2, word_y2)));
word_length = word_length * 72.0 / ppi;
x = x * 72 / ppi;
y = height - (y * 72.0 / ppi);
}
*x0 = x;
*y0 = y;
*length = word_length;
}
// Compute coefficients for an affine matrix describing the rotation
// of the text. If the text is right-to-left such as Arabic or Hebrew,
// we reflect over the Y-axis. This matrix will set the coordinate
// system for placing text in the PDF file.
//
// RTL
// [ x' ] = [ a b ][ x ] = [-1 0 ] [ cos sin ][ x ]
// [ y' ] [ c d ][ y ] [ 0 1 ] [-sin cos ][ y ]
void AffineMatrix(int writing_direction,
int line_x1, int line_y1, int line_x2, int line_y2,
double *a, double *b, double *c, double *d) {
double theta = atan2(static_cast<double>(line_y1 - line_y2),
static_cast<double>(line_x2 - line_x1));
*a = cos(theta);
*b = sin(theta);
*c = -sin(theta);
*d = cos(theta);
switch(writing_direction) {
case WRITING_DIRECTION_RIGHT_TO_LEFT:
*a = -*a;
*b = -*b;
break;
case WRITING_DIRECTION_TOP_TO_BOTTOM:
// TODO(jbreiden) Consider using the vertical PDF writing mode.
break;
default:
break;
}
}
// There are some really stupid PDF viewers in the wild, such as
// 'Preview' which ships with the Mac. They do a better job with text
// selection and highlighting when given perfectly flat baseline
// instead of very slightly tilted. We clip small tilts to appease
// these viewers. I chose this threshold large enough to absorb noise,
// but small enough that lines probably won't cross each other if the
// whole page is tilted at almost exactly the clipping threshold.
void ClipBaseline(int ppi, int x1, int y1, int x2, int y2,
int *line_x1, int *line_y1,
int *line_x2, int *line_y2) {
*line_x1 = x1;
*line_y1 = y1;
*line_x2 = x2;
*line_y2 = y2;
double rise = abs(y2 - y1) * 72 / ppi;
double run = abs(x2 - x1) * 72 / ppi;
if (rise < 2.0 && 2.0 < run)
*line_y1 = *line_y2 = (y1 + y2) / 2;
}
char* TessPDFRenderer::GetPDFTextObjects(TessBaseAPI* api,
double width, double height) {
STRING pdf_str("");
double ppi = api->GetSourceYResolution();
// These initial conditions are all arbitrary and will be overwritten
double old_x = 0.0, old_y = 0.0;
int old_fontsize = 0;
tesseract::WritingDirection old_writing_direction =
WRITING_DIRECTION_LEFT_TO_RIGHT;
bool new_block = true;
int fontsize = 0;
double a = 1;
double b = 0;
double c = 0;
double d = 1;
// TODO(jbreiden) This marries the text and image together.
// Slightly cleaner from an abstraction standpoint if this were to
// live inside a separate text object.
pdf_str += "q ";
pdf_str.add_str_double("", prec(width));
pdf_str += " 0 0 ";
pdf_str.add_str_double("", prec(height));
pdf_str += " 0 0 cm /Im1 Do Q\n";
ResultIterator *res_it = api->GetIterator();
while (!res_it->Empty(RIL_BLOCK)) {
if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
pdf_str += "BT\n3 Tr"; // Begin text object, use invisible ink
old_fontsize = 0; // Every block will declare its fontsize
new_block = true; // Every block will declare its affine matrix
}
int line_x1, line_y1, line_x2, line_y2;
if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
int x1, y1, x2, y2;
res_it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2);
ClipBaseline(ppi, x1, y1, x2, y2, &line_x1, &line_y1, &line_x2, &line_y2);
}
if (res_it->Empty(RIL_WORD)) {
res_it->Next(RIL_WORD);
continue;
}
// Writing direction changes at a per-word granularity
tesseract::WritingDirection writing_direction;
{
tesseract::Orientation orientation;
tesseract::TextlineOrder textline_order;
float deskew_angle;
res_it->Orientation(&orientation, &writing_direction,
&textline_order, &deskew_angle);
if (writing_direction != WRITING_DIRECTION_TOP_TO_BOTTOM) {
switch (res_it->WordDirection()) {
case DIR_LEFT_TO_RIGHT:
writing_direction = WRITING_DIRECTION_LEFT_TO_RIGHT;
break;
case DIR_RIGHT_TO_LEFT:
writing_direction = WRITING_DIRECTION_RIGHT_TO_LEFT;
break;
default:
writing_direction = old_writing_direction;
}
}
}
// Where is word origin and how long is it?
double x, y, word_length;
{
int word_x1, word_y1, word_x2, word_y2;
res_it->Baseline(RIL_WORD, &word_x1, &word_y1, &word_x2, &word_y2);
GetWordBaseline(writing_direction, ppi, height,
word_x1, word_y1, word_x2, word_y2,
line_x1, line_y1, line_x2, line_y2,
&x, &y, &word_length);
}
if (writing_direction != old_writing_direction || new_block) {
AffineMatrix(writing_direction,
line_x1, line_y1, line_x2, line_y2, &a, &b, &c, &d);
pdf_str.add_str_double(" ", prec(a)); // . This affine matrix
pdf_str.add_str_double(" ", prec(b)); // . sets the coordinate
pdf_str.add_str_double(" ", prec(c)); // . system for all
pdf_str.add_str_double(" ", prec(d)); // . text that follows.
pdf_str.add_str_double(" ", prec(x)); // .
pdf_str.add_str_double(" ", prec(y)); // .
pdf_str += (" Tm "); // Place cursor absolutely
new_block = false;
} else {
double dx = x - old_x;
double dy = y - old_y;
pdf_str.add_str_double(" ", prec(dx * a + dy * b));
pdf_str.add_str_double(" ", prec(dx * c + dy * d));
pdf_str += (" Td "); // Relative moveto
}
old_x = x;
old_y = y;
old_writing_direction = writing_direction;
// Adjust font size on a per word granularity. Pay attention to
// fontsize, old_fontsize, and pdf_str. We've found that for
// in Arabic, Tesseract will happily return a fontsize of zero,
// so we make up a default number to protect ourselves.
{
bool bold, italic, underlined, monospace, serif, smallcaps;
int font_id;
res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace,
&serif, &smallcaps, &fontsize, &font_id);
const int kDefaultFontsize = 8;
if (fontsize <= 0)
fontsize = kDefaultFontsize;
if (fontsize != old_fontsize) {
char textfont[20];
snprintf(textfont, sizeof(textfont), "/f-0-0 %d Tf ", fontsize);
pdf_str += textfont;
old_fontsize = fontsize;
}
}
bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD);
bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD);
STRING pdf_word("");
int pdf_word_len = 0;
do {
const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL);
if (grapheme && grapheme[0] != '\0') {
// TODO(jbreiden) Do a real UTF-16BE conversion
// http://en.wikipedia.org/wiki/UTF-16#Example_UTF-16_encoding_procedure
string_32 utf32;
CubeUtils::UTF8ToUTF32(grapheme, &utf32);
char utf16[20];
for (int i = 0; i < static_cast<int>(utf32.length()); i++) {
snprintf(utf16, sizeof(utf16), "<%04X>", utf32[i]);
pdf_word += utf16;
pdf_word_len++;
}
}
delete []grapheme;
res_it->Next(RIL_SYMBOL);
} while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
if (word_length > 0 && pdf_word_len > 0 && fontsize > 0) {
double h_stretch =
kCharWidth * prec(100.0 * word_length / (fontsize * pdf_word_len));
pdf_str.add_str_double("", h_stretch);
pdf_str += " Tz"; // horizontal stretch
pdf_str += " [ ";
pdf_str += pdf_word; // UTF-16BE representation
pdf_str += " ] TJ"; // show the text
}
if (last_word_in_line) {
pdf_str += " \n";
}
if (last_word_in_block) {
pdf_str += "ET\n"; // end the text object
}
}
char *ret = new char[pdf_str.length() + 1];
strcpy(ret, pdf_str.string());
delete res_it;
return ret;
}
bool TessPDFRenderer::BeginDocumentHandler() {
char buf[kBasicBufSize];
size_t n;
n = snprintf(buf, sizeof(buf),
"%%PDF-1.5\n"
"%%%c%c%c%c\n",
0xDE, 0xAD, 0xBE, 0xEB);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
// CATALOG
n = snprintf(buf, sizeof(buf),
"1 0 obj\n"
"<<\n"
" /Type /Catalog\n"
" /Pages %ld 0 R\n"
">>\n"
"endobj\n", 2L);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
// We are reserving object #2 for the /Pages
// object, which I am going to create and write
// at the end of the PDF file.
AppendPDFObject("");
// TYPE0 FONT
n = snprintf(buf, sizeof(buf),
"3 0 obj\n"
"<<\n"
" /BaseFont /GlyphLessFont\n"
" /DescendantFonts [ %ld 0 R ]\n"
" /Encoding /Identity-H\n"
" /Subtype /Type0\n"
" /ToUnicode %ld 0 R\n"
" /Type /Font\n"
">>\n"
"endobj\n",
4L, // CIDFontType2 font
5L // ToUnicode
);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
// CIDFONTTYPE2
n = snprintf(buf, sizeof(buf),
"4 0 obj\n"
"<<\n"
" /BaseFont /GlyphLessFont\n"
" /CIDToGIDMap /Identity\n"
" /CIDSystemInfo\n"
" <<\n"
" /Ordering (Identity)\n"
" /Registry (Adobe)\n"
" /Supplement 0\n"
" >>\n"
" /FontDescriptor %ld 0 R\n"
" /Subtype /CIDFontType2\n"
" /Type /Font\n"
" /DW %d\n"
">>\n"
"endobj\n",
6L, // Font descriptor
1000 / kCharWidth);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
const char *stream =
"/CIDInit /ProcSet findresource begin\n"
"12 dict begin\n"
"begincmap\n"
"/CIDSystemInfo\n"
"<<\n"
" /Registry (Adobe)\n"
" /Ordering (UCS)\n"
" /Supplement 0\n"
">> def\n"
"/CMapName /Adobe-Identify-UCS def\n"
"/CMapType 2 def\n"
"1 begincodespacerange\n"
"<0000> <FFFF>\n"
"endcodespacerange\n"
"1 beginbfrange\n"
"<0000> <FFFF> <0000>\n"
"endbfrange\n"
"endcmap\n"
"CMapName currentdict /CMap defineresource pop\n"
"end\n"
"end\n";
// TOUNICODE
n = snprintf(buf, sizeof(buf),
"5 0 obj\n"
"<< /Length %lu >>\n"
"stream\n"
"%s"
"endstream\n"
"endobj\n", (unsigned long) strlen(stream), stream);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
// FONT DESCRIPTOR
const int kCharHeight = 2; // Effect: highlights are half height
n = snprintf(buf, sizeof(buf),
"6 0 obj\n"
"<<\n"
" /Ascent %d\n"
" /CapHeight %d\n"
" /Descent -1\n" // Spec says must be negative
" /Flags 5\n" // FixedPitch + Symbolic
" /FontBBox [ 0 0 %d %d ]\n"
" /FontFile2 %ld 0 R\n"
" /FontName /GlyphLessFont\n"
" /ItalicAngle 0\n"
" /StemV 80\n"
" /Type /FontDescriptor\n"
">>\n"
"endobj\n",
1000 / kCharHeight,
1000 / kCharHeight,
1000 / kCharWidth,
1000 / kCharHeight,
7L // Font data
);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
n = snprintf(buf, sizeof(buf), "%s/pdf.ttf", datadir_);
if (n >= sizeof(buf)) return false;
FILE *fp = fopen(buf, "rb");
if (!fp)
return false;
fseek(fp, 0, SEEK_END);
long int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = new char[size];
if (fread(buffer, 1, size, fp) != size) {
fclose(fp);
delete[] buffer;
return false;
}
fclose(fp);
// FONTFILE2
n = snprintf(buf, sizeof(buf),
"7 0 obj\n"
"<<\n"
" /Length %ld\n"
" /Length1 %ld\n"
">>\n"
"stream\n", size, size);
if (n >= sizeof(buf)) return false;
AppendString(buf);
size_t objsize = strlen(buf);
AppendData(buffer, size);
delete[] buffer;
objsize += size;
const char *b2 =
"endstream\n"
"endobj\n";
AppendString(b2);
objsize += strlen(b2);
AppendPDFObjectDIY(objsize);
return true;
}
bool TessPDFRenderer::imageToPDFObj(Pix *pix,
char *filename,
long int objnum,
char **pdf_object,
long int *pdf_object_size) {
size_t n;
char b0[kBasicBufSize];
char b1[kBasicBufSize];
char b2[kBasicBufSize];
if (!pdf_object_size || !pdf_object)
return false;
*pdf_object = NULL;
*pdf_object_size = 0;
if (!filename)
return false;
L_COMP_DATA *cid = NULL;
const int kJpegQuality = 85;
// TODO(jbreiden) Leptonica 1.71 doesn't correctly handle certain
// types of PNG files, especially if there are 2 samples per pixel.
// We can get rid of this logic after Leptonica 1.72 is released and
// has propagated everywhere. Bug discussion as follows.
// https://code.google.com/p/tesseract-ocr/issues/detail?id=1300
int format, sad;
findFileFormat(filename, &format);
if (pixGetSpp(pix) == 4 && format == IFF_PNG) {
pixSetSpp(pix, 3);
sad = pixGenerateCIData(pix, L_FLATE_ENCODE, 0, 0, &cid);
} else {
sad = l_generateCIDataForPdf(filename, pix, kJpegQuality, &cid);
}
if (sad || !cid) {
l_CIDataDestroy(&cid);
return false;
}
const char *group4 = "";
const char *filter;
switch(cid->type) {
case L_FLATE_ENCODE:
filter = "/FlateDecode";
break;
case L_JPEG_ENCODE:
filter = "/DCTDecode";
break;
case L_G4_ENCODE:
filter = "/CCITTFaxDecode";
group4 = " /K -1\n";
break;
case L_JP2K_ENCODE:
filter = "/JPXDecode";
break;
default:
l_CIDataDestroy(&cid);
return false;
}
// Maybe someday we will accept RGBA but today is not that day.
// It requires creating an /SMask for the alpha channel.
// http://stackoverflow.com/questions/14220221
const char *colorspace;
if (cid->ncolors > 0) {
n = snprintf(b0, sizeof(b0),
" /ColorSpace [ /Indexed /DeviceRGB %d %s ]\n",
cid->ncolors - 1, cid->cmapdatahex);
if (n >= sizeof(b0)) {
l_CIDataDestroy(&cid);
return false;
}
colorspace = b0;
} else {
switch (cid->spp) {
case 1:
colorspace = " /ColorSpace /DeviceGray\n";
break;
case 3:
colorspace = " /ColorSpace /DeviceRGB\n";
break;
default:
l_CIDataDestroy(&cid);
return false;
}
}
int predictor = (cid->predictor) ? 14 : 1;
// IMAGE
n = snprintf(b1, sizeof(b1),
"%ld 0 obj\n"
"<<\n"
" /Length %ld\n"
" /Subtype /Image\n",
objnum, (unsigned long) cid->nbytescomp);
if (n >= sizeof(b1)) {
l_CIDataDestroy(&cid);
return false;
}
n = snprintf(b2, sizeof(b2),
" /Width %d\n"
" /Height %d\n"
" /BitsPerComponent %d\n"
" /Filter %s\n"
" /DecodeParms\n"
" <<\n"
" /Predictor %d\n"
" /Colors %d\n"
"%s"
" /Columns %d\n"
" /BitsPerComponent %d\n"
" >>\n"
">>\n"
"stream\n",
cid->w, cid->h, cid->bps, filter, predictor, cid->spp,
group4, cid->w, cid->bps);
if (n >= sizeof(b2)) {
l_CIDataDestroy(&cid);
return false;
}
const char *b3 =
"endstream\n"
"endobj\n";
size_t b1_len = strlen(b1);
size_t b2_len = strlen(b2);
size_t b3_len = strlen(b3);
size_t colorspace_len = strlen(colorspace);
*pdf_object_size =
b1_len + colorspace_len + b2_len + cid->nbytescomp + b3_len;
*pdf_object = new char[*pdf_object_size];
if (!pdf_object) {
l_CIDataDestroy(&cid);
return false;
}
char *p = *pdf_object;
memcpy(p, b1, b1_len);
p += b1_len;
memcpy(p, colorspace, colorspace_len);
p += colorspace_len;
memcpy(p, b2, b2_len);
p += b2_len;
memcpy(p, cid->datacomp, cid->nbytescomp);
p += cid->nbytescomp;
memcpy(p, b3, b3_len);
l_CIDataDestroy(&cid);
return true;
}
bool TessPDFRenderer::AddImageHandler(TessBaseAPI* api) {
size_t n;
char buf[kBasicBufSize];
Pix *pix = api->GetInputImage();
char *filename = (char *)api->GetInputName();
int ppi = api->GetSourceYResolution();
if (!pix || ppi <= 0)
return false;
double width = pixGetWidth(pix) * 72.0 / ppi;
double height = pixGetHeight(pix) * 72.0 / ppi;
// PAGE
n = snprintf(buf, sizeof(buf),
"%ld 0 obj\n"
"<<\n"
" /Type /Page\n"
" /Parent %ld 0 R\n"
" /MediaBox [0 0 %.2f %.2f]\n"
" /Contents %ld 0 R\n"
" /Resources\n"
" <<\n"
" /XObject << /Im1 %ld 0 R >>\n"
" /ProcSet [ /PDF /Text /ImageB /ImageI /ImageC ]\n"
" /Font << /f-0-0 %ld 0 R >>\n"
" >>\n"
">>\n"
"endobj\n",
obj_,
2L, // Pages object
width,
height,
obj_ + 1, // Contents object
obj_ + 2, // Image object
3L); // Type0 Font
if (n >= sizeof(buf)) return false;
pages_.push_back(obj_);
AppendPDFObject(buf);
// CONTENTS
char* pdftext = GetPDFTextObjects(api, width, height);
long pdftext_len = strlen(pdftext);
unsigned char *pdftext_casted = reinterpret_cast<unsigned char *>(pdftext);
size_t len;
unsigned char *comp_pdftext =
zlibCompress(pdftext_casted,
pdftext_len,
&len);
long comp_pdftext_len = len;
n = snprintf(buf, sizeof(buf),
"%ld 0 obj\n"
"<<\n"
" /Length %ld /Filter /FlateDecode\n"
">>\n"
"stream\n", obj_, comp_pdftext_len);
if (n >= sizeof(buf)) {
delete[] pdftext;
lept_free(comp_pdftext);
return false;
}
AppendString(buf);
long objsize = strlen(buf);
AppendData(reinterpret_cast<char *>(comp_pdftext), comp_pdftext_len);
objsize += comp_pdftext_len;
lept_free(comp_pdftext);
delete[] pdftext;
const char *b2 =
"endstream\n"
"endobj\n";
AppendString(b2);
objsize += strlen(b2);
AppendPDFObjectDIY(objsize);
char *pdf_object;
if (!imageToPDFObj(pix, filename, obj_, &pdf_object, &objsize)) {
return false;
}
AppendData(pdf_object, objsize);
AppendPDFObjectDIY(objsize);
delete[] pdf_object;
return true;
}
bool TessPDFRenderer::EndDocumentHandler() {
size_t n;
char buf[kBasicBufSize];
// We reserved the /Pages object number early, so that the /Page
// objects could refer to their parent. We finally have enough
// information to go fill it in. Using lower level calls to manipulate
// the offset record in two spots, because we are placing objects
// out of order in the file.
// PAGES
const long int kPagesObjectNumber = 2;
offsets_[kPagesObjectNumber] = offsets_.back(); // manipulation #1
n = snprintf(buf, sizeof(buf),
"%ld 0 obj\n"
"<<\n"
" /Type /Pages\n"
" /Kids [ ", kPagesObjectNumber);
if (n >= sizeof(buf)) return false;
AppendString(buf);
size_t pages_objsize = strlen(buf);
for (size_t i = 0; i < pages_.size(); i++) {
n = snprintf(buf, sizeof(buf),
"%ld 0 R ", pages_[i]);
if (n >= sizeof(buf)) return false;
AppendString(buf);
pages_objsize += strlen(buf);
}
n = snprintf(buf, sizeof(buf),
"]\n"
" /Count %d\n"
">>\n"
"endobj\n", pages_.size());
if (n >= sizeof(buf)) return false;
AppendString(buf);
pages_objsize += strlen(buf);
offsets_.back() += pages_objsize; // manipulation #2
// INFO
char* datestr = l_getFormattedDate();
n = snprintf(buf, sizeof(buf),
"%ld 0 obj\n"
"<<\n"
" /Producer (Tesseract %s)\n"
" /CreationDate (D:%s)\n"
" /Title (%s)"
">>\n"
"endobj\n", obj_, TESSERACT_VERSION_STR, datestr, title());
lept_free(datestr);
if (n >= sizeof(buf)) return false;
AppendPDFObject(buf);
n = snprintf(buf, sizeof(buf),
"xref\n"
"0 %ld\n"
"0000000000 65535 f \n", obj_);
if (n >= sizeof(buf)) return false;
AppendString(buf);
for (int i = 1; i < obj_; i++) {
n = snprintf(buf, sizeof(buf), "%010ld 00000 n \n", offsets_[i]);
if (n >= sizeof(buf)) return false;
AppendString(buf);
}
n = snprintf(buf, sizeof(buf),
"trailer\n"
"<<\n"
" /Size %ld\n"
" /Root %ld 0 R\n"
" /Info %ld 0 R\n"
">>\n"
"startxref\n"
"%ld\n"
"%%%%EOF\n",
obj_,
1L, // catalog
obj_ - 1, // info
offsets_.back());
if (n >= sizeof(buf)) return false;
AppendString(buf);
return true;
}
} // namespace tesseract
| C++ |
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include <string.h>
#include "baseapi.h"
#include "genericvector.h"
#include "renderer.h"
namespace tesseract {
/**********************************************************************
* Base Renderer interface implementation
**********************************************************************/
TessResultRenderer::TessResultRenderer(const char *outputbase,
const char* extension)
: file_extension_(extension),
title_(""), imagenum_(-1),
fout_(stdout),
next_(NULL),
happy_(true) {
if (strcmp(outputbase, "-") && strcmp(outputbase, "stdout")) {
STRING outfile = STRING(outputbase) + STRING(".") + STRING(file_extension_);
fout_ = fopen(outfile.string(), "wb");
if (fout_ == NULL) {
happy_ = false;
}
}
}
TessResultRenderer::~TessResultRenderer() {
if (fout_ != stdout)
fclose(fout_);
else
clearerr(fout_);
delete next_;
}
void TessResultRenderer::insert(TessResultRenderer* next) {
if (next == NULL) return;
TessResultRenderer* remainder = next_;
next_ = next;
if (remainder) {
while (next->next_ != NULL) {
next = next->next_;
}
next->next_ = remainder;
}
}
bool TessResultRenderer::BeginDocument(const char* title) {
if (!happy_) return false;
title_ = title;
imagenum_ = -1;
bool ok = BeginDocumentHandler();
if (next_) {
ok = next_->BeginDocument(title) && ok;
}
return ok;
}
bool TessResultRenderer::AddImage(TessBaseAPI* api) {
if (!happy_) return false;
++imagenum_;
bool ok = AddImageHandler(api);
if (next_) {
ok = next_->AddImage(api) && ok;
}
return ok;
}
bool TessResultRenderer::EndDocument() {
if (!happy_) return false;
bool ok = EndDocumentHandler();
if (next_) {
ok = next_->EndDocument() && ok;
}
return ok;
}
void TessResultRenderer::AppendString(const char* s) {
AppendData(s, strlen(s));
}
void TessResultRenderer::AppendData(const char* s, int len) {
int n = fwrite(s, 1, len, fout_);
if (n != len) happy_ = false;
}
bool TessResultRenderer::BeginDocumentHandler() {
return happy_;
}
bool TessResultRenderer::EndDocumentHandler() {
return happy_;
}
/**********************************************************************
* UTF8 Text Renderer interface implementation
**********************************************************************/
TessTextRenderer::TessTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "txt") {
}
bool TessTextRenderer::AddImageHandler(TessBaseAPI* api) {
char* utf8 = api->GetUTF8Text();
if (utf8 == NULL) {
return false;
}
AppendString(utf8);
delete[] utf8;
return true;
}
/**********************************************************************
* HOcr Text Renderer interface implementation
**********************************************************************/
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = false;
}
TessHOcrRenderer::TessHOcrRenderer(const char *outputbase, bool font_info)
: TessResultRenderer(outputbase, "hocr") {
font_info_ = font_info;
}
bool TessHOcrRenderer::BeginDocumentHandler() {
AppendString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" "
"lang=\"en\">\n <head>\n <title>\n");
AppendString(title());
AppendString(
"</title>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html;"
"charset=utf-8\" />\n"
" <meta name='ocr-system' content='tesseract " TESSERACT_VERSION_STR
"' />\n"
" <meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par"
" ocr_line ocrx_word");
if (font_info_)
AppendString(
" ocrp_lang ocrp_dir ocrp_font ocrp_fsize ocrp_wconf");
AppendString(
"'/>\n"
"</head>\n<body>\n");
return true;
}
bool TessHOcrRenderer::EndDocumentHandler() {
AppendString(" </body>\n</html>\n");
return true;
}
bool TessHOcrRenderer::AddImageHandler(TessBaseAPI* api) {
char* hocr = api->GetHOCRText(imagenum());
if (hocr == NULL) return false;
AppendString(hocr);
delete[] hocr;
return true;
}
/**********************************************************************
* UNLV Text Renderer interface implementation
**********************************************************************/
TessUnlvRenderer::TessUnlvRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "unlv") {
}
bool TessUnlvRenderer::AddImageHandler(TessBaseAPI* api) {
char* unlv = api->GetUNLVText();
if (unlv == NULL) return false;
AppendString(unlv);
delete[] unlv;
return true;
}
/**********************************************************************
* BoxText Renderer interface implementation
**********************************************************************/
TessBoxTextRenderer::TessBoxTextRenderer(const char *outputbase)
: TessResultRenderer(outputbase, "box") {
}
bool TessBoxTextRenderer::AddImageHandler(TessBaseAPI* api) {
char* text = api->GetBoxText(imagenum());
if (text == NULL) return false;
AppendString(text);
delete[] text;
return true;
}
} // namespace tesseract
| C++ |
/**********************************************************************
* File: baseapi.cpp
* Description: Simple API for calling tesseract.
* Author: Ray Smith
* Created: Fri Oct 06 15:35:01 PDT 2006
*
* (C) Copyright 2006, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#ifdef __linux__
#include <signal.h>
#endif
#if defined(_WIN32)
#ifdef _MSC_VER
#include "mathfix.h"
#elif MINGW
// workaround for stdlib.h with -std=c++11 for _splitpath and _MAX_FNAME
#undef __STRICT_ANSI__
#endif // _MSC_VER
#include <stdlib.h>
#include <windows.h>
#include <fcntl.h>
#include <io.h>
#else
#include <dirent.h>
#include <libgen.h>
#include <string.h>
#endif // _WIN32
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
#include "allheaders.h"
#include "baseapi.h"
#include "resultiterator.h"
#include "mutableiterator.h"
#include "thresholder.h"
#include "tesseractclass.h"
#include "pageres.h"
#include "paragraphs.h"
#include "tessvars.h"
#include "control.h"
#include "dict.h"
#include "pgedit.h"
#include "paramsd.h"
#include "output.h"
#include "globaloc.h"
#include "globals.h"
#include "edgblob.h"
#include "equationdetect.h"
#include "tessbox.h"
#include "makerow.h"
#include "otsuthr.h"
#include "osdetect.h"
#include "params.h"
#include "renderer.h"
#include "strngs.h"
#include "openclwrapper.h"
BOOL_VAR(stream_filelist, FALSE, "Stream a filelist from stdin");
namespace tesseract {
/** Minimum sensible image size to be worth running tesseract. */
const int kMinRectSize = 10;
/** Character returned when Tesseract couldn't recognize as anything. */
const char kTesseractReject = '~';
/** Character used by UNLV error counter as a reject. */
const char kUNLVReject = '~';
/** Character used by UNLV as a suspect marker. */
const char kUNLVSuspect = '^';
/**
* Filename used for input image file, from which to derive a name to search
* for a possible UNLV zone file, if none is specified by SetInputName.
*/
const char* kInputFile = "noname.tif";
/**
* Temp file used for storing current parameters before applying retry values.
*/
const char* kOldVarsFile = "failed_vars.txt";
/** Max string length of an int. */
const int kMaxIntSize = 22;
/**
* Minimum believable resolution. Used as a default if there is no other
* information, as it is safer to under-estimate than over-estimate.
*/
const int kMinCredibleResolution = 70;
/** Maximum believable resolution. */
const int kMaxCredibleResolution = 2400;
TessBaseAPI::TessBaseAPI()
: tesseract_(NULL),
osd_tesseract_(NULL),
equ_detect_(NULL),
// Thresholder is initialized to NULL here, but will be set before use by:
// A constructor of a derived API, SetThresholder(), or
// created implicitly when used in InternalSetImage.
thresholder_(NULL),
paragraph_models_(NULL),
block_list_(NULL),
page_res_(NULL),
input_file_(NULL),
input_image_(NULL),
output_file_(NULL),
datapath_(NULL),
language_(NULL),
last_oem_requested_(OEM_DEFAULT),
recognition_done_(false),
truth_cb_(NULL),
rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0),
image_width_(0), image_height_(0) {
}
TessBaseAPI::~TessBaseAPI() {
End();
}
/**
* Returns the version identifier as a static string. Do not delete.
*/
const char* TessBaseAPI::Version() {
return TESSERACT_VERSION_STR;
}
/**
* If compiled with OpenCL AND an available OpenCL
* device is deemed faster than serial code, then
* "device" is populated with the cl_device_id
* and returns sizeof(cl_device_id)
* otherwise *device=NULL and returns 0.
*/
#ifdef USE_OPENCL
#if USE_DEVICE_SELECTION
#include "opencl_device_selection.h"
#endif
#endif
size_t TessBaseAPI::getOpenCLDevice(void **data) {
#ifdef USE_OPENCL
#if USE_DEVICE_SELECTION
ds_device device = OpenclDevice::getDeviceSelection();
if (device.type == DS_DEVICE_OPENCL_DEVICE) {
*data = reinterpret_cast<void*>(new cl_device_id);
memcpy(*data, &device.oclDeviceID, sizeof(cl_device_id));
return sizeof(cl_device_id);
}
#endif
#endif
*data = NULL;
return 0;
}
/**
* Writes the thresholded image to stderr as a PBM file on receipt of a
* SIGSEGV, SIGFPE, or SIGBUS signal. (Linux/Unix only).
*/
void TessBaseAPI::CatchSignals() {
#ifdef __linux__
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = &signal_exit;
action.sa_flags = SA_RESETHAND;
sigaction(SIGSEGV, &action, NULL);
sigaction(SIGFPE, &action, NULL);
sigaction(SIGBUS, &action, NULL);
#else
// Warn API users that an implementation is needed.
tprintf("CatchSignals has no non-linux implementation!\n");
#endif
}
/**
* Set the name of the input file. Needed only for training and
* loading a UNLV zone file.
*/
void TessBaseAPI::SetInputName(const char* name) {
if (input_file_ == NULL)
input_file_ = new STRING(name);
else
*input_file_ = name;
}
/** Set the name of the output files. Needed only for debugging. */
void TessBaseAPI::SetOutputName(const char* name) {
if (output_file_ == NULL)
output_file_ = new STRING(name);
else
*output_file_ = name;
}
bool TessBaseAPI::SetVariable(const char* name, const char* value) {
if (tesseract_ == NULL) tesseract_ = new Tesseract;
return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_NON_INIT_ONLY,
tesseract_->params());
}
bool TessBaseAPI::SetDebugVariable(const char* name, const char* value) {
if (tesseract_ == NULL) tesseract_ = new Tesseract;
return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_DEBUG_ONLY,
tesseract_->params());
}
bool TessBaseAPI::GetIntVariable(const char *name, int *value) const {
IntParam *p = ParamUtils::FindParam<IntParam>(
name, GlobalParams()->int_params, tesseract_->params()->int_params);
if (p == NULL) return false;
*value = (inT32)(*p);
return true;
}
bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const {
BoolParam *p = ParamUtils::FindParam<BoolParam>(
name, GlobalParams()->bool_params, tesseract_->params()->bool_params);
if (p == NULL) return false;
*value = (BOOL8)(*p);
return true;
}
const char *TessBaseAPI::GetStringVariable(const char *name) const {
StringParam *p = ParamUtils::FindParam<StringParam>(
name, GlobalParams()->string_params, tesseract_->params()->string_params);
return (p != NULL) ? p->string() : NULL;
}
bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const {
DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
name, GlobalParams()->double_params, tesseract_->params()->double_params);
if (p == NULL) return false;
*value = (double)(*p);
return true;
}
/** Get value of named variable as a string, if it exists. */
bool TessBaseAPI::GetVariableAsString(const char *name, STRING *val) {
return ParamUtils::GetParamAsString(name, tesseract_->params(), val);
}
/** Print Tesseract parameters to the given file. */
void TessBaseAPI::PrintVariables(FILE *fp) const {
ParamUtils::PrintParams(fp, tesseract_->params());
}
/**
* The datapath must be the name of the data directory (no ending /) or
* some other file in which the data directory resides (for instance argv[0].)
* The language is (usually) an ISO 639-3 string or NULL will default to eng.
* If numeric_mode is true, then only digits and Roman numerals will
* be returned.
* @return: 0 on success and -1 on initialization failure.
*/
int TessBaseAPI::Init(const char* datapath, const char* language,
OcrEngineMode oem, char **configs, int configs_size,
const GenericVector<STRING> *vars_vec,
const GenericVector<STRING> *vars_values,
bool set_only_non_debug_params) {
PERF_COUNT_START("TessBaseAPI::Init")
// Default language is "eng".
if (language == NULL) language = "eng";
// If the datapath, OcrEngineMode or the language have changed - start again.
// Note that the language_ field stores the last requested language that was
// initialized successfully, while tesseract_->lang stores the language
// actually used. They differ only if the requested language was NULL, in
// which case tesseract_->lang is set to the Tesseract default ("eng").
if (tesseract_ != NULL &&
(datapath_ == NULL || language_ == NULL ||
*datapath_ != datapath || last_oem_requested_ != oem ||
(*language_ != language && tesseract_->lang != language))) {
delete tesseract_;
tesseract_ = NULL;
}
// PERF_COUNT_SUB("delete tesseract_")
#ifdef USE_OPENCL
OpenclDevice od;
od.InitEnv();
#endif
PERF_COUNT_SUB("OD::InitEnv()")
bool reset_classifier = true;
if (tesseract_ == NULL) {
reset_classifier = false;
tesseract_ = new Tesseract;
if (tesseract_->init_tesseract(
datapath, output_file_ != NULL ? output_file_->string() : NULL,
language, oem, configs, configs_size, vars_vec, vars_values,
set_only_non_debug_params) != 0) {
return -1;
}
}
PERF_COUNT_SUB("update tesseract_")
// Update datapath and language requested for the last valid initialization.
if (datapath_ == NULL)
datapath_ = new STRING(datapath);
else
*datapath_ = datapath;
if ((strcmp(datapath_->string(), "") == 0) &&
(strcmp(tesseract_->datadir.string(), "") != 0))
*datapath_ = tesseract_->datadir;
if (language_ == NULL)
language_ = new STRING(language);
else
*language_ = language;
last_oem_requested_ = oem;
// PERF_COUNT_SUB("update last_oem_requested_")
// For same language and datapath, just reset the adaptive classifier.
if (reset_classifier) {
tesseract_->ResetAdaptiveClassifier();
PERF_COUNT_SUB("tesseract_->ResetAdaptiveClassifier()")
}
PERF_COUNT_END
return 0;
}
/**
* Returns the languages string used in the last valid initialization.
* If the last initialization specified "deu+hin" then that will be
* returned. If hin loaded eng automatically as well, then that will
* not be included in this list. To find the languages actually
* loaded use GetLoadedLanguagesAsVector.
* The returned string should NOT be deleted.
*/
const char* TessBaseAPI::GetInitLanguagesAsString() const {
return (language_ == NULL || language_->string() == NULL) ?
"" : language_->string();
}
/**
* Returns the loaded languages in the vector of STRINGs.
* Includes all languages loaded by the last Init, including those loaded
* as dependencies of other loaded languages.
*/
void TessBaseAPI::GetLoadedLanguagesAsVector(
GenericVector<STRING>* langs) const {
langs->clear();
if (tesseract_ != NULL) {
langs->push_back(tesseract_->lang);
int num_subs = tesseract_->num_sub_langs();
for (int i = 0; i < num_subs; ++i)
langs->push_back(tesseract_->get_sub_lang(i)->lang);
}
}
/**
* Returns the available languages in the vector of STRINGs.
*/
void TessBaseAPI::GetAvailableLanguagesAsVector(
GenericVector<STRING>* langs) const {
langs->clear();
if (tesseract_ != NULL) {
#ifdef _WIN32
STRING pattern = tesseract_->datadir + "/*." + kTrainedDataSuffix;
char fname[_MAX_FNAME];
WIN32_FIND_DATA data;
BOOL result = TRUE;
HANDLE handle = FindFirstFile(pattern.string(), &data);
if (handle != INVALID_HANDLE_VALUE) {
for (; result; result = FindNextFile(handle, &data)) {
_splitpath(data.cFileName, NULL, NULL, fname, NULL);
langs->push_back(STRING(fname));
}
FindClose(handle);
}
#else // _WIN32
DIR *dir;
struct dirent *dirent;
char *dot;
STRING extension = STRING(".") + kTrainedDataSuffix;
dir = opendir(tesseract_->datadir.string());
if (dir != NULL) {
while ((dirent = readdir(dir))) {
// Skip '.', '..', and hidden files
if (dirent->d_name[0] != '.') {
if (strstr(dirent->d_name, extension.string()) != NULL) {
dot = strrchr(dirent->d_name, '.');
// This ensures that .traineddata is at the end of the file name
if (strncmp(dot, extension.string(),
strlen(extension.string())) == 0) {
*dot = '\0';
langs->push_back(STRING(dirent->d_name));
}
}
}
}
closedir(dir);
}
#endif
}
}
/**
* Init only the lang model component of Tesseract. The only functions
* that work after this init are SetVariable and IsValidWord.
* WARNING: temporary! This function will be removed from here and placed
* in a separate API at some future time.
*/
int TessBaseAPI::InitLangMod(const char* datapath, const char* language) {
if (tesseract_ == NULL)
tesseract_ = new Tesseract;
else
ParamUtils::ResetToDefaults(tesseract_->params());
return tesseract_->init_tesseract_lm(datapath, NULL, language);
}
/**
* Init only for page layout analysis. Use only for calls to SetImage and
* AnalysePage. Calls that attempt recognition will generate an error.
*/
void TessBaseAPI::InitForAnalysePage() {
if (tesseract_ == NULL) {
tesseract_ = new Tesseract;
tesseract_->InitAdaptiveClassifier(false);
}
}
/**
* Read a "config" file containing a set of parameter name, value pairs.
* Searches the standard places: tessdata/configs, tessdata/tessconfigs
* and also accepts a relative or absolute path name.
*/
void TessBaseAPI::ReadConfigFile(const char* filename) {
tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_NON_INIT_ONLY);
}
/** Same as above, but only set debug params from the given config file. */
void TessBaseAPI::ReadDebugConfigFile(const char* filename) {
tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_DEBUG_ONLY);
}
/**
* Set the current page segmentation mode. Defaults to PSM_AUTO.
* The mode is stored as an IntParam so it can also be modified by
* ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string).
*/
void TessBaseAPI::SetPageSegMode(PageSegMode mode) {
if (tesseract_ == NULL)
tesseract_ = new Tesseract;
tesseract_->tessedit_pageseg_mode.set_value(mode);
}
/** Return the current page segmentation mode. */
PageSegMode TessBaseAPI::GetPageSegMode() const {
if (tesseract_ == NULL)
return PSM_SINGLE_BLOCK;
return static_cast<PageSegMode>(
static_cast<int>(tesseract_->tessedit_pageseg_mode));
}
/**
* Recognize a rectangle from an image and return the result as a string.
* May be called many times for a single Init.
* Currently has no error checking.
* Greyscale of 8 and color of 24 or 32 bits per pixel may be given.
* Palette color images will not work properly and must be converted to
* 24 bit.
* Binary images of 1 bit per pixel may also be given but they must be
* byte packed with the MSB of the first byte being the first pixel, and a
* one pixel is WHITE. For binary images set bytes_per_pixel=0.
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
*/
char* TessBaseAPI::TesseractRect(const unsigned char* imagedata,
int bytes_per_pixel,
int bytes_per_line,
int left, int top,
int width, int height) {
if (tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize)
return NULL; // Nothing worth doing.
// Since this original api didn't give the exact size of the image,
// we have to invent a reasonable value.
int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
bytes_per_pixel, bytes_per_line);
SetRectangle(left, top, width, height);
return GetUTF8Text();
}
/**
* Call between pages or documents etc to free up memory and forget
* adaptive data.
*/
void TessBaseAPI::ClearAdaptiveClassifier() {
if (tesseract_ == NULL)
return;
tesseract_->ResetAdaptiveClassifier();
tesseract_->ResetDocumentDictionary();
}
/**
* Provide an image for Tesseract to recognize. Format is as
* TesseractRect above. Does not copy the image buffer, or take
* ownership. The source image may be destroyed after Recognize is called,
* either explicitly or implicitly via one of the Get*Text functions.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*/
void TessBaseAPI::SetImage(const unsigned char* imagedata,
int width, int height,
int bytes_per_pixel, int bytes_per_line) {
if (InternalSetImage())
thresholder_->SetImage(imagedata, width, height,
bytes_per_pixel, bytes_per_line);
}
void TessBaseAPI::SetSourceResolution(int ppi) {
if (thresholder_)
thresholder_->SetSourceYResolution(ppi);
else
tprintf("Please call SetImage before SetSourceResolution.\n");
}
/**
* Provide an image for Tesseract to recognize. As with SetImage above,
* Tesseract doesn't take a copy or ownership or pixDestroy the image, so
* it must persist until after Recognize.
* Pix vs raw, which to use?
* Use Pix where possible. A future version of Tesseract may choose to use Pix
* as its internal representation and discard IMAGE altogether.
* Because of that, an implementation that sources and targets Pix may end up
* with less copies than an implementation that does not.
*/
void TessBaseAPI::SetImage(Pix* pix) {
if (InternalSetImage())
thresholder_->SetImage(pix);
SetInputImage(pix);
}
/**
* Restrict recognition to a sub-rectangle of the image. Call after SetImage.
* Each SetRectangle clears the recogntion results so multiple rectangles
* can be recognized with the same image.
*/
void TessBaseAPI::SetRectangle(int left, int top, int width, int height) {
if (thresholder_ == NULL)
return;
thresholder_->SetRectangle(left, top, width, height);
ClearResults();
}
/**
* ONLY available after SetImage if you have Leptonica installed.
* Get a copy of the internal thresholded image from Tesseract.
*/
Pix* TessBaseAPI::GetThresholdedImage() {
if (tesseract_ == NULL || thresholder_ == NULL)
return NULL;
if (tesseract_->pix_binary() == NULL)
Threshold(tesseract_->mutable_pix_binary());
return pixClone(tesseract_->pix_binary());
}
/**
* Get the result of page layout analysis as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* TessBaseAPI::GetRegions(Pixa** pixa) {
return GetComponentImages(RIL_BLOCK, false, pixa, NULL);
}
/**
* Get the textlines as a leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
* If paraids is not NULL, the paragraph-id of each line within its block is
* also returned as an array of one element per line. delete [] after use.
*/
Boxa* TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding,
Pixa** pixa, int** blockids, int** paraids) {
return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding,
pixa, blockids, paraids);
}
/**
* Get textlines and strips of image regions as a leptonica-style Boxa, Pixa
* pair, in reading order. Enables downstream handling of non-rectangular
* regions.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
*/
Boxa* TessBaseAPI::GetStrips(Pixa** pixa, int** blockids) {
return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids);
}
/**
* Get the words as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* TessBaseAPI::GetWords(Pixa** pixa) {
return GetComponentImages(RIL_WORD, true, pixa, NULL);
}
/**
* Gets the individual connected (text) components (created
* after pages segmentation step, but before recognition)
* as a leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa* TessBaseAPI::GetConnectedComponents(Pixa** pixa) {
return GetComponentImages(RIL_SYMBOL, true, pixa, NULL);
}
/**
* Get the given level kind of components (block, textline, word etc.) as a
* leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not NULL, the block-id of each component is also returned
* as an array of one element per component. delete [] after use.
* If text_only is true, then only text components are returned.
*/
Boxa* TessBaseAPI::GetComponentImages(PageIteratorLevel level,
bool text_only, bool raw_image,
const int raw_padding,
Pixa** pixa, int** blockids,
int** paraids) {
PageIterator* page_it = GetIterator();
if (page_it == NULL)
page_it = AnalyseLayout();
if (page_it == NULL)
return NULL; // Failed.
// Count the components to get a size for the arrays.
int component_count = 0;
int left, top, right, bottom;
TessResultCallback<bool>* get_bbox = NULL;
if (raw_image) {
// Get bounding box in original raw image with padding.
get_bbox = NewPermanentTessCallback(page_it, &PageIterator::BoundingBox,
level, raw_padding,
&left, &top, &right, &bottom);
} else {
// Get bounding box from binarized imaged. Note that this could be
// differently scaled from the original image.
get_bbox = NewPermanentTessCallback(page_it,
&PageIterator::BoundingBoxInternal,
level, &left, &top, &right, &bottom);
}
do {
if (get_bbox->Run() &&
(!text_only || PTIsTextType(page_it->BlockType())))
++component_count;
} while (page_it->Next(level));
Boxa* boxa = boxaCreate(component_count);
if (pixa != NULL)
*pixa = pixaCreate(component_count);
if (blockids != NULL)
*blockids = new int[component_count];
if (paraids != NULL)
*paraids = new int[component_count];
int blockid = 0;
int paraid = 0;
int component_index = 0;
page_it->Begin();
do {
if (get_bbox->Run() &&
(!text_only || PTIsTextType(page_it->BlockType()))) {
Box* lbox = boxCreate(left, top, right - left, bottom - top);
boxaAddBox(boxa, lbox, L_INSERT);
if (pixa != NULL) {
Pix* pix = NULL;
if (raw_image) {
pix = page_it->GetImage(level, raw_padding, input_image_,
&left, &top);
} else {
pix = page_it->GetBinaryImage(level);
}
pixaAddPix(*pixa, pix, L_INSERT);
pixaAddBox(*pixa, lbox, L_CLONE);
}
if (paraids != NULL) {
(*paraids)[component_index] = paraid;
if (page_it->IsAtFinalElement(RIL_PARA, level))
++paraid;
}
if (blockids != NULL) {
(*blockids)[component_index] = blockid;
if (page_it->IsAtFinalElement(RIL_BLOCK, level)) {
++blockid;
paraid = 0;
}
}
++component_index;
}
} while (page_it->Next(level));
delete page_it;
delete get_bbox;
return boxa;
}
int TessBaseAPI::GetThresholdedImageScaleFactor() const {
if (thresholder_ == NULL) {
return 0;
}
return thresholder_->GetScaleFactor();
}
/** Dump the internal binary image to a PGM file. */
void TessBaseAPI::DumpPGM(const char* filename) {
if (tesseract_ == NULL)
return;
FILE *fp = fopen(filename, "wb");
Pix* pix = tesseract_->pix_binary();
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
l_uint32* data = pixGetData(pix);
fprintf(fp, "P5 %d %d 255\n", width, height);
for (int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
for (int x = 0; x < width; ++x) {
uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255;
fwrite(&b, 1, 1, fp);
}
}
fclose(fp);
}
/**
* Placeholder for call to Cube and test that the input data is correct.
* reskew is the direction of baselines in the skewed image in
* normalized (cos theta, sin theta) form, so (0.866, 0.5) would represent
* a 30 degree anticlockwise skew.
*/
int CubeAPITest(Boxa* boxa_blocks, Pixa* pixa_blocks,
Boxa* boxa_words, Pixa* pixa_words,
const FCOORD& reskew, Pix* page_pix,
PAGE_RES* page_res) {
int block_count = boxaGetCount(boxa_blocks);
ASSERT_HOST(block_count == pixaGetCount(pixa_blocks));
// Write each block to the current directory as junk_write_display.nnn.png.
for (int i = 0; i < block_count; ++i) {
Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE);
pixDisplayWrite(pix, 1);
}
int word_count = boxaGetCount(boxa_words);
ASSERT_HOST(word_count == pixaGetCount(pixa_words));
int pr_word = 0;
PAGE_RES_IT page_res_it(page_res);
for (page_res_it.restart_page(); page_res_it.word () != NULL;
page_res_it.forward(), ++pr_word) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE* choice = word->best_choice;
// Write the first 100 words to files names wordims/<wordstring>.tif.
if (pr_word < 100) {
STRING filename("wordims/");
if (choice != NULL) {
filename += choice->unichar_string();
} else {
char numbuf[32];
filename += "unclassified";
snprintf(numbuf, 32, "%03d", pr_word);
filename += numbuf;
}
filename += ".tif";
Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE);
pixWrite(filename.string(), pix, IFF_TIFF_G4);
}
}
ASSERT_HOST(pr_word == word_count);
return 0;
}
/**
* Runs page layout analysis in the mode set by SetPageSegMode.
* May optionally be called prior to Recognize to get access to just
* the page layout results. Returns an iterator to the results.
* If merge_similar_words is true, words are combined where suitable for use
* with a line recognizer. Use if you want to use AnalyseLayout to find the
* textlines, and then want to process textline fragments with an external
* line recognizer.
* Returns NULL on error or an empty page.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
PageIterator* TessBaseAPI::AnalyseLayout(bool merge_similar_words) {
if (FindLines() == 0) {
if (block_list_->empty())
return NULL; // The page was empty.
page_res_ = new PAGE_RES(merge_similar_words, block_list_, NULL);
DetectParagraphs(false);
return new PageIterator(
page_res_, tesseract_, thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_);
}
return NULL;
}
/**
* Recognize the tesseract global image and return the result as Tesseract
* internal structures.
*/
int TessBaseAPI::Recognize(ETEXT_DESC* monitor) {
if (tesseract_ == NULL)
return -1;
if (FindLines() != 0)
return -1;
if (page_res_ != NULL)
delete page_res_;
if (block_list_->empty()) {
page_res_ = new PAGE_RES(false, block_list_,
&tesseract_->prev_word_best_choice_);
return 0; // Empty page.
}
tesseract_->SetBlackAndWhitelist();
recognition_done_ = true;
if (tesseract_->tessedit_resegment_from_line_boxes) {
page_res_ = tesseract_->ApplyBoxes(*input_file_, true, block_list_);
} else if (tesseract_->tessedit_resegment_from_boxes) {
page_res_ = tesseract_->ApplyBoxes(*input_file_, false, block_list_);
} else {
// TODO(rays) LSTM here.
page_res_ = new PAGE_RES(false,
block_list_, &tesseract_->prev_word_best_choice_);
}
if (tesseract_->tessedit_make_boxes_from_boxes) {
tesseract_->CorrectClassifyWords(page_res_);
return 0;
}
if (truth_cb_ != NULL) {
tesseract_->wordrec_run_blamer.set_value(true);
PageIterator *page_it = new PageIterator(
page_res_, tesseract_, thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_);
truth_cb_->Run(tesseract_->getDict().getUnicharset(),
image_height_, page_it, this->tesseract()->pix_grey());
delete page_it;
}
int result = 0;
if (tesseract_->interactive_display_mode) {
#ifndef GRAPHICS_DISABLED
tesseract_->pgeditor_main(rect_width_, rect_height_, page_res_);
#endif // GRAPHICS_DISABLED
// The page_res is invalid after an interactive session, so cleanup
// in a way that lets us continue to the next page without crashing.
delete page_res_;
page_res_ = NULL;
return -1;
} else if (tesseract_->tessedit_train_from_boxes) {
tesseract_->ApplyBoxTraining(*output_file_, page_res_);
} else if (tesseract_->tessedit_ambigs_training) {
FILE *training_output_file = tesseract_->init_recog_training(*input_file_);
// OCR the page segmented into words by tesseract.
tesseract_->recog_training_segmented(
*input_file_, page_res_, monitor, training_output_file);
fclose(training_output_file);
} else {
// Now run the main recognition.
bool wait_for_text = true;
GetBoolVariable("paragraph_text_based", &wait_for_text);
if (!wait_for_text) DetectParagraphs(false);
if (tesseract_->recog_all_words(page_res_, monitor, NULL, NULL, 0)) {
if (wait_for_text) DetectParagraphs(true);
} else {
result = -1;
}
}
return result;
}
/** Tests the chopper by exhaustively running chop_one_blob. */
int TessBaseAPI::RecognizeForChopTest(ETEXT_DESC* monitor) {
if (tesseract_ == NULL)
return -1;
if (thresholder_ == NULL || thresholder_->IsEmpty()) {
tprintf("Please call SetImage before attempting recognition.");
return -1;
}
if (page_res_ != NULL)
ClearResults();
if (FindLines() != 0)
return -1;
// Additional conditions under which chopper test cannot be run
if (tesseract_->interactive_display_mode) return -1;
recognition_done_ = true;
page_res_ = new PAGE_RES(false, block_list_,
&(tesseract_->prev_word_best_choice_));
PAGE_RES_IT page_res_it(page_res_);
while (page_res_it.word() != NULL) {
WERD_RES *word_res = page_res_it.word();
GenericVector<TBOX> boxes;
tesseract_->MaximallyChopWord(boxes, page_res_it.block()->block,
page_res_it.row()->row, word_res);
page_res_it.forward();
}
return 0;
}
void TessBaseAPI::SetInputImage(Pix *pix) {
if (input_image_)
pixDestroy(&input_image_);
input_image_ = NULL;
if (pix)
input_image_ = pixCopy(NULL, pix);
}
Pix* TessBaseAPI::GetInputImage() {
return input_image_;
}
const char * TessBaseAPI::GetInputName() {
if (input_file_)
return input_file_->c_str();
return NULL;
}
const char * TessBaseAPI::GetDatapath() {
return tesseract_->datadir.c_str();
}
int TessBaseAPI::GetSourceYResolution() {
return thresholder_->GetSourceYResolution();
}
// If flist exists, get data from there. Otherwise get data from buf.
// Seems convoluted, but is the easiest way I know of to meet multiple
// goals. Support streaming from stdin, and also work on platforms
// lacking fmemopen.
bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
STRING *buf,
const char* retry_config,
int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number) {
if (!flist && !buf) return false;
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
char pagename[MAX_PATH];
GenericVector<STRING> lines;
if (!flist) {
buf->split('\n', &lines);
if (lines.empty()) return false;
}
// Skip to the requested page number.
for (int i = 0; i < page; i++) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
}
}
// Begin producing output
const char* kUnknownTitle = "";
if (renderer && !renderer->BeginDocument(kUnknownTitle)) {
return false;
}
// Loop over all pages - or just the requested one
while (true) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
} else {
if (page >= lines.size()) break;
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == NULL) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %d : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config,
timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) return false;
if (tessedit_page_number >= 0) break;
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;
}
bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data,
size_t size,
const char* filename,
const char* retry_config,
int timeout_millisec,
TessResultRenderer* renderer,
int tessedit_page_number) {
Pix *pix = NULL;
#ifdef USE_OPENCL
OpenclDevice od;
#endif
int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
for (; ; ++page) {
if (tessedit_page_number >= 0)
page = tessedit_page_number;
#ifdef USE_OPENCL
if ( od.selectedDeviceIsOpenCL() ) {
// FIXME(jbreiden) Not implemented.
pix = od.pixReadMemTiffCl(data, size, page);
} else {
#endif
pix = pixReadMemTiff(data, size, page);
#ifdef USE_OPENCL
}
#endif
if (pix == NULL) break;
tprintf("Page %d\n", page + 1);
char page_str[kMaxIntSize];
snprintf(page_str, kMaxIntSize - 1, "%d", page);
SetVariable("applybox_page", page_str);
bool r = ProcessPage(pix, page, filename, retry_config,
timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) return false;
if (tessedit_page_number >= 0) break;
}
return true;
}
// In the ideal scenario, Tesseract will start working on data as soon
// as it can. For example, if you steam a filelist through stdin, we
// should start the OCR process as soon as the first filename is
// available. This is particularly useful when hooking Tesseract up to
// slow hardware such as a book scanning machine.
//
// Unfortunately there are tradeoffs. You can't seek on stdin. That
// makes automatic detection of datatype (TIFF? filelist? PNG?)
// impractical. So we support a command line flag to explicitly
// identify the scenario that really matters: filelists on
// stdin. We'll still do our best if the user likes pipes. That means
// piling up any data coming into stdin into a memory buffer.
bool TessBaseAPI::ProcessPages(const char* filename,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer) {
PERF_COUNT_START("ProcessPages")
bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
if (stdInput) {
#ifdef WIN32
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
tprintf("ERROR: cin to binary: %s", strerror(errno));
#endif // WIN32
}
if (stream_filelist) {
return ProcessPagesFileList(stdin, NULL, retry_config,
timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// At this point we are officially in autodection territory.
// That means we are going to buffer stdin so that it is
// seekable. To keep code simple we will also buffer data
// coming from a file.
std::string buf;
if (stdInput) {
buf.assign((std::istreambuf_iterator<char>(std::cin)),
(std::istreambuf_iterator<char>()));
} else {
std::ifstream ifs(filename, std::ios::binary);
if (ifs) {
buf.assign((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
} else {
tprintf("ERROR: Can not open input file %s\n", filename);
return false;
}
}
// Here is our autodetection
int format;
const l_uint8 * data = reinterpret_cast<const l_uint8 *>(buf.c_str());
findFileFormatBuffer(data, &format);
// Maybe we have a filelist
if (format == IFF_UNKNOWN) {
STRING s(buf.c_str());
return ProcessPagesFileList(NULL, &s, retry_config,
timeout_millisec, renderer,
tesseract_->tessedit_page_number);
}
// Maybe we have a TIFF which is potentially multipage
bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
format == IFF_TIFF_ZIP);
// Fail early if we can, before producing any output
Pix *pix = NULL;
if (!tiff) {
pix = pixReadMem(data, buf.size());
if (pix == NULL) {
return false;
}
}
// Begin the output
const char* kUnknownTitle = "";
if (renderer && !renderer->BeginDocument(kUnknownTitle)) {
pixDestroy(&pix);
return false;
}
// Produce output
bool r = false;
if (tiff) {
r = ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config,
timeout_millisec, renderer,
tesseract_->tessedit_page_number);
} else {
r = ProcessPage(pix, 0, filename, retry_config,
timeout_millisec, renderer);
pixDestroy(&pix);
}
// End the output
if (!r || (renderer && !renderer->EndDocument())) {
return false;
}
PERF_COUNT_END
return true;
}
bool TessBaseAPI::ProcessPage(Pix* pix, int page_index, const char* filename,
const char* retry_config, int timeout_millisec,
TessResultRenderer* renderer) {
PERF_COUNT_START("ProcessPage")
SetInputName(filename);
SetImage(pix);
bool failed = false;
if (timeout_millisec > 0) {
// Running with a timeout.
ETEXT_DESC monitor;
monitor.cancel = NULL;
monitor.cancel_this = NULL;
monitor.set_deadline_msecs(timeout_millisec);
// Now run the main recognition.
failed = Recognize(&monitor) < 0;
} else if (tesseract_->tessedit_pageseg_mode == PSM_OSD_ONLY ||
tesseract_->tessedit_pageseg_mode == PSM_AUTO_ONLY) {
// Disabled character recognition.
PageIterator* it = AnalyseLayout();
if (it == NULL) {
failed = true;
} else {
delete it;
PERF_COUNT_END
return true;
}
} else {
// Normal layout and character recognition with no timeout.
failed = Recognize(NULL) < 0;
}
if (tesseract_->tessedit_write_images) {
Pix* page_pix = GetThresholdedImage();
pixWrite("tessinput.tif", page_pix, IFF_TIFF_G4);
}
if (failed && retry_config != NULL && retry_config[0] != '\0') {
// Save current config variables before switching modes.
FILE* fp = fopen(kOldVarsFile, "wb");
PrintVariables(fp);
fclose(fp);
// Switch to alternate mode for retry.
ReadConfigFile(retry_config);
SetImage(pix);
Recognize(NULL);
// Restore saved config variables.
ReadConfigFile(kOldVarsFile);
}
if (renderer && !failed) {
failed = !renderer->AddImage(this);
}
PERF_COUNT_END
return !failed;
}
/**
* Get a left-to-right iterator to the results of LayoutAnalysis and/or
* Recognize. The returned iterator must be deleted after use.
*/
LTRResultIterator* TessBaseAPI::GetLTRIterator() {
if (tesseract_ == NULL || page_res_ == NULL)
return NULL;
return new LTRResultIterator(
page_res_, tesseract_,
thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_);
}
/**
* Get a reading-order iterator to the results of LayoutAnalysis and/or
* Recognize. The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
ResultIterator* TessBaseAPI::GetIterator() {
if (tesseract_ == NULL || page_res_ == NULL)
return NULL;
return ResultIterator::StartOfParagraph(LTRResultIterator(
page_res_, tesseract_,
thresholder_->GetScaleFactor(), thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_));
}
/**
* Get a mutable iterator to the results of LayoutAnalysis and/or Recognize.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
MutableIterator* TessBaseAPI::GetMutableIterator() {
if (tesseract_ == NULL || page_res_ == NULL)
return NULL;
return new MutableIterator(page_res_, tesseract_,
thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(),
rect_left_, rect_top_, rect_width_, rect_height_);
}
/** Make a text string from the internal data structures. */
char* TessBaseAPI::GetUTF8Text() {
if (tesseract_ == NULL ||
(!recognition_done_ && Recognize(NULL) < 0))
return NULL;
STRING text("");
ResultIterator *it = GetIterator();
do {
if (it->Empty(RIL_PARA)) continue;
char *para_text = it->GetUTF8Text(RIL_PARA);
text += para_text;
delete []para_text;
} while (it->Next(RIL_PARA));
char* result = new char[text.length() + 1];
strncpy(result, text.string(), text.length() + 1);
delete it;
return result;
}
/**
* Gets the block orientation at the current iterator position.
*/
static tesseract::Orientation GetBlockTextOrientation(const PageIterator *it) {
tesseract::Orientation orientation;
tesseract::WritingDirection writing_direction;
tesseract::TextlineOrder textline_order;
float deskew_angle;
it->Orientation(&orientation, &writing_direction, &textline_order,
&deskew_angle);
return orientation;
}
/**
* Fits a line to the baseline at the given level, and appends its coefficients
* to the hOCR string.
* NOTE: The hOCR spec is unclear on how to specify baseline coefficients for
* rotated textlines. For this reason, on textlines that are not upright, this
* method currently only inserts a 'textangle' property to indicate the rotation
* direction and does not add any baseline information to the hocr string.
*/
static void AddBaselineCoordsTohOCR(const PageIterator *it,
PageIteratorLevel level,
STRING* hocr_str) {
tesseract::Orientation orientation = GetBlockTextOrientation(it);
if (orientation != ORIENTATION_PAGE_UP) {
hocr_str->add_str_int("; textangle ", 360 - orientation * 90);
return;
}
int left, top, right, bottom;
it->BoundingBox(level, &left, &top, &right, &bottom);
// Try to get the baseline coordinates at this level.
int x1, y1, x2, y2;
if (!it->Baseline(level, &x1, &y1, &x2, &y2))
return;
// Following the description of this field of the hOCR spec, we convert the
// baseline coordinates so that "the bottom left of the bounding box is the
// origin".
x1 -= left;
x2 -= left;
y1 -= bottom;
y2 -= bottom;
// Now fit a line through the points so we can extract coefficients for the
// equation: y = p1 x + p0
double p1 = 0;
double p0 = 0;
if (x1 == x2) {
// Problem computing the polynomial coefficients.
return;
}
p1 = (y2 - y1) / static_cast<double>(x2 - x1);
p0 = y1 - static_cast<double>(p1 * x1);
hocr_str->add_str_double("; baseline ", round(p1 * 1000.0) / 1000.0);
hocr_str->add_str_double(" ", round(p0 * 1000.0) / 1000.0);
}
static void AddBoxTohOCR(const PageIterator *it,
PageIteratorLevel level,
STRING* hocr_str) {
int left, top, right, bottom;
it->BoundingBox(level, &left, &top, &right, &bottom);
hocr_str->add_str_int("' title=\"bbox ", left);
hocr_str->add_str_int(" ", top);
hocr_str->add_str_int(" ", right);
hocr_str->add_str_int(" ", bottom);
// Add baseline coordinates for textlines only.
if (level == RIL_TEXTLINE)
AddBaselineCoordsTohOCR(it, level, hocr_str);
*hocr_str += "\">";
}
/**
* Make a HTML-formatted string with hOCR markup from the internal
* data structures.
* page_number is 0-based but will appear in the output as 1-based.
* Image name/input_file_ can be set by SetInputName before calling
* GetHOCRText
* STL removed from original patch submission and refactored by rays.
*/
char* TessBaseAPI::GetHOCRText(int page_number) {
if (tesseract_ == NULL ||
(page_res_ == NULL && Recognize(NULL) < 0))
return NULL;
int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
int page_id = page_number + 1; // hOCR uses 1-based page numbers.
bool font_info = false;
GetBoolVariable("hocr_font_info", &font_info);
STRING hocr_str("");
if (input_file_ == NULL)
SetInputName(NULL);
#ifdef _WIN32
// convert input name from ANSI encoding to utf-8
int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
NULL, NULL);
wchar_t *uni16_str = new WCHAR[str16_len];
str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
uni16_str, str16_len);
int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL,
NULL, NULL, NULL);
char *utf8_str = new char[utf8_len];
WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
utf8_len, NULL, NULL);
*input_file_ = utf8_str;
delete[] uni16_str;
delete[] utf8_str;
#endif
hocr_str.add_str_int(" <div class='ocr_page' id='page_", page_id);
hocr_str += "' title='image \"";
if (input_file_) {
hocr_str += HOcrEscape(input_file_->string());
} else {
hocr_str += "unknown";
}
hocr_str.add_str_int("\"; bbox ", rect_left_);
hocr_str.add_str_int(" ", rect_top_);
hocr_str.add_str_int(" ", rect_width_);
hocr_str.add_str_int(" ", rect_height_);
hocr_str.add_str_int("; ppageno ", page_number);
hocr_str += "'>\n";
ResultIterator *res_it = GetIterator();
while (!res_it->Empty(RIL_BLOCK)) {
if (res_it->Empty(RIL_WORD)) {
res_it->Next(RIL_WORD);
continue;
}
// Open any new block/paragraph/textline.
if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
hocr_str.add_str_int(" <div class='ocr_carea' id='block_", page_id);
hocr_str.add_str_int("_", bcnt);
AddBoxTohOCR(res_it, RIL_BLOCK, &hocr_str);
}
if (res_it->IsAtBeginningOf(RIL_PARA)) {
if (res_it->ParagraphIsLtr()) {
hocr_str.add_str_int("\n <p class='ocr_par' dir='ltr' id='par_",
page_id);
hocr_str.add_str_int("_", pcnt);
} else {
hocr_str.add_str_int("\n <p class='ocr_par' dir='rtl' id='par_",
page_id);
hocr_str.add_str_int("_", pcnt);
}
AddBoxTohOCR(res_it, RIL_PARA, &hocr_str);
}
if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
hocr_str.add_str_int("\n <span class='ocr_line' id='line_", page_id);
hocr_str.add_str_int("_", lcnt);
AddBoxTohOCR(res_it, RIL_TEXTLINE, &hocr_str);
}
// Now, process the word...
hocr_str.add_str_int("<span class='ocrx_word' id='word_", page_id);
hocr_str.add_str_int("_", wcnt);
int left, top, right, bottom;
bool bold, italic, underlined, monospace, serif, smallcaps;
int pointsize, font_id;
const char *font_name;
res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);
font_name = res_it->WordFontAttributes(&bold, &italic, &underlined,
&monospace, &serif, &smallcaps,
&pointsize, &font_id);
hocr_str.add_str_int("' title='bbox ", left);
hocr_str.add_str_int(" ", top);
hocr_str.add_str_int(" ", right);
hocr_str.add_str_int(" ", bottom);
hocr_str.add_str_int("; x_wconf ", res_it->Confidence(RIL_WORD));
if (font_info) {
hocr_str += "; x_font ";
hocr_str += HOcrEscape(font_name);
hocr_str.add_str_int("; x_fsize ", pointsize);
}
hocr_str += "'";
if (res_it->WordRecognitionLanguage()) {
hocr_str += " lang='";
hocr_str += res_it->WordRecognitionLanguage();
hocr_str += "'";
}
switch (res_it->WordDirection()) {
case DIR_LEFT_TO_RIGHT: hocr_str += " dir='ltr'"; break;
case DIR_RIGHT_TO_LEFT: hocr_str += " dir='rtl'"; break;
default: // Do nothing.
break;
}
hocr_str += ">";
bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD);
bool last_word_in_para = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD);
bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD);
if (bold) hocr_str += "<strong>";
if (italic) hocr_str += "<em>";
do {
const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL);
if (grapheme && grapheme[0] != 0) {
if (grapheme[1] == 0) {
hocr_str += HOcrEscape(grapheme);
} else {
hocr_str += grapheme;
}
}
delete []grapheme;
res_it->Next(RIL_SYMBOL);
} while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
if (italic) hocr_str += "</em>";
if (bold) hocr_str += "</strong>";
hocr_str += "</span> ";
wcnt++;
// Close any ending block/paragraph/textline.
if (last_word_in_line) {
hocr_str += "\n </span>";
lcnt++;
}
if (last_word_in_para) {
hocr_str += "\n </p>\n";
pcnt++;
}
if (last_word_in_block) {
hocr_str += " </div>\n";
bcnt++;
}
}
hocr_str += " </div>\n";
char *ret = new char[hocr_str.length() + 1];
strcpy(ret, hocr_str.string());
delete res_it;
return ret;
}
/** The 5 numbers output for each box (the usual 4 and a page number.) */
const int kNumbersPerBlob = 5;
/**
* The number of bytes taken by each number. Since we use inT16 for ICOORD,
* assume only 5 digits max.
*/
const int kBytesPerNumber = 5;
/**
* Multiplier for max expected textlength assumes (kBytesPerNumber + space)
* * kNumbersPerBlob plus the newline. Add to this the
* original UTF8 characters, and one kMaxBytesPerLine for safety.
*/
const int kBytesPerBlob = kNumbersPerBlob * (kBytesPerNumber + 1) + 1;
const int kBytesPerBoxFileLine = (kBytesPerNumber + 1) * kNumbersPerBlob + 1;
/** Max bytes in the decimal representation of inT64. */
const int kBytesPer64BitNumber = 20;
/**
* A maximal single box could occupy kNumbersPerBlob numbers at
* kBytesPer64BitNumber digits (if someone sneaks in a 64 bit value) and a
* space plus the newline and the maximum length of a UNICHAR.
* Test against this on each iteration for safety.
*/
const int kMaxBytesPerLine = kNumbersPerBlob * (kBytesPer64BitNumber + 1) + 1 +
UNICHAR_LEN;
/**
* The recognized text is returned as a char* which is coded
* as a UTF8 box file and must be freed with the delete [] operator.
* page_number is a 0-base page index that will appear in the box file.
*/
char* TessBaseAPI::GetBoxText(int page_number) {
if (tesseract_ == NULL ||
(!recognition_done_ && Recognize(NULL) < 0))
return NULL;
int blob_count;
int utf8_length = TextLength(&blob_count);
int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
kMaxBytesPerLine;
char* result = new char[total_length];
strcpy(result, "\0");
int output_length = 0;
LTRResultIterator* it = GetLTRIterator();
do {
int left, top, right, bottom;
if (it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom)) {
char* text = it->GetUTF8Text(RIL_SYMBOL);
// Tesseract uses space for recognition failure. Fix to a reject
// character, kTesseractReject so we don't create illegal box files.
for (int i = 0; text[i] != '\0'; ++i) {
if (text[i] == ' ')
text[i] = kTesseractReject;
}
snprintf(result + output_length, total_length - output_length,
"%s %d %d %d %d %d\n",
text, left, image_height_ - bottom,
right, image_height_ - top, page_number);
output_length += strlen(result + output_length);
delete [] text;
// Just in case...
if (output_length + kMaxBytesPerLine > total_length)
break;
}
} while (it->Next(RIL_SYMBOL));
delete it;
return result;
}
/**
* Conversion table for non-latin characters.
* Maps characters out of the latin set into the latin set.
* TODO(rays) incorporate this translation into unicharset.
*/
const int kUniChs[] = {
0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
};
/** Latin chars corresponding to the unicode chars above. */
const int kLatinChs[] = {
0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
};
/**
* The recognized text is returned as a char* which is coded
* as UNLV format Latin-1 with specific reject and suspect codes
* and must be freed with the delete [] operator.
*/
char* TessBaseAPI::GetUNLVText() {
if (tesseract_ == NULL ||
(!recognition_done_ && Recognize(NULL) < 0))
return NULL;
bool tilde_crunch_written = false;
bool last_char_was_newline = true;
bool last_char_was_tilde = false;
int total_length = TextLength(NULL);
PAGE_RES_IT page_res_it(page_res_);
char* result = new char[total_length];
char* ptr = result;
for (page_res_it.restart_page(); page_res_it.word () != NULL;
page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
// Process the current word.
if (word->unlv_crunch_mode != CR_NONE) {
if (word->unlv_crunch_mode != CR_DELETE &&
(!tilde_crunch_written ||
(word->unlv_crunch_mode == CR_KEEP_SPACE &&
word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)))) {
if (!word->word->flag(W_BOL) &&
word->word->space() > 0 &&
!word->word->flag(W_FUZZY_NON) &&
!word->word->flag(W_FUZZY_SP)) {
/* Write a space to separate from preceeding good text */
*ptr++ = ' ';
last_char_was_tilde = false;
}
if (!last_char_was_tilde) {
// Write a reject char.
last_char_was_tilde = true;
*ptr++ = kUNLVReject;
tilde_crunch_written = true;
last_char_was_newline = false;
}
}
} else {
// NORMAL PROCESSING of non tilde crunched words.
tilde_crunch_written = false;
tesseract_->set_unlv_suspects(word);
const char* wordstr = word->best_choice->unichar_string().string();
const STRING& lengths = word->best_choice->unichar_lengths();
int length = lengths.length();
int i = 0;
int offset = 0;
if (last_char_was_tilde &&
word->word->space() == 0 && wordstr[offset] == ' ') {
// Prevent adjacent tilde across words - we know that adjacent tildes
// within words have been removed.
// Skip the first character.
offset = lengths[i++];
}
if (i < length && wordstr[offset] != 0) {
if (!last_char_was_newline)
*ptr++ = ' ';
else
last_char_was_newline = false;
for (; i < length; offset += lengths[i++]) {
if (wordstr[offset] == ' ' ||
wordstr[offset] == kTesseractReject) {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
} else {
if (word->reject_map[i].rejected())
*ptr++ = kUNLVSuspect;
UNICHAR ch(wordstr + offset, lengths[i]);
int uni_ch = ch.first_uni();
for (int j = 0; kUniChs[j] != 0; ++j) {
if (kUniChs[j] == uni_ch) {
uni_ch = kLatinChs[j];
break;
}
}
if (uni_ch <= 0xff) {
*ptr++ = static_cast<char>(uni_ch);
last_char_was_tilde = false;
} else {
*ptr++ = kUNLVReject;
last_char_was_tilde = true;
}
}
}
}
}
if (word->word->flag(W_EOL) && !last_char_was_newline) {
/* Add a new line output */
*ptr++ = '\n';
tilde_crunch_written = false;
last_char_was_newline = true;
last_char_was_tilde = false;
}
}
*ptr++ = '\n';
*ptr = '\0';
return result;
}
/** Returns the average word confidence for Tesseract page result. */
int TessBaseAPI::MeanTextConf() {
int* conf = AllWordConfidences();
if (!conf) return 0;
int sum = 0;
int *pt = conf;
while (*pt >= 0) sum += *pt++;
if (pt != conf) sum /= pt - conf;
delete [] conf;
return sum;
}
/** Returns an array of all word confidences, terminated by -1. */
int* TessBaseAPI::AllWordConfidences() {
if (tesseract_ == NULL ||
(!recognition_done_ && Recognize(NULL) < 0))
return NULL;
int n_word = 0;
PAGE_RES_IT res_it(page_res_);
for (res_it.restart_page(); res_it.word() != NULL; res_it.forward())
n_word++;
int* conf = new int[n_word+1];
n_word = 0;
for (res_it.restart_page(); res_it.word() != NULL; res_it.forward()) {
WERD_RES *word = res_it.word();
WERD_CHOICE* choice = word->best_choice;
int w_conf = static_cast<int>(100 + 5 * choice->certainty());
// This is the eq for converting Tesseract confidence to 1..100
if (w_conf < 0) w_conf = 0;
if (w_conf > 100) w_conf = 100;
conf[n_word++] = w_conf;
}
conf[n_word] = -1;
return conf;
}
/**
* Applies the given word to the adaptive classifier if possible.
* The word must be SPACE-DELIMITED UTF-8 - l i k e t h i s , so it can
* tell the boundaries of the graphemes.
* Assumes that SetImage/SetRectangle have been used to set the image
* to the given word. The mode arg should be PSM_SINGLE_WORD or
* PSM_CIRCLE_WORD, as that will be used to control layout analysis.
* The currently set PageSegMode is preserved.
* Returns false if adaption was not possible for some reason.
*/
bool TessBaseAPI::AdaptToWordStr(PageSegMode mode, const char* wordstr) {
int debug = 0;
GetIntVariable("applybox_debug", &debug);
bool success = true;
PageSegMode current_psm = GetPageSegMode();
SetPageSegMode(mode);
SetVariable("classify_enable_learning", "0");
char* text = GetUTF8Text();
if (debug) {
tprintf("Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
}
if (text != NULL) {
PAGE_RES_IT it(page_res_);
WERD_RES* word_res = it.word();
if (word_res != NULL) {
word_res->word->set_text(wordstr);
} else {
success = false;
}
// Check to see if text matches wordstr.
int w = 0;
int t = 0;
for (t = 0; text[t] != '\0'; ++t) {
if (text[t] == '\n' || text[t] == ' ')
continue;
while (wordstr[w] != '\0' && wordstr[w] == ' ')
++w;
if (text[t] != wordstr[w])
break;
++w;
}
if (text[t] != '\0' || wordstr[w] != '\0') {
// No match.
delete page_res_;
GenericVector<TBOX> boxes;
page_res_ = tesseract_->SetupApplyBoxes(boxes, block_list_);
tesseract_->ReSegmentByClassification(page_res_);
tesseract_->TidyUp(page_res_);
PAGE_RES_IT pr_it(page_res_);
if (pr_it.word() == NULL)
success = false;
else
word_res = pr_it.word();
} else {
word_res->BestChoiceToCorrectText();
}
if (success) {
tesseract_->EnableLearning = true;
tesseract_->LearnWord(NULL, word_res);
}
delete [] text;
} else {
success = false;
}
SetPageSegMode(current_psm);
return success;
}
/**
* Free up recognition results and any stored image data, without actually
* freeing any recognition data that would be time-consuming to reload.
* Afterwards, you must call SetImage or TesseractRect before doing
* any Recognize or Get* operation.
*/
void TessBaseAPI::Clear() {
if (thresholder_ != NULL)
thresholder_->Clear();
ClearResults();
SetInputImage(NULL);
}
/**
* Close down tesseract and free up all memory. End() is equivalent to
* destructing and reconstructing your TessBaseAPI.
* Once End() has been used, none of the other API functions may be used
* other than Init and anything declared above it in the class definition.
*/
void TessBaseAPI::End() {
if (thresholder_ != NULL) {
delete thresholder_;
thresholder_ = NULL;
}
if (page_res_ != NULL) {
delete page_res_;
page_res_ = NULL;
}
if (block_list_ != NULL) {
delete block_list_;
block_list_ = NULL;
}
if (paragraph_models_ != NULL) {
paragraph_models_->delete_data_pointers();
delete paragraph_models_;
paragraph_models_ = NULL;
}
if (tesseract_ != NULL) {
delete tesseract_;
if (osd_tesseract_ == tesseract_)
osd_tesseract_ = NULL;
tesseract_ = NULL;
}
if (osd_tesseract_ != NULL) {
delete osd_tesseract_;
osd_tesseract_ = NULL;
}
if (equ_detect_ != NULL) {
delete equ_detect_;
equ_detect_ = NULL;
}
if (input_file_ != NULL) {
delete input_file_;
input_file_ = NULL;
}
if (input_image_ != NULL) {
pixDestroy(&input_image_);
input_image_ = NULL;
}
if (output_file_ != NULL) {
delete output_file_;
output_file_ = NULL;
}
if (datapath_ != NULL) {
delete datapath_;
datapath_ = NULL;
}
if (language_ != NULL) {
delete language_;
language_ = NULL;
}
}
// Clear any library-level memory caches.
// There are a variety of expensive-to-load constant data structures (mostly
// language dictionaries) that are cached globally -- surviving the Init()
// and End() of individual TessBaseAPI's. This function allows the clearing
// of these caches.
void TessBaseAPI::ClearPersistentCache() {
Dict::GlobalDawgCache()->DeleteUnusedDawgs();
}
/**
* Check whether a word is valid according to Tesseract's language model
* returns 0 if the word is invalid, non-zero if valid
*/
int TessBaseAPI::IsValidWord(const char *word) {
return tesseract_->getDict().valid_word(word);
}
// Returns true if utf8_character is defined in the UniCharset.
bool TessBaseAPI::IsValidCharacter(const char *utf8_character) {
return tesseract_->unicharset.contains_unichar(utf8_character);
}
// TODO(rays) Obsolete this function and replace with a more aptly named
// function that returns image coordinates rather than tesseract coordinates.
bool TessBaseAPI::GetTextDirection(int* out_offset, float* out_slope) {
PageIterator* it = AnalyseLayout();
if (it == NULL) {
return false;
}
int x1, x2, y1, y2;
it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2);
// Calculate offset and slope (NOTE: Kind of ugly)
if (x2 <= x1) x2 = x1 + 1;
// Convert the point pair to slope/offset of the baseline (in image coords.)
*out_slope = static_cast<float>(y2 - y1) / (x2 - x1);
*out_offset = static_cast<int>(y1 - *out_slope * x1);
// Get the y-coord of the baseline at the left and right edges of the
// textline's bounding box.
int left, top, right, bottom;
if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) {
delete it;
return false;
}
int left_y = IntCastRounded(*out_slope * left + *out_offset);
int right_y = IntCastRounded(*out_slope * right + *out_offset);
// Shift the baseline down so it passes through the nearest bottom-corner
// of the textline's bounding box. This is the difference between the y
// at the lowest (max) edge of the box and the actual box bottom.
*out_offset += bottom - MAX(left_y, right_y);
// Switch back to bottom-up tesseract coordinates. Requires negation of
// the slope and height - offset for the offset.
*out_slope = -*out_slope;
*out_offset = rect_height_ - *out_offset;
delete it;
return true;
}
/** Sets Dict::letter_is_okay_ function to point to the given function. */
void TessBaseAPI::SetDictFunc(DictFunc f) {
if (tesseract_ != NULL) {
tesseract_->getDict().letter_is_okay_ = f;
}
}
/**
* Sets Dict::probability_in_context_ function to point to the given
* function.
*
* @param f A single function that returns the probability of the current
* "character" (in general a utf-8 string), given the context of a previous
* utf-8 string.
*/
void TessBaseAPI::SetProbabilityInContextFunc(ProbabilityInContextFunc f) {
if (tesseract_ != NULL) {
tesseract_->getDict().probability_in_context_ = f;
// Set it for the sublangs too.
int num_subs = tesseract_->num_sub_langs();
for (int i = 0; i < num_subs; ++i) {
tesseract_->get_sub_lang(i)->getDict().probability_in_context_ = f;
}
}
}
/** Sets Wordrec::fill_lattice_ function to point to the given function. */
void TessBaseAPI::SetFillLatticeFunc(FillLatticeFunc f) {
if (tesseract_ != NULL) tesseract_->fill_lattice_ = f;
}
/** Common code for setting the image. */
bool TessBaseAPI::InternalSetImage() {
if (tesseract_ == NULL) {
tprintf("Please call Init before attempting to set an image.");
return false;
}
if (thresholder_ == NULL)
thresholder_ = new ImageThresholder;
ClearResults();
return true;
}
/**
* Run the thresholder to make the thresholded image, returned in pix,
* which must not be NULL. *pix must be initialized to NULL, or point
* to an existing pixDestroyable Pix.
* The usual argument to Threshold is Tesseract::mutable_pix_binary().
*/
void TessBaseAPI::Threshold(Pix** pix) {
ASSERT_HOST(pix != NULL);
if (*pix != NULL)
pixDestroy(pix);
// Zero resolution messes up the algorithms, so make sure it is credible.
int y_res = thresholder_->GetScaledYResolution();
if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) {
// Use the minimum default resolution, as it is safer to under-estimate
// than over-estimate resolution.
thresholder_->SetSourceYResolution(kMinCredibleResolution);
}
PageSegMode pageseg_mode =
static_cast<PageSegMode>(
static_cast<int>(tesseract_->tessedit_pageseg_mode));
thresholder_->ThresholdToPix(pageseg_mode, pix);
thresholder_->GetImageSizes(&rect_left_, &rect_top_,
&rect_width_, &rect_height_,
&image_width_, &image_height_);
if (!thresholder_->IsBinary()) {
tesseract_->set_pix_thresholds(thresholder_->GetPixRectThresholds());
tesseract_->set_pix_grey(thresholder_->GetPixRectGrey());
} else {
tesseract_->set_pix_thresholds(NULL);
tesseract_->set_pix_grey(NULL);
}
// Set the internal resolution that is used for layout parameters from the
// estimated resolution, rather than the image resolution, which may be
// fabricated, but we will use the image resolution, if there is one, to
// report output point sizes.
int estimated_res = ClipToRange(thresholder_->GetScaledEstimatedResolution(),
kMinCredibleResolution,
kMaxCredibleResolution);
if (estimated_res != thresholder_->GetScaledEstimatedResolution()) {
tprintf("Estimated resolution %d out of range! Corrected to %d\n",
thresholder_->GetScaledEstimatedResolution(), estimated_res);
}
tesseract_->set_source_resolution(estimated_res);
SavePixForCrash(estimated_res, *pix);
}
/** Find lines from the image making the BLOCK_LIST. */
int TessBaseAPI::FindLines() {
if (thresholder_ == NULL || thresholder_->IsEmpty()) {
tprintf("Please call SetImage before attempting recognition.");
return -1;
}
if (recognition_done_)
ClearResults();
if (!block_list_->empty()) {
return 0;
}
if (tesseract_ == NULL) {
tesseract_ = new Tesseract;
tesseract_->InitAdaptiveClassifier(false);
}
if (tesseract_->pix_binary() == NULL)
Threshold(tesseract_->mutable_pix_binary());
if (tesseract_->ImageWidth() > MAX_INT16 ||
tesseract_->ImageHeight() > MAX_INT16) {
tprintf("Image too large: (%d, %d)\n",
tesseract_->ImageWidth(), tesseract_->ImageHeight());
return -1;
}
tesseract_->PrepareForPageseg();
if (tesseract_->textord_equation_detect) {
if (equ_detect_ == NULL && datapath_ != NULL) {
equ_detect_ = new EquationDetect(datapath_->string(), NULL);
}
tesseract_->SetEquationDetect(equ_detect_);
}
Tesseract* osd_tess = osd_tesseract_;
OSResults osr;
if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == NULL) {
if (strcmp(language_->string(), "osd") == 0) {
osd_tess = tesseract_;
} else {
osd_tesseract_ = new Tesseract;
if (osd_tesseract_->init_tesseract(
datapath_->string(), NULL, "osd", OEM_TESSERACT_ONLY,
NULL, 0, NULL, NULL, false) == 0) {
osd_tess = osd_tesseract_;
osd_tesseract_->set_source_resolution(
thresholder_->GetSourceYResolution());
} else {
tprintf("Warning: Auto orientation and script detection requested,"
" but osd language failed to load\n");
delete osd_tesseract_;
osd_tesseract_ = NULL;
}
}
}
if (tesseract_->SegmentPage(input_file_, block_list_, osd_tess, &osr) < 0)
return -1;
// If Devanagari is being recognized, we use different images for page seg
// and for OCR.
tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
return 0;
}
/** Delete the pageres and clear the block list ready for a new page. */
void TessBaseAPI::ClearResults() {
if (tesseract_ != NULL) {
tesseract_->Clear();
}
if (page_res_ != NULL) {
delete page_res_;
page_res_ = NULL;
}
recognition_done_ = false;
if (block_list_ == NULL)
block_list_ = new BLOCK_LIST;
else
block_list_->clear();
if (paragraph_models_ != NULL) {
paragraph_models_->delete_data_pointers();
delete paragraph_models_;
paragraph_models_ = NULL;
}
SavePixForCrash(0, NULL);
}
/**
* Return the length of the output text string, as UTF8, assuming
* liberally two spacing marks after each word (as paragraphs end with two
* newlines), and assuming a single character reject marker for each rejected
* character.
* Also return the number of recognized blobs in blob_count.
*/
int TessBaseAPI::TextLength(int* blob_count) {
if (tesseract_ == NULL || page_res_ == NULL)
return 0;
PAGE_RES_IT page_res_it(page_res_);
int total_length = 2;
int total_blobs = 0;
// Iterate over the data structures to extract the recognition result.
for (page_res_it.restart_page(); page_res_it.word () != NULL;
page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
WERD_CHOICE* choice = word->best_choice;
if (choice != NULL) {
total_blobs += choice->length() + 2;
total_length += choice->unichar_string().length() + 2;
for (int i = 0; i < word->reject_map.length(); ++i) {
if (word->reject_map[i].rejected())
++total_length;
}
}
}
if (blob_count != NULL)
*blob_count = total_blobs;
return total_length;
}
/**
* Estimates the Orientation And Script of the image.
* Returns true if the image was processed successfully.
*/
bool TessBaseAPI::DetectOS(OSResults* osr) {
if (tesseract_ == NULL)
return false;
ClearResults();
if (tesseract_->pix_binary() == NULL)
Threshold(tesseract_->mutable_pix_binary());
if (input_file_ == NULL)
input_file_ = new STRING(kInputFile);
return orientation_and_script_detection(*input_file_, osr, tesseract_);
}
void TessBaseAPI::set_min_orientation_margin(double margin) {
tesseract_->min_orientation_margin.set_value(margin);
}
/**
* Return text orientation of each block as determined in an earlier page layout
* analysis operation. Orientation is returned as the number of ccw 90-degree
* rotations (in [0..3]) required to make the text in the block upright
* (readable). Note that this may not necessary be the block orientation
* preferred for recognition (such as the case of vertical CJK text).
*
* Also returns whether the text in the block is believed to have vertical
* writing direction (when in an upright page orientation).
*
* The returned array is of length equal to the number of text blocks, which may
* be less than the total number of blocks. The ordering is intended to be
* consistent with GetTextLines().
*/
void TessBaseAPI::GetBlockTextOrientations(int** block_orientation,
bool** vertical_writing) {
delete[] *block_orientation;
*block_orientation = NULL;
delete[] *vertical_writing;
*vertical_writing = NULL;
BLOCK_IT block_it(block_list_);
block_it.move_to_first();
int num_blocks = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
if (!block_it.data()->poly_block()->IsText()) {
continue;
}
++num_blocks;
}
if (!num_blocks) {
tprintf("WARNING: Found no blocks\n");
return;
}
*block_orientation = new int[num_blocks];
*vertical_writing = new bool[num_blocks];
block_it.move_to_first();
int i = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list();
block_it.forward()) {
if (!block_it.data()->poly_block()->IsText()) {
continue;
}
FCOORD re_rotation = block_it.data()->re_rotation();
float re_theta = re_rotation.angle();
FCOORD classify_rotation = block_it.data()->classify_rotation();
float classify_theta = classify_rotation.angle();
double rot_theta = - (re_theta - classify_theta) * 2.0 / PI;
if (rot_theta < 0) rot_theta += 4;
int num_rotations = static_cast<int>(rot_theta + 0.5);
(*block_orientation)[i] = num_rotations;
// The classify_rotation is non-zero only if the text has vertical
// writing direction.
(*vertical_writing)[i] = classify_rotation.y() != 0.0f;
++i;
}
}
// ____________________________________________________________________________
// Ocropus add-ons.
/** Find lines from the image making the BLOCK_LIST. */
BLOCK_LIST* TessBaseAPI::FindLinesCreateBlockList() {
FindLines();
BLOCK_LIST* result = block_list_;
block_list_ = NULL;
return result;
}
/**
* Delete a block list.
* This is to keep BLOCK_LIST pointer opaque
* and let go of including the other headers.
*/
void TessBaseAPI::DeleteBlockList(BLOCK_LIST *block_list) {
delete block_list;
}
ROW *TessBaseAPI::MakeTessOCRRow(float baseline,
float xheight,
float descender,
float ascender) {
inT32 xstarts[] = {-32000};
double quad_coeffs[] = {0, 0, baseline};
return new ROW(1,
xstarts,
quad_coeffs,
xheight,
ascender - (baseline + xheight),
descender - baseline,
0,
0);
}
/** Creates a TBLOB* from the whole pix. */
TBLOB *TessBaseAPI::MakeTBLOB(Pix *pix) {
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
BLOCK block("a character", TRUE, 0, 0, 0, 0, width, height);
// Create C_BLOBs from the page
extract_edges(pix, &block);
// Merge all C_BLOBs
C_BLOB_LIST *list = block.blob_list();
C_BLOB_IT c_blob_it(list);
if (c_blob_it.empty())
return NULL;
// Move all the outlines to the first blob.
C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
for (c_blob_it.forward();
!c_blob_it.at_first();
c_blob_it.forward()) {
C_BLOB *c_blob = c_blob_it.data();
ol_it.add_list_after(c_blob->out_list());
}
// Convert the first blob to the output TBLOB.
return TBLOB::PolygonalCopy(false, c_blob_it.data());
}
/**
* This method baseline normalizes a TBLOB in-place. The input row is used
* for normalization. The denorm is an optional parameter in which the
* normalization-antidote is returned.
*/
void TessBaseAPI::NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode) {
TBOX box = tblob->bounding_box();
float x_center = (box.left() + box.right()) / 2.0f;
float baseline = row->base_line(x_center);
float scale = kBlnXHeight / row->x_height();
tblob->Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
0.0f, static_cast<float>(kBlnBaselineOffset), false, NULL);
}
/**
* Return a TBLOB * from the whole pix.
* To be freed later with delete.
*/
TBLOB *make_tesseract_blob(float baseline, float xheight,
float descender, float ascender,
bool numeric_mode, Pix* pix) {
TBLOB *tblob = TessBaseAPI::MakeTBLOB(pix);
// Normalize TBLOB
ROW *row =
TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender);
TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode);
delete row;
return tblob;
}
/**
* Adapt to recognize the current image as the given character.
* The image must be preloaded into pix_binary_ and be just an image
* of a single character.
*/
void TessBaseAPI::AdaptToCharacter(const char *unichar_repr,
int length,
float baseline,
float xheight,
float descender,
float ascender) {
UNICHAR_ID id = tesseract_->unicharset.unichar_to_id(unichar_repr, length);
TBLOB *blob = make_tesseract_blob(baseline, xheight, descender, ascender,
tesseract_->classify_bln_numeric_mode,
tesseract_->pix_binary());
float threshold;
float best_rating = -100;
// Classify to get a raw choice.
BLOB_CHOICE_LIST choices;
tesseract_->AdaptiveClassifier(blob, &choices);
BLOB_CHOICE_IT choice_it;
choice_it.set_to_list(&choices);
for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
choice_it.forward()) {
if (choice_it.data()->rating() > best_rating) {
best_rating = choice_it.data()->rating();
}
}
threshold = tesseract_->matcher_good_threshold;
if (blob->outlines)
tesseract_->AdaptToChar(blob, id, kUnknownFontinfoId, threshold);
delete blob;
}
PAGE_RES* TessBaseAPI::RecognitionPass1(BLOCK_LIST* block_list) {
PAGE_RES *page_res = new PAGE_RES(false, block_list,
&(tesseract_->prev_word_best_choice_));
tesseract_->recog_all_words(page_res, NULL, NULL, NULL, 1);
return page_res;
}
PAGE_RES* TessBaseAPI::RecognitionPass2(BLOCK_LIST* block_list,
PAGE_RES* pass1_result) {
if (!pass1_result)
pass1_result = new PAGE_RES(false, block_list,
&(tesseract_->prev_word_best_choice_));
tesseract_->recog_all_words(pass1_result, NULL, NULL, NULL, 2);
return pass1_result;
}
void TessBaseAPI::DetectParagraphs(bool after_text_recognition) {
int debug_level = 0;
GetIntVariable("paragraph_debug_level", &debug_level);
if (paragraph_models_ == NULL)
paragraph_models_ = new GenericVector<ParagraphModel*>;
MutableIterator *result_it = GetMutableIterator();
do { // Detect paragraphs for this block
GenericVector<ParagraphModel *> models;
::tesseract::DetectParagraphs(debug_level, after_text_recognition,
result_it, &models);
*paragraph_models_ += models;
} while (result_it->Next(RIL_BLOCK));
delete result_it;
}
struct TESS_CHAR : ELIST_LINK {
char *unicode_repr;
int length; // of unicode_repr
float cost;
TBOX box;
TESS_CHAR(float _cost, const char *repr, int len = -1) : cost(_cost) {
length = (len == -1 ? strlen(repr) : len);
unicode_repr = new char[length + 1];
strncpy(unicode_repr, repr, length);
}
TESS_CHAR() { // Satisfies ELISTIZE.
}
~TESS_CHAR() {
delete [] unicode_repr;
}
};
ELISTIZEH(TESS_CHAR)
ELISTIZE(TESS_CHAR)
static void add_space(TESS_CHAR_IT* it) {
TESS_CHAR *t = new TESS_CHAR(0, " ");
it->add_after_then_move(t);
}
static float rating_to_cost(float rating) {
rating = 100 + rating;
// cuddled that to save from coverage profiler
// (I have never seen ratings worse than -100,
// but the check won't hurt)
if (rating < 0) rating = 0;
return rating;
}
/**
* Extract the OCR results, costs (penalty points for uncertainty),
* and the bounding boxes of the characters.
*/
static void extract_result(TESS_CHAR_IT* out,
PAGE_RES* page_res) {
PAGE_RES_IT page_res_it(page_res);
int word_count = 0;
while (page_res_it.word() != NULL) {
WERD_RES *word = page_res_it.word();
const char *str = word->best_choice->unichar_string().string();
const char *len = word->best_choice->unichar_lengths().string();
TBOX real_rect = word->word->bounding_box();
if (word_count)
add_space(out);
int n = strlen(len);
for (int i = 0; i < n; i++) {
TESS_CHAR *tc = new TESS_CHAR(rating_to_cost(word->best_choice->rating()),
str, *len);
tc->box = real_rect.intersection(word->box_word->BlobBox(i));
out->add_after_then_move(tc);
str += *len;
len++;
}
page_res_it.forward();
word_count++;
}
}
/**
* Extract the OCR results, costs (penalty points for uncertainty),
* and the bounding boxes of the characters.
*/
int TessBaseAPI::TesseractExtractResult(char** text,
int** lengths,
float** costs,
int** x0,
int** y0,
int** x1,
int** y1,
PAGE_RES* page_res) {
TESS_CHAR_LIST tess_chars;
TESS_CHAR_IT tess_chars_it(&tess_chars);
extract_result(&tess_chars_it, page_res);
tess_chars_it.move_to_first();
int n = tess_chars.length();
int text_len = 0;
*lengths = new int[n];
*costs = new float[n];
*x0 = new int[n];
*y0 = new int[n];
*x1 = new int[n];
*y1 = new int[n];
int i = 0;
for (tess_chars_it.mark_cycle_pt();
!tess_chars_it.cycled_list();
tess_chars_it.forward(), i++) {
TESS_CHAR *tc = tess_chars_it.data();
text_len += (*lengths)[i] = tc->length;
(*costs)[i] = tc->cost;
(*x0)[i] = tc->box.left();
(*y0)[i] = tc->box.bottom();
(*x1)[i] = tc->box.right();
(*y1)[i] = tc->box.top();
}
char *p = *text = new char[text_len];
tess_chars_it.move_to_first();
for (tess_chars_it.mark_cycle_pt();
!tess_chars_it.cycled_list();
tess_chars_it.forward()) {
TESS_CHAR *tc = tess_chars_it.data();
strncpy(p, tc->unicode_repr, tc->length);
p += tc->length;
}
return n;
}
/** This method returns the features associated with the input blob. */
// The resulting features are returned in int_features, which must be
// of size MAX_NUM_INT_FEATURES. The number of features is returned in
// num_features (or 0 if there was a failure).
// On return feature_outline_index is filled with an index of the outline
// corresponding to each feature in int_features.
// TODO(rays) Fix the caller to out outline_counts instead.
void TessBaseAPI::GetFeaturesForBlob(TBLOB* blob,
INT_FEATURE_STRUCT* int_features,
int* num_features,
int* feature_outline_index) {
GenericVector<int> outline_counts;
GenericVector<INT_FEATURE_STRUCT> bl_features;
GenericVector<INT_FEATURE_STRUCT> cn_features;
INT_FX_RESULT_STRUCT fx_info;
tesseract_->ExtractFeatures(*blob, false, &bl_features,
&cn_features, &fx_info, &outline_counts);
if (cn_features.size() == 0 || cn_features.size() > MAX_NUM_INT_FEATURES) {
*num_features = 0;
return; // Feature extraction failed.
}
*num_features = cn_features.size();
memcpy(int_features, &cn_features[0], *num_features * sizeof(cn_features[0]));
// TODO(rays) Pass outline_counts back and simplify the calling code.
if (feature_outline_index != NULL) {
int f = 0;
for (int i = 0; i < outline_counts.size(); ++i) {
while (f < outline_counts[i])
feature_outline_index[f++] = i;
}
}
}
// This method returns the row to which a box of specified dimensions would
// belong. If no good match is found, it returns NULL.
ROW* TessBaseAPI::FindRowForBox(BLOCK_LIST* blocks,
int left, int top, int right, int bottom) {
TBOX box(left, bottom, right, top);
BLOCK_IT b_it(blocks);
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOCK* block = b_it.data();
if (!box.major_overlap(block->bounding_box()))
continue;
ROW_IT r_it(block->row_list());
for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
ROW* row = r_it.data();
if (!box.major_overlap(row->bounding_box()))
continue;
WERD_IT w_it(row->word_list());
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD* word = w_it.data();
if (box.major_overlap(word->bounding_box()))
return row;
}
}
}
return NULL;
}
/** Method to run adaptive classifier on a blob. */
void TessBaseAPI::RunAdaptiveClassifier(TBLOB* blob,
int num_max_matches,
int* unichar_ids,
float* ratings,
int* num_matches_returned) {
BLOB_CHOICE_LIST* choices = new BLOB_CHOICE_LIST;
tesseract_->AdaptiveClassifier(blob, choices);
BLOB_CHOICE_IT choices_it(choices);
int& index = *num_matches_returned;
index = 0;
for (choices_it.mark_cycle_pt();
!choices_it.cycled_list() && index < num_max_matches;
choices_it.forward()) {
BLOB_CHOICE* choice = choices_it.data();
unichar_ids[index] = choice->unichar_id();
ratings[index] = choice->rating();
++index;
}
*num_matches_returned = index;
delete choices;
}
/** This method returns the string form of the specified unichar. */
const char* TessBaseAPI::GetUnichar(int unichar_id) {
return tesseract_->unicharset.id_to_unichar(unichar_id);
}
/** Return the pointer to the i-th dawg loaded into tesseract_ object. */
const Dawg *TessBaseAPI::GetDawg(int i) const {
if (tesseract_ == NULL || i >= NumDawgs()) return NULL;
return tesseract_->getDict().GetDawg(i);
}
/** Return the number of dawgs loaded into tesseract_ object. */
int TessBaseAPI::NumDawgs() const {
return tesseract_ == NULL ? 0 : tesseract_->getDict().NumDawgs();
}
/** Return a pointer to underlying CubeRecoContext object if present. */
CubeRecoContext *TessBaseAPI::GetCubeRecoContext() const {
return (tesseract_ == NULL) ? NULL : tesseract_->GetCubeRecoContext();
}
/** Escape a char string - remove <>&"' with HTML codes. */
STRING HOcrEscape(const char* text) {
STRING ret;
const char *ptr;
for (ptr = text; *ptr; ptr++) {
switch (*ptr) {
case '<': ret += "<"; break;
case '>': ret += ">"; break;
case '&': ret += "&"; break;
case '"': ret += """; break;
case '\'': ret += "'"; break;
default: ret += *ptr;
}
}
return ret;
}
} // namespace tesseract.
| C++ |
///////////////////////////////////////////////////////////////////////
// File: renderer.h
// Description: Rendering interface to inject into TessBaseAPI
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_API_RENDERER_H__
#define TESSERACT_API_RENDERER_H__
// To avoid collision with other typenames include the ABSOLUTE MINIMUM
// complexity of includes here. Use forward declarations wherever possible
// and hide includes of complex types in baseapi.cpp.
#include "genericvector.h"
#include "platform.h"
#include "publictypes.h"
namespace tesseract {
class TessBaseAPI;
/**
* Interface for rendering tesseract results into a document, such as text,
* HOCR or pdf. This class is abstract. Specific classes handle individual
* formats. This interface is then used to inject the renderer class into
* tesseract when processing images.
*
* For simplicity implementing this with tesesract version 3.01,
* the renderer contains document state that is cleared from document
* to document just as the TessBaseAPI is. This way the base API can just
* delegate its rendering functionality to injected renderers, and the
* renderers can manage the associated state needed for the specific formats
* in addition to the heuristics for producing it.
*/
class TESS_API TessResultRenderer {
public:
virtual ~TessResultRenderer();
// Takes ownership of pointer so must be new'd instance.
// Renderers aren't ordered, but appends the sequences of next parameter
// and existing next(). The renderers should be unique across both lists.
void insert(TessResultRenderer* next);
// Returns the next renderer or NULL.
TessResultRenderer* next() { return next_; }
/**
* Starts a new document with the given title.
* This clears the contents of the output data.
*/
bool BeginDocument(const char* title);
/**
* Adds the recognized text from the source image to the current document.
* Invalid if BeginDocument not yet called.
*
* Note that this API is a bit weird but is designed to fit into the
* current TessBaseAPI implementation where the api has lots of state
* information that we might want to add in.
*/
bool AddImage(TessBaseAPI* api);
/**
* Finishes the document and finalizes the output data
* Invalid if BeginDocument not yet called.
*/
bool EndDocument();
const char* file_extension() const { return file_extension_; }
const char* title() const { return title_; }
/**
* Returns the index of the last image given to AddImage
* (i.e. images are incremented whether the image succeeded or not)
*
* This is always defined. It means either the number of the
* current image, the last image ended, or in the completed document
* depending on when in the document lifecycle you are looking at it.
* Will return -1 if a document was never started.
*/
int imagenum() const { return imagenum_; }
protected:
/**
* Called by concrete classes.
*
* outputbase is the name of the output file excluding
* extension. For example, "/path/to/chocolate-chip-cookie-recipe"
*
* extension indicates the file extension to be used for output
* files. For example "pdf" will produce a .pdf file, and "hocr"
* will produce .hocr files.
*/
TessResultRenderer(const char *outputbase,
const char* extension);
// Hook for specialized handling in BeginDocument()
virtual bool BeginDocumentHandler();
// This must be overriden to render the OCR'd results
virtual bool AddImageHandler(TessBaseAPI* api) = 0;
// Hook for specialized handling in EndDocument()
virtual bool EndDocumentHandler();
// Renderers can call this to append '\0' terminated strings into
// the output string returned by GetOutput.
// This method will grow the output buffer if needed.
void AppendString(const char* s);
// Renderers can call this to append binary byte sequences into
// the output string returned by GetOutput. Note that s is not necessarily
// '\0' terminated (and can contain '\0' within it).
// This method will grow the output buffer if needed.
void AppendData(const char* s, int len);
private:
const char* file_extension_; // standard extension for generated output
const char* title_; // title of document being renderered
int imagenum_; // index of last image added
FILE* fout_; // output file pointer
TessResultRenderer* next_; // Can link multiple renderers together
bool happy_; // I get grumpy when the disk fills up, etc.
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessTextRenderer : public TessResultRenderer {
public:
explicit TessTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
/**
* Renders tesseract output into an hocr text string
*/
class TESS_API TessHOcrRenderer : public TessResultRenderer {
public:
explicit TessHOcrRenderer(const char *outputbase, bool font_info);
explicit TessHOcrRenderer(const char *outputbase);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
private:
bool font_info_; // whether to print font information
};
/**
* Renders tesseract output into searchable PDF
*/
class TESS_API TessPDFRenderer : public TessResultRenderer {
public:
// datadir is the location of the TESSDATA. We need it because
// we load a custom PDF font from this location.
TessPDFRenderer(const char *outputbase, const char *datadir);
protected:
virtual bool BeginDocumentHandler();
virtual bool AddImageHandler(TessBaseAPI* api);
virtual bool EndDocumentHandler();
private:
// We don't want to have every image in memory at once,
// so we store some metadata as we go along producing
// PDFs one page at a time. At the end that metadata is
// used to make everything that isn't easily handled in a
// streaming fashion.
long int obj_; // counter for PDF objects
GenericVector<long int> offsets_; // offset of every PDF object in bytes
GenericVector<long int> pages_; // object number for every /Page object
const char *datadir_; // where to find the custom font
// Bookkeeping only. DIY = Do It Yourself.
void AppendPDFObjectDIY(size_t objectsize);
// Bookkeeping + emit data.
void AppendPDFObject(const char *data);
// Create the /Contents object for an entire page.
static char* GetPDFTextObjects(TessBaseAPI* api,
double width, double height);
// Turn an image into a PDF object. Only transcode if we have to.
static bool imageToPDFObj(Pix *pix, char *filename, long int objnum,
char **pdf_object, long int *pdf_object_size);
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessUnlvRenderer : public TessResultRenderer {
public:
explicit TessUnlvRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
/**
* Renders tesseract output into a plain UTF-8 text string
*/
class TESS_API TessBoxTextRenderer : public TessResultRenderer {
public:
explicit TessBoxTextRenderer(const char *outputbase);
protected:
virtual bool AddImageHandler(TessBaseAPI* api);
};
} // namespace tesseract.
#endif // TESSERACT_API_RENDERER_H__
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.