这可能不是最好的方法,但它只需要几秒钟就可以工作,并且让我知道什么时候应该取消 OCR,因为基于找到的符号数量比预期的执行时间长,假设我将 OCR 操作放在它自己的线程中可以被杀死。您还可以找到行数 (RIL_TEXTLINE),但如果您有多个列,结果会得到更多行。
import tesseract
import cv2.cv as cv
api = tesseract.TessBaseAPI()
api.Init('.','eng',tesseract.OEM_DEFAULT)
api.SetPageSegMode(tesseract.PSM_AUTO_OSD)
# Load image
img_data = cv2.imread('file.jpg')
image = cv.CreateImageHeader((width1,height1), cv.IPL_DEPTH_8U, channel1)
cv.SetData(image, img_data.tostring(),img_data.dtype.itemsize * channel1 * (width1))
tesseract.SetCvImage(image,api)
# Check number of chars
chars_iterator = api.AnalyseLayout()
num_chars = 1
while chars_iterator.Next(tesseract.RIL_SYMBOL) is True: num_chars += 1
# Break of there are too many chars
if num_chars > 1000:
print "Too many chars!"
break
# Reset api to delete previous layout iterator
api.Clear()
tesseract.SetCvImage(image,api)
# Do real OCR, and put this in its own thread if you want to kill it when it takes too long
result_xml = api.GetHOCRText(1)
print api.GetUTF8Text()