【问题标题】:How to pass OpenCV image to Tesseract in python?如何在 python 中将 OpenCV 图像传递给 Tesseract?
【发布时间】:2015-08-04 22:51:03
【问题描述】:

给定 Python 代码调用 Tesseract 的 C API 并使用 ctypes 库,在 选项 #1 中,Tesseract 正在加载图像并且它工作正常!问题出在 Option #2 中,当我尝试传递 OpenCV 加载的图像时,T​​esseract 返回垃圾:

from ctypes import *
import cv2

class API(Structure):
    _fields_ = []

lang = "eng"
ts = cdll.LoadLibrary("c:/Tesseract-OCR/libtesseract302.dll")
ts.TessBaseAPICreate.restype = POINTER(API)
api = ts.TessBaseAPICreate()
rc = ts.TessBaseAPIInit3(api, 'c:/Tesseract-OCR/', lang)

##### Option #1
out = ts.TessBaseAPIProcessPages(api, 'c:/Tesseract-OCR/doc/eurotext.tif', None, 0)
print 'Option #1 => ' + string_at(out)

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

im = cv2.imread('c:/Temp/Downloads/test-slim/eurotext.jpg', cv2.COLOR_BGR2GRAY)
c_ubyte_p = POINTER(c_ubyte)
##ts.TessBaseAPISetImage.argtypes = [POINTER(API), c_ubyte_p, c_int, c_int, c_int, c_int]
ts.TessBaseAPISetImage(api, im.ctypes.data_as(c_ubyte_p), 800, 1024, 3, 800 * 3)
out = ts.TessBaseAPIGetUTF8Text(api)
print 'Option #2 => ' + string_at(out)

输出如下:

选项 #1 => (快速)[棕色] {狐狸} 跳跃! 超过 $43,456.78 #90 狗 & 鸭/鹅,占 E-mail 的 12.5% 来自 aspammer@website.com 的垃圾邮件。 Der ,,schnelleâ€� braune Fuchs springt ? ber den faulen Hund。勒纳布朗 «rapide» 炒par-dessus le chien 帕雷塞克斯。 La volpe marrone rapida salta sopra il cane pigro。埃尔佐罗 marrén répido salta sobre el perro 佩雷索索。枣树 salta sobre o cï¬�o preguicoso。

选项#2 => 7?:5:*:>\—â€~- ;2—;i3E:?:;i3".i: iiâ€~; 3;’ f- ié%:::’::;?:=â«â€™:: =£<:7 :>:3_3:l.':—â€~:—:£€:-_’:§3;;%§%ai5~«:é: :3%ia»â‚¬E:

备注:

  • 我试过python-tesseract和tightocr库,很好
    够了,但缺少文档
  • 这里我使用 opencv.imread 以便有可能应用数学 矩阵算法

任何想法如何将 OpenCV 图像(即 numpy.ndarray)传递给 Tesseract?任何帮助都会很有用。

【问题讨论】:

  • 令人惊讶...事实证明,它已经解决了,link.. 感谢@eryksun 和 stackoverflow!

标签: python opencv numpy tesseract


【解决方案1】:

我在 python 3 中使用它:(bw_img 是一个 numpy.ndarray)

import numpy as np
import cv2
from PIL import Image
import pytesseract

...

(thresh, bw_img) = cv2.threshold(bw_img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
...

img = Image.fromarray(bw_img)
txt = pytesseract.image_to_string(img)
print(txt)

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 1970-01-01
    • 2019-12-26
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多