使用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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值