2014-02-13 69 views
5

我想在python中使用Tesseract 3.02与ctypes和cv2。正方体提供了一个DLL暴露集合C风格的API,其中之一是如下:在python中使用tesseract 3.02与ctypes和cv2的C API

TESS_API void TESS_CALL TessBaseAPISetImage(TessBaseAPI* handle, const unsigned char* imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line); 

到目前为止,我的代码如下:

tesseract = ctypes.cdll.LoadLibrary('libtesseract302.dll') 
api = tesseract.TessBaseAPICreate() 
tesseract.TessBaseAPIInit3(api, '', 'eng') 
imcv = cv2.imread('test.bmp') 
w, h, d = imcv.shape 
ret = tesseract.TessBaseAPISetImage(api, ctypes.c_char_p(str(imcv.data)), w, h, d, w * d) 
#ret = 44 here 

最后一行返回错误代码44,我在Tesseract提供的errcode.h中找不到任何地方。我不确定我在这里做错了什么。

我找到类似的问题How to recognize data not filename using ctypes and tesseract 3.0.2?,但问题没有解决。 我也知道https://code.google.com/p/python-tesseract/,我深入了解这个项目的源代码,但是无法找到我需要的信息。

我可以通过调用cv2.imshow来确认test.bmp中的图像是否合法并可读。 同样的图像可以通过命令行上的Tesseract进行OCR。

+1

我不能帮你用C-API,但如果没有人回答:使用[可执行程序获得出文本](https://github.com/niccokunzmann/mousemove/blob/master/mousemove/auslesen.py#L32)。它远离最佳状态。 – User

+1

'TessBaseAPISetImage'不返回值。默认的'restype'是'c_int',所以44只是垃圾转换为整数。 – eryksun

回答

9

默认restypec_int,并且整数的默认参数转换也是c_int。您将在网络上找到假设具有sizeof(int) == sizeof(void *)的32位平台的示例。这从来都不是一个好的假设。为了保护64位指针在与Python整数转换时截断,设置函数指针的argtypesrestype。无论如何,这是一个好主意,因为它允许ctypes在使用错误类型或数量的参数时引发ArgumentError

如果您不想为每个函数定义原型,那么至少应将TessBaseAPICreate.restype设置为不透明指针类型。

以下ctypes定义基于标头api/capi.h。为了方便起见,我将API打包为Tesseract类。

import sys 
import cv2 
import ctypes 
import ctypes.util 

if sys.platform == 'win32': 
    LIBNAME = 'libtesseract302' 
else: 
    LIBNAME = 'tesseract' 

class TesseractError(Exception): 
    pass 

class Tesseract(object): 
    _lib = None 
    _api = None 

    class TessBaseAPI(ctypes._Pointer): 
     _type_ = type('_TessBaseAPI', (ctypes.Structure,), {}) 

    @classmethod 
    def setup_lib(cls, lib_path=None): 
     if cls._lib is not None: 
      return 
     if lib_path is None: 
      lib_path = ctypes.util.find_library(LIBNAME) 
      if lib_path is None: 
       raise TesseractError('tesseract library not found') 
     cls._lib = lib = ctypes.CDLL(lib_path) 

     # source: 
     # https://github.com/tesseract-ocr/tesseract/ 
     #   blob/3.02.02/api/capi.h 

     lib.TessBaseAPICreate.restype = cls.TessBaseAPI 

     lib.TessBaseAPIDelete.restype = None # void 
     lib.TessBaseAPIDelete.argtypes = (
      cls.TessBaseAPI,) # handle 

     lib.TessBaseAPIInit3.argtypes = (
      cls.TessBaseAPI, # handle 
      ctypes.c_char_p, # datapath 
      ctypes.c_char_p) # language 

     lib.TessBaseAPISetImage.restype = None 
     lib.TessBaseAPISetImage.argtypes = (
      cls.TessBaseAPI, # handle 
      ctypes.c_void_p, # imagedata 
      ctypes.c_int, # width 
      ctypes.c_int, # height 
      ctypes.c_int, # bytes_per_pixel 
      ctypes.c_int) # bytes_per_line 

     lib.TessBaseAPIGetUTF8Text.restype = ctypes.c_char_p 
     lib.TessBaseAPIGetUTF8Text.argtypes = (
      cls.TessBaseAPI,) # handle 

    def __init__(self, language='eng', datapath=None, lib_path=None): 
     if self._lib is None: 
      self.setup_lib(lib_path) 
     self._api = self._lib.TessBaseAPICreate() 
     if self._lib.TessBaseAPIInit3(self._api, datapath, language): 
      raise TesseractError('initialization failed') 

    def __del__(self): 
     if not self._lib or not self._api: 
      return 
     if not getattr(self, 'closed', False): 
      self._lib.TessBaseAPIDelete(self._api) 
      self.closed = True 

    def _check_setup(self): 
     if not self._lib: 
      raise TesseractError('lib not configured') 
     if not self._api: 
      raise TesseractError('api not created') 

    def set_image(self, imagedata, width, height, 
        bytes_per_pixel, bytes_per_line=None): 
     self._check_setup() 
     if bytes_per_line is None: 
      bytes_per_line = width * bytes_per_pixel 
     self._lib.TessBaseAPISetImage(self._api, 
             imagedata, width, height, 
             bytes_per_pixel, bytes_per_line) 

    def get_utf8_text(self): 
     self._check_setup() 
     return self._lib.TessBaseAPIGetUTF8Text(self._api) 

    def get_text(self): 
     self._check_setup() 
     result = self._lib.TessBaseAPIGetUTF8Text(self._api) 
     if result: 
      return result.decode('utf-8') 

实例:

if __name__ == '__main__': 
    imcv = cv2.imread('ocrtest.png') 
    height, width, depth = imcv.shape 

    tess = Tesseract() 
    tess.set_image(imcv.ctypes, width, height, depth) 
    text = tess.get_text() 

    print text.strip() 

我libtesseract.so.3测试这在Linux。请注意0​​返回一个NumPy数组。这有一个​​属性,其中包括_as_parameter_钩子,设置为指向该阵列的c_void_p指针。还要注意,问题中显示的代码具有宽度和高度转置。它应该是h, w, d = imcv.shape

ocrtest.png:

ocrtest

输出:

I am trying to use Tesseract 3.02 with ctypes and cv2 in python. Tesseract 
provides a DLL exposed set of C style APIs, one of them is as following: 
+0

非常感谢@eryksun!我在交互式shell中测试的事实误导了我(它返回了44,这让我想到了函数导致的错误) – xbtsw

+0

我偶然发现了谷歌搜索,并且有同样的问题。但是,我对这个答案感到困惑。这段代码后面的代码片段是基于头文件api/capi.h.'做了什么?是否需要将cv2图像传递给c api?或者唯一需要的是'Example(用libtesseract.so.3在Linux上测试)'后的代码片段? – Anthony

+0

@Anthony,我重写了更多面向对象的答案,并且我更新了github上新项目站点的标题链接。 – eryksun

相关问题