Python Tesseract OCR 错误:'Error opening data file...' 解决方法

这篇文章解释了 Python 运行时遇到 'Traceback (most recent call last): ... pytesseract.pytesseract.TesseractError: (1, 'Error opening data file ...')' 错误的原因和解决方法。

错误信息分析:

这个错误信息表明你的 Python 程序在使用 pytesseract 库进行光学字符识别 (OCR) 时遇到了问题。具体来说,程序无法找到 Tesseract OCR 引擎需要使用的语言数据文件 (eng.traineddata)。

错误信息解读:

  1. Traceback (most recent call last): Python 解释器追踪错误发生的位置。
  2. File 'D:\excel\4.py', line 4, in : 错误出现在 '4.py' 文件的第 4 行。
  3. pytesseract.pytesseract.TesseractError: (1, 'Error opening data file ...'): pytesseract 库抛出 TesseractError,错误码为 1,并提示无法打开数据文件。
  4. Error opening data file \Program Files (x86)\Tesseract-OCR\eng.traineddata: 无法打开英文语言数据文件 'eng.traineddata'。
  5. Please make sure the TESSDATA_PREFIX environment variable is set to your 'tessdata' directory: 建议检查环境变量 'TESSDATA_PREFIX' 是否指向 'tessdata' 文件夹。
  6. Failed loading language 'eng' ...: 无法加载英语语言数据,导致 Tesseract 无法初始化。

解决方法:

  1. 安装 Tesseract OCR 引擎:
  2. 设置 TESSDATA_PREFIX 环境变量:
    • 找到 Tesseract OCR 的安装目录,通常在 'C:\Program Files\Tesseract-OCR' 或类似路径下。
    • 找到 'tessdata' 文件夹,该文件夹包含语言数据文件。
    • 设置名为 'TESSDATA_PREFIX' 的环境变量,将其值设置为 'tessdata' 文件夹的完整路径。
      • Windows:
        • 在搜索栏中搜索“环境变量”,选择“编辑系统环境变量”。
        • 点击“环境变量”按钮。
        • 在“系统变量”区域,点击“新建”。
        • 输入变量名:TESSDATA_PREFIX
        • 输入变量值:C:\Program Files\Tesseract-OCR\tessdata (根据你的实际安装路径修改)
        • 点击“确定”保存所有更改。
      • Linux/macOS:
        • 在终端中运行以下命令:
          export TESSDATA_PREFIX=/usr/share/tesseract-ocr/4.00/tessdata 
          
          (根据你的实际安装路径修改)
  3. 检查语言数据文件:
    • 确保 'tessdata' 文件夹中包含你需要使用的语言数据文件 (例如 'eng.traineddata' 用于英语)。
    • 如果缺少语言文件,你可以从 https://github.com/tesseract-ocr/tessdata 下载。

代码示例 (修正后):

import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # 根据你的实际安装路径修改

text = pytesseract.image_to_string(Image.open(r'D:\excel\yzm.png')) 
print(text) 

注意:

  • 将代码中的路径替换为你的实际文件和文件夹路径。
  • 重启你的 Python IDE 或命令行窗口,以使环境变量更改生效。
解决Python Tesseract OCR错误:TesseractError(1, 'Error opening data file...')

原文地址: https://www.cveoy.top/t/topic/jphD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录