使用Tesseract OCR库识别验证码:Python与PyCharm环境下的实践指南

一、步骤

1. 安装 Tesseract OCR

步骤:

  1. 下载 Tesseract

  2. 前往 Tesseract GitHub 下载 Windows 安装包(.exe

  3. 在以下链接下载可执行文件,然后一顿点击下一步安装即可(放在不需要权限的纯英文路径下):http:// https://github.com/tesseract-ocr/

  4. 运行安装程序,勾选 Add Tesseract to PATH(自动添加环境变量)。

  5. 验证安装

      在 CMD 输入:

tesseract --version
  • 如果显示版本号(如 tesseract 5.3.0),说明安装成功。

  • 如果报错 'tesseract' is not recognized,需手动添加环境变量:

    1. 右键 此电脑 → 属性 → 高级系统设置 → 环境变量

    2. 在 Path 中添加 Tesseract 的安装路径(如 C:\Program Files\Tesseract-OCR)。

    3. 重启 CMD 再次验证。

  • 2. 安装 Python 依赖库

    在 PyCharm 的终端或 CMD 中运行:

    pip install pytesseract pillow
  • pytesseract:Tesseract 的 Python 接口

  • pillow(PIL):用于处理图像

  • 3. 准备测试图片
    1. 将待识别的图片(如 test.png)放在项目目录下,或记住它的绝对路径(如 D:\test.png)。

    2. 确保图片清晰(文字部分无模糊、倾斜或复杂背景)。

    二、举例子证明:

      c.png

     

     

    然后在CMD里面:

     

    此处为空说明它没有识别出内容来

    正好 在c.png底下会生成记事本的text文本

    打开之后内容也是空的

     

    同时,在pycharm代码里面

    import pytesseract
    import pytesseract.pytesseract as te
    from PIL import Image
    image=Image.open("c.png")
    pytesseract.pytesseract.tesseract_cmd=r"D:\Tesseract-OCR\tesseract.exe"
    textcode=pytesseract.pytesseract.image_to_string(image).strip()
    print(textcode)

    运行结果也为空

    三、成功案例(与二同样的步骤)

     b.png

    在CMD里面运行之后:

    具体内容:

    在pycharm代码里面的运行结果:注意要把照片放到目录底下!!!

     

    结果正确 验证码识别成功!

    四、拓展更好看的代码格式

    import pytesseract
    from PIL import Image
    
    # 1. 设置 Tesseract 路径(如果未自动识别)
    pytesseract.pytesseract.tesseract_cmd = r'D:\Tesseract-OCR\tesseract.exe'
    
    # 2. 打开图片(使用绝对路径更可靠)
    image_path = "b.png"  # 或 r"D:\test.png"
    try:
        image = Image.open(image_path)
    except FileNotFoundError:
        print("错误:图片文件未找到!请检查路径。")
        exit()
    
    # 3. 识别文字(优化参数)
    config = '--psm 6 -l eng'  # 模式6(单行文本)+ 英文(中文用 chi_sim)
    text = pytesseract.image_to_string(image, config=config).strip()
    
    # 4. 输出结果
    print("识别结果:", text)
    
    # 5. 可选:保存到文件
    with open("output.txt", "w", encoding="utf-8") as file:
        file.write(text)
    print("结果已保存到 output.txt")

    运行结果:

    作者:莓事哒

    物联沃分享整理
    物联沃-IOTWORD物联网 » 使用Tesseract OCR库识别验证码:Python与PyCharm环境下的实践指南

    发表回复