使用python的opencv和tesseract库来识别图片中指定区域的中文

使用python的opencv和tesseract库来识别图片中指定区域的中文

需求说明

图片中包含大量中文,tesseract全图识别是逐行识别的,无法得出满意的结果,需要识别指定区域的中文。

实现方案

我们可以使用指定ROI(region of interest)的方式,对ROI里的中文进行识别。Python的opencv库和tesseract库安装和使用都非常方便,文档也比较全,因此选择使用python的opencv和tesseract库来进行识别。

参考文档:
https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html#image-roi
https://pypi.org/project/pytesseract/

示例代码

# coding: utf-8
import cv2
import pytesseract

# 设置tesseract可执行程序及中文字库的路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
tessdata_dir_config = r'--tessdata-dir "C:\Program Files (x86)\Tesseract-OCR\tessdata"'

img = cv2.imread("E:\\workspace\\cvimg\\1.png")

print img.shape
height, width, _ = img.shape

# 设定图片区域,例如取图片顶部以下60行、从右往左数第5-125列的区域
img_roi = img[0:60, width-125:width-5]

text = pytesseract.image_to_string(img_roi, lang='chi_sim', config=tessdata_dir_config)
print text

# 由于图片上字符间距的原因,识别出的文本中可能会包含空格,使用下列语句去除空格
for r in text.splitlines():
    print r.replace(" ", "")

cv2.namedWindow("roi")
cv2.imshow("roi", img_roi)
cv2.waitKey(0)
cv2.destroyAllWindow()

猜你喜欢

转载自blog.csdn.net/huzhenwei/article/details/83508524