python3使用谷歌tesseract-ocr4.0实现图像/文字识别
python3使用谷歌tesseract-ocr4.0实现图像/文字识别
上一篇是关于安装:ubuntu16.04安装编译谷歌tesseract-ocr4.0。
这一篇python3使用谷歌tesseract-ocr4.0实现图像/文字识别。
在安装tesseract-ocr4.0完成以后,在pycharm里面配置了对应的字体库路径(这步可以不做)。
打开pycharm:
新建一个gg_ocr.py:
当前路径是: /home/xxy/PycharmProjects/different_ocr/google_ocr
源码如下:
# python 3.5
# 谷歌tesseract-ocr使用
from PIL import Image
import pytesseract
import json
import re
import os
class Languages:
CHS = 'chi_sim' # 中文
CHT = 'chi_tra' # 繁体
ENG = 'eng' # 英文
# 调用tesseract-ocr
def img_to_str(image_path, lang):
return pytesseract.image_to_string(Image.open(image_path), lang)
def save(text):
fs = open("../txt/gg_ocr.txt", 'w+', encoding='utf-8') # 遍历后的图片提取文字,保存到txt
fs.write(text)
fs.close()
# file = open("../txt/gg_ocr.txt", 'w+', encoding='utf-8')
# # 格式化存储
# for k, v in re.items():
# line = "filename :" + name + "\t" + k.encode("utf-8") + "\t" + str(v) + "\n"
# file.write(line)
# file.close()
def main(image_path):
if image_path is None or len(image_path) == 0:
print("图片不存在。")
else:
# 识别
lang = Languages.CHS
text = img_to_str(image_path, lang)
print("内容?", text, type(text))
# 保存
save(text)
if __name__=='__main__':
print('当前路径是:', os.getcwd())
image_path = '../img/0001.jpg'
main(image_path)
print("识别完成。")
识别效果:
结束。