转自:https://code.google.com/p/tesseract-ocr/wiki/APIExample
APIExample

API examples

Updated Aug 12, 2014 by theraysm...@gmail.com

This wiki provide simple example how to use tesseract-ocr API (v3.02.02) in C++. It is expected that tesseract-ocr is correctly installed including all dependecies. It is expected that user is familiar with C++, compiling and linking program on his platform, though basic compilation examples are included for beginners with Linux.

More details about tesseract-ocr API can found at baseapi.h

Basic example

Code:

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h> int main()
{
    char *outText;     tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
    // Initialize tesseract-ocr with English, without specifying tessdata path
    if (api->Init(NULL, "eng")) {
        fprintf(stderr, "Could not initialize tesseract.\n");
        exit(1);
    }     // Open input image with leptonica library
    Pix *image = pixRead("/usr/src/tesseract-3.02/phototest.tif");
    api->SetImage(image);
    // Get OCR result
    outText = api->GetUTF8Text();
    printf("OCR output:\n%s", outText);     // Destroy used object and release memory
    api->End();
    delete [] outText;
    pixDestroy(&image);     return 0;
}

Program must be linked to tesseract-ocr library and leptonica library.

If you want to restrict recognition to a sub-rectangle of the image - call SetRectangle(left, top, width, height) after SetImage. Each SetRectangle clears the recogntion results so multiple rectangles can be recognized with the same image. E.g.

  api->SetRectangle(30, 86, 590, 100);

GetComponentImages example

  Pix *image = pixRead("/usr/src/tesseract-3.02/phototest.tif");
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, NULL, NULL);
  printf("Found %d textline image components.\n", boxes->n);
  for (int i = 0; i < boxes->n; i++) {
    BOX* box = boxaGetBox(boxes, i, L_CLONE);
    api->SetRectangle(box->x, box->y, box->w, box->h);
    char* ocrResult = api->GetUTF8Text();
    int conf = api->MeanTextConf();
    fprintf(stdout, "Box[%d]: x=%d, y=%d, w=%d, h=%d, confidence: %d, text: %s",
                    i, box->x, box->y, box->w, box->h, conf, ocrResult);
  }

Result iterator example

There is posibility to get confidence value and BoundingBox per word from ResultIterator:

  Pix *image = pixRead("/usr/src/tesseract-3.02/phototest.tif");
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  api->Recognize(0);
  tesseract::ResultIterator* ri = api->GetIterator();
  tesseract::PageIteratorLevel level = tesseract::RIL_WORD;
  if (ri != 0) {
    do {
      const char* word = ri->GetUTF8Text(level);
      float conf = ri->Confidence(level);
      int x1, y1, x2, y2;
      ri->BoundingBox(level, &x1, &y1, &x2, &y2);
      printf("word: '%s';  \tconf: %.2f; BoundingBox: %d,%d,%d,%d;\n",
               word, conf, x1, y1, x2, y2);
      delete[] word;
    } while (ri->Next(level));
  }

Of course there is posibility to use other PageiteratorLevel.

Orientation and script detection (OSD) example

  const char* inputfile = "/usr/src/tesseract-3.02/eurotext.tif";
  tesseract::Orientation orientation;
  tesseract::WritingDirection direction;
  tesseract::TextlineOrder order;
  float deskew_angle;   PIX *image = pixRead(inputfile);
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init("/usr/src/tesseract-3.02/", "eng");
  api->SetPageSegMode(tesseract::PSM_AUTO_OSD);
  api->SetImage(image);
  api->Recognize(0);   tesseract::PageIterator* it =  api->AnalyseLayout();
  it->Orientation(&orientation, &direction, &order, &deskew_angle);
  printf("Orientation: %d;\nWritingDirection: %d\nTextlineOrder: %d\n" \
         "Deskew angle: %.4f\n",
         orientation, direction, order, deskew_angle);

Explanation for result codes are in publictypes.h

