Skip to main content
 首页 » 编程设计

python之如何获取Tesseract ocr检索到的字母坐标

2024年11月01日11Renyi-Fan

我正在尝试在 python 中处理 tesseract 来完成简单的工作: - 打开图片 - 运行光学识别 - 获取字符串 - 获取字符坐标

最后一个是我的痛!

这是我的第一个代码:

import tesseract 
import glob 
import cv2 
 
api = tesseract.TessBaseAPI() 
api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéèô%") 
api.SetPageSegMode(tesseract.PSM_AUTO) 
 
imagepath = "C:\\Project\\Bob\\" 
imagePathList = glob.glob(imagepath + "*.jpg") 
 
for image in imagePathList: 
    mBuffer=open(imagePathList[10],"rb").read() 
    result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api) 
    img = cv2.imread(image) 
    cv2.putText(img,result,(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))        
    cv2.imshow("Original",img) 
    cv2.waitKey() 

由于我的图片有多种布局,不同的位置有不同的文字,我想为每个字符得到一个框。

我看到有人在谈论: - api.getBoxText - 霍克

但是还没有找到用 Python 实现它的方法。

请您参考如下方法:

tesserocr提供访问几乎所有 tesseract API 功能的能力。这是一个 example这可能是你想要的:

from PIL import Image 
from tesserocr import PyTessBaseAPI, RIL 
 
image = Image.open('/usr/src/tesseract/testing/phototest.tif') 
with PyTessBaseAPI() as api: 
    api.SetImage(image) 
    boxes = api.GetComponentImages(RIL.TEXTLINE, True) 
    print 'Found {} textline image components.'.format(len(boxes)) 
    for i, (im, box, _, _) in enumerate(boxes): 
        # im is a PIL image object 
        # box is a dict with x, y, w and h keys 
        api.SetRectangle(box['x'], box['y'], box['w'], box['h']) 
        ocrResult = api.GetUTF8Text() 
        conf = api.MeanTextConf() 
        print (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, " 
               "confidence: {1}, text: {2}").format(i, conf, ocrResult, **box) 

您还可以访问其他 API 方法,例如 GetHOCRText 和 GetBoxText 等。

但是,目前它只支持 *nix 系统,尽管用户 successfully compiled it on Windows并提供了二进制文件(如果您想尝试一下)。

免责声明:此处为 tesserocr 作者。