一、下载并配置Tesseract 1.Tesseract下载地址:https://digi.bib.uni-mannheim.de/tesseract/ 2.安装完后,记得配置环境变量,默认是:C:\Program Files (x86)\Tesseract-OCR 3.为了在python代码中使用tesseract功能,使用pip安装pytesseract:
pip install pytesseract二、场景文字识别例子 如果要做真实场景下的文字识别,有一个问题是必须要考虑的,就是复杂场景下怎么保证识别准确率。 我举的这个例子可能不太准确,但是能给一些参考吧。我想在一张监控图片中读取右下角的时间。图片如下(当然,真实情况下要复杂得多): 我的思路是这样的,首先截取时间区域的图片,在通过opencv对改区域进行二值化变换,最后再用Tesseract识别。 截取时间区域: 变换后:
识别结果: 代码:
import cv2 import pytesseract import os import shutil def THRESH_TOVALUE(image,threshold,value): (w,h)=image.shape for i in range(w): for j in range(h): if(image[i][j]>threshold): image[i][j]=value return image def ocr_num(image,flag): pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)/Tesseract-OCR/tesseract.exe' thresh = cv2.threshold(image, 220, 255, cv2.THRESH_TOZERO_INV)[1] thresh = cv2.threshold(thresh, 10, 255, cv2.THRESH_BINARY)[1] thresh = cv2.GaussianBlur(thresh, (3,3), 0) data = pytesseract.image_to_string(thresh, lang='eng',config='--psm 6') #cv2.imshow('11111',thresh) #cv2.waitKey(0) return str(data) if __name__ == "__main__": x1, y1 =[1810,1335] # 获取左上角坐标s x2, y2 =[2435,1400] # 获取右下角坐标 name='20200526173716.jpg' image = cv2.imread(name, 0) img_cut = image[y1:y2, x1:x2] # 切片裁剪图像 data=ocr_num(img_cut,name) print(data)