Example of iterator over the classifier choices for a single symbol

  Pix *image = pixRead("/usr/src/tesseract-3.02/phototest.tif");
  tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
  api->Init(NULL, "eng");
  api->SetImage(image);
  api->SetVariable("save_blob_choices", "T");
  api->SetRectangle(37, 228, 548, 31);
  api->Recognize(NULL);   tesseract::ResultIterator* ri = api->GetIterator();
  tesseract::PageIteratorLevel level = tesseract::RIL_SYMBOL;
  if(ri != 0) {
      do {
          const char* symbol = ri->GetUTF8Text(level);
          float conf = ri->Confidence(level);
          if(symbol != 0) {
              printf("symbol %s, conf: %f", symbol, conf);
              bool indent = false;
              tesseract::ChoiceIterator ci(*ri);
              do {
                  if (indent) printf("\t\t ");
                  printf("\t- ");
                  const char* choice = ci.GetUTF8Text();
                  printf("%s conf: %f\n", choice, ci.Confidence());
                  indent = true;
              } while(ci.Next());
          }
          printf("---------------------------------------------\n");
          delete[] symbol;
      } while((ri->Next(level)));
  }

Compiling C++ API programs on Linux

Including and linking to Tesseract's API is done in a standard Linux way. To compile a basic program against the API, you can use a command like this:

g++ -o myprogram myprogram.cpp -llept -ltesseract

If Tesseract is installed in an unusual place, you can specify the include and lib directories explicitly with g++'s -I and -L flags, like this:

g++ -o myprogram myprogram.cpp -I/home/nick/local/include/tesseract -L/home/nick/local/lib -llept -ltesseract

C-API in python

Tesseract-ocr from version 3.02.02 provide C-API. This enable to use tesseract-ocr shared library in python (and other languages that can use C libraries):

import os
import ctypes lang = "eng"
filename = "/usr/src/tesseract-ocr/phototest.tif"
libname = "/usr/local/lib64/libtesseract.so.3"
TESSDATA_PREFIX = os.environ.get('TESSDATA_PREFIX')
if not TESSDATA_PREFIX:
    TESSDATA_PREFIX = "../" tesseract = ctypes.cdll.LoadLibrary(libname)
tesseract.TessVersion.restype = ctypes.c_char_p
tesseract_version = tesseract.TessVersion()
api = tesseract.TessBaseAPICreate()
rc = tesseract.TessBaseAPIInit3(api, TESSDATA_PREFIX, lang)
if (rc):
    tesseract.TessBaseAPIDelete(api)
    print("Could not initialize tesseract.\n")
    exit(3) text_out = tesseract.TessBaseAPIProcessPages(api, filename, None, 0)
result_text = ctypes.string_at(text_out) print 'Tesseract-ocr version', tesseract_version
print result_text

Example of passing python file object to C-API can be found at pastebin.

Example using the C-API in a C program

The C-API can of course also be used by regular C programs, as in this very basic example.

#include <stdio.h>
#include <allheaders.h>
#include <capi.h> void die(const char *errstr) {
        fputs(errstr, stderr);
        exit(1);
} int main(int argc, char *argv[]) {
        TessBaseAPI *handle;
        PIX *img;
        char *text;         if((img = pixRead("img.png")) == NULL)
                die("Error reading image\n");         handle = TessBaseAPICreate();
        if(TessBaseAPIInit3(handle, NULL, "eng") != 0)
                die("Error initialising tesseract\n");         TessBaseAPISetImage2(handle, img);
        if(TessBaseAPIRecognize(handle, NULL) != 0)
                die("Error in Tesseract recognition\n");         if((text = TessBaseAPIGetUTF8Text(handle)) == NULL)
                die("Error getting text\n");         fputs(text, stdout);         TessDeleteText(text);
        TessBaseAPIEnd(handle);
        TessBaseAPIDelete(handle);
        pixDestroy(&img);         return 0;
}

On Linux you can compile it as you would build a program using the C++ API.

