Python实现从图片提取文字

环境

  1. Python3
  2. Python3的pillow、pytesseract包
    可使用pip install pillow、pip install pytesseract命令安装
    或者通过pycharm进行安装
  3. 识别引擎tesseract-ocr ,下载地址

代码

#-*- coding:utf-8 -*- 
import pytesseract  
from PIL import Image  

# 使用pytesseract对英文进行识别,lang参数可省略 
print(pytesseract.image_to_string(Image.open('textEng.png',lang='eng')))  
# 使用pytesseract对中文(含英文,但识别率降低)进行识别 
print(pytesseract.image_to_string(Image.open('textCh.png'), lang='chi_sim'))  

该提取文字的功能对英文识别率还是可以的,但对中文稍差强人意,不过还是比手打的要方便。

报错及解决

1. FileNotFoundError:[WinError 2]系统找不到指定文件。

解决方法:
搜索文件pytesseract.py,找到如下代码,将tesseract_cmd的值修改为全路径(tesseract文件的全路径,该文件在Tesseract-OCR下)。如下:

tesseract_cmd = 'tesseract'

改为

tesseract_cmd = 'E:\Python36\Tesseract-OCR\\tesseract'

2.pytesseract.pytesseract.TesseractError: (1, ‘Error opening data file ··· ··· Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your “tessdata” directory. Failed loading language \’chi_sim\’ Tesseract couldn\’t load any languages! Could not initialize tesseract.’)

解决办法:
1. 检查是否将TESSDATA_PREFIX添加到系统变量里,若没有,在系统变量(注意不是环境变量)里新建变量名TESSDATA_PREFIX,变量值为E:\Python37\Tesseract-OCR\(此处填你的Tesseract-OCR文件路径)。
2. 检查“Tesseract-OCR\tessdata”路径下是否存在chi_sim.traineddata(若是报错是无法加载eng则查看是否存在相应文件),若没有,下载chi_sim.traineddata文件,并放置在“Tesseract-OCR\tessdata”路径下。
3. 若还没有解决:
打开文件pytesseract.py,找到image_to_string,在上面一行指定config的参数为tessdata文件的路径,如下:

tessdata_dir_config = '--tessdata-dir "E:\Python37\Tesseract-OCR\\tessdata"'
def image_to_string(image, lang=None, config='', nice=0, boxes=False, output_type=Output.STRING):

3.permission denied:[WinError 5] 拒绝访问

解决方法:
Tesseract-OCR默认安装在”C:\Program Files (x86)”下,访问该路径需要administrator权限。修改Tesseract-OCR安装路径并更改tesseract_cmd的值即可。

你可能感兴趣的:(Python)