Skip to main content
 首页 » 编程设计

python之如何使用 ctypes 和 tesseract 3.0.2 识别数据而不是文件名

2025年05月04日10落叶无声

我使用 ctypes 和 tesseract 3.0.2 编写了一个片段,引用了 example :

import ctypes 
from PIL import Image 
 
 
libname = '/opt/tesseract/lib/libtesseract.so.3.0.2' 
tesseract = ctypes.cdll.LoadLibrary(libname) 
api = tesseract.TessBaseAPICreate() 
 
rc = tesseract.TessBaseAPIInit3(api, "", 'eng') 
filename = '/opt/ddl.ddl.exp654.png' 
 
text_out = tesseract.TessBaseAPIProcessPages(api, filename, None, 0) 
result_text = ctypes.string_at(text_out) 
print result_text 

它传递文件名作为参数,我不知道调用API中的哪个方法传递原始数据,如:

tesseract.TessBaseAPIWhichMethod(api, open(filename).read()) 

请您参考如下方法:

我不能肯定地说,但我不认为你可以将复杂的 python 对象传递给那个特定的 API,它不知道如何处理它们。您最好的选择是查看像 http://code.google.com/p/python-tesseract/ 这样的包装器,它允许您使用文件缓冲区

import tesseract 
api = tesseract.TessBaseAPI() 
api.Init(".","eng",tesseract.OEM_DEFAULT) 
api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyz") 
api.SetPageSegMode(tesseract.PSM_AUTO) 
 
mImgFile = "eurotext.jpg" 
mBuffer=open(mImgFile,"rb").read() 
result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api) #YAY for buffers. 
print "result(ProcessPagesBuffer)=",result 

编辑

http://code.google.com/p/python-tesseract/source/browse/python-tesseract-0.7.4/debian/python-tesseract/usr/share/pyshared/tesseract.py 可能会为您提供所需的见解。

...

实际上,如果您不介意替换时会发生什么

text_out = tesseract.TessBaseAPIProcessPages(api, filename, None, 0) 

与

text_out = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api)