tesseract api C++使用例子的更多相关文章

  1. Tesseract API在VS 2013中的配置以及调用

    [Tesseract]Tesseract API在VS 2013中的配置以及调用 时间:2016-05-31 20:35:19      阅读:127      评论:0      收藏:0      ...

  2. 【Tesseract】Tesseract API在VS 2013中的配置以及调用

    想要在VS中使用Tesseract库,必须使用经过相对应的VS版本编译过的dll以及lib.比如在VS 2013中,就必须使用在VS 2013中编译过的Tesseract库. 这里我给出经过VS 20 ...

  3. 【windows核心编程】一个API拦截的例子

    API拦截 修改PE文件导入段中的导入函数地址 为 新的函数地址 这涉及PE文件格式中的导入表和IAT,PE文件中每个隐式链接的DLL对应一个IMAGE_IMPORT_DESCRIPTOR描述符结构, ...

  4. yii2 高级版新建一个应用(api应用为例子)

    先在项目的根目录下复制一份 backend 为 api: cp backend/ api -r 拷贝 api 环境 cp -a environments/dev/frontend environmen ...

  5. jquery api 常见api 效果操作例子

    addClass_removeClass_toggleClass_hasClass.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 ...

  6. jquery api 常见api 元素操作例子

    append_prepend.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> ...

  7. API StringBuffer类例子

    package cn.zmh.Buffer; public class StringBufferDemo { public static void main(String[] args) { prin ...

  8. VC API常用函数简单例子大全(1-89)

    第一个:FindWindow根据窗口类名或窗口标题名来获得窗口的句柄,该函数返回窗口的句柄 函数的定义:HWND WINAPI FindWindow(LPCSTR lpClassName ,LPCST ...

  9. C#调用windows API的一些方法

    使用C#调用windows API(从其它地方总结来的,以备查询) C#调用windows API也可以叫做C#如何直接调用非托管代码,通常有2种方法: 1.  直接调用从 DLL 导出的函数. 2. ...

随机推荐

  1. Codeforces 719E [斐波那契区间操作][矩阵快速幂][线段树区间更新]

    /* 题意:给定一个长度为n的序列a. 两种操作: 1.给定区间l r 加上某个数x. 2.查询区间l r sigma(fib(ai)) fib代表斐波那契数列. 思路: 1.矩阵操作,由矩阵快速幂求 ...

  2. 抽象类和抽象方法(关键字abstract)

     1.抽象类不能被实例化,可以没有,一个或多个抽象方法  2.抽象方法只有方法的声明但没有方法的实现,有抽象方法的类必须声明为抽象类,子类必须重写父类所有的抽象方法才能被实例化,否则子类也是个抽象类, ...

  3. QTdebug时没有调试引擎

    问题描述: 在调试程序时,点击调试按钮,弹出no engine. 问题解决: 到官网下载调试的SDK.https://developer.microsoft.com/zh-cn/windows/dow ...

  4. String 及其数组的相关问题

    由其他类型转String一般用三种方法 方法1:采用 Object.toString()方法 请看下面的例子: Object object = getObject(); System.out.prin ...

  5. tp框架 中的时间 查询范围

    $where['add_time'] = array(array('egt',$starttime),array('elt',$endtime),'AND');

  6. Myeclipse以及Genymotion工具的使用以及java后台开发小结

    1. 服务端的Servlet程序修改并保存后,需要重启tomcat服务器才能使其修改有效.重新部署web项目是没有什么卵用的. 2. servers选项卡若是移走了看不到,在window-show v ...

  7. 对Web标准的理解。可用性和可访问性

    一Web标准 简单的说,就是HTML.CSS.JavaScript这三者分离.WEB标准不是某一个标准,而是一系列标准的集合.网页主要由三部分组成:结构(Structure).表现(Presentat ...

  8. 在SWING里嵌入SWT的组件

    http://zhanghan3366.blog.163.com/blog/static/6966305220110505351568/ ——————————————————————————————— ...

  9. win8自动升级win8.1后 wampserver无法启动

    原因是升级时win8把其他的系统服务都给停止了. 解决办法是左键点击wamp的小图标,选择apache/mysql - service - 安装服务. 然后再选择启动服务,即可.

  10. thinkphp加载 和url_model

    1.加载thinkphp.php requrie('./ThinkPHP/ThinkPHP.php'); 2.加载核心文件 ./thinkPHP/LIB/core 3.加载项目的文件 分析URL 调用 ...