OCR识别是开源的字符识别库,在使用之前首先进行安装
-
https://digi.bib.uni-mannheim.de/tesseract/
打开该网址下载想要的tesseract安装包,直接点击next安装,在安装过程中复制安装路径 -
配置环境变量
-
系统变量和用户变量的path中添加如:E:\Program Files (x86)\Tesseract-OCR(即tesseract安装路径)
-
新建系统变量如下图:路径为E:\Program Files (x86)\Tesseract-OCR\tessdata
-
测试:安装完成后在cmd中输入tesseract -v,安装成功的测试结果如下:
-安装pytesseract,便于在python中调用
由于我只有一个Python环境,因此直接在cmd窗口中运行pip install pytesseract即可
- 修改代码
找到Python的安装目录,
打开pytesseract.py文件,修改tesseract_cmd为安装路径+/tesseract.exe如下图
- 重启电脑(我的电脑是win7系统,新建系统变量之后重启才会生效)
- 打开pycharm,输入测试程序如下:
from PIL import Image
import pytesseract
import cv2
import os
preprocess = 'blur' #thresh
image = cv2.imread('scan.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if preprocess == "thresh":
gray = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
if preprocess == "blur":
gray = cv2.medianBlur(gray, 3)
filename = "{}.jpg".format(os.getpid())
cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open(filename))
print(text)
os.remove(filename)
cv2.imshow("Image", image)
cv2.imshow("Output", gray)
cv2.waitKey(0)
输出字符说明安装完毕