python使用tesseract OCR文字识别
·
安装tesseract
首先安装包括安装tesseract-ocr4.0,安装中文/英文字体包,eng是英语,chi_sim是中文。安装python库pytesseract
sudo apt-get install tesseract-ocr
sudo apt-get install tesseract-ocr-eng tesseract-ocr-chi-sim
pip install pytesseract
文字识别
我这里用手机将需要识别的文章拍照,然后将照片放到~/OCR/pic文件夹中然后使用下面的python程序识别照片上的文字,将识别的内容放到~/OCR/out文件夹中,这里用到了一些第三方库,需要提前安装
import pytesseract
import cv2
from PIL import Image
import os
import subprocess
class OCRDETECT:
def __init__(self,name):
self.file = './OCR/out/'+ name + '.txt'
self.picCatalog = './OCR/pic'
self.detect(self.picCatalog)
def detect(self,lists):
path_list=os.listdir(lists)
pathDir = subprocess.run('ls ./OCR/pic',shell=True,capture_output=True,encoding='utf-8').stdout
print(pathDir.split())
a = pathDir.split()
for i in a:
name = './OCR/pic/' + i
img = cv2.imread(name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, self.threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
text = pytesseract.image_to_string(self.threshold, lang='chi_sim+eng')
self.logs(text)
print('now out ',i)
# self.displayPic(i)
def logs(self,text):
# 判断日志文件是否存在,不存在则创建
if not (os.path.exists(self.file)):
file = open(self.file, "x")
file.close()
file = open(self.file, "a")
file.write(text)
file.close()
def displayPic(self,name):
# cv2.imshow('pic',self.threshold)
file = './OCR/outpic/' + name + '.jpg'
cv2.imwrite(file,self.threshold)
# cv2.waitKey(1000)
print(file)
OCRDETECT('OCR') #输出文件名
大概原理就是先将照片进行二值化处理,然后调用tesseract进行文字的识别,识别的成功率跟照片的清晰度有很大的关系。
更多推荐

所有评论(0)