You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytesseract调用后终端无文本输出,图片可正常显示求助

解决Tesseract无法识别图片文本的问题

针对你遇到的代码能显示图片但无识别文本输出的情况,可按以下步骤排查解决:

1. 确认Tesseract安装与路径配置

  • 先在终端执行tesseract --version,如果无输出说明未安装Tesseract:
    • Ubuntu/Debian:sudo apt install tesseract-ocr
    • macOS:brew install tesseract
    • Windows:从Tesseract官方仓库下载安装包,安装时勾选添加到系统路径
  • 如果已安装但仍无法识别,在代码中指定Tesseract的执行路径:
    import cv2 
    import pytesseract
    
    # 根据你的系统路径调整
    pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'  # Linux
    # pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'  # Windows
    
    img = cv2.imread('/home/mubashir/jeh_Project/1.jpeg')
    if img is None:
        print("图片读取失败,请检查路径是否正确")
    else:
        rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        print(pytesseract.image_to_string(rgb_img))
        cv2.imshow('RGB_img', rgb_img)
        cv2.waitKey(0)
    

2. 对图片进行预处理优化

Tesseract对高对比度、清晰的图片识别效果更好,可通过预处理提升识别率:

import cv2 
import pytesseract

pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'

img = cv2.imread('/home/mubashir/jeh_Project/1.jpeg')
if img is None:
    print("图片读取失败,请检查路径是否正确")
else:
    # 转为灰度图
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 二值化处理(可根据图片实际情况调整阈值,示例用127)
    _, thresh_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV)
    # 降噪处理
    denoised_img = cv2.medianBlur(thresh_img, 3)
    
    # 用预处理后的图片识别
    print(pytesseract.image_to_string(denoised_img))
    cv2.imshow('Processed_img', denoised_img)
    cv2.waitKey(0)

3. 配置Tesseract识别参数

针对数字和字母的识别,可指定白名单和识别模式,提升精准度:

import cv2 
import pytesseract

pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'

img = cv2.imread('/home/mubashir/jeh_Project/1.jpeg')
if img is None:
    print("图片读取失败,请检查路径是否正确")
else:
    rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # 自定义配置:指定只识别字母和数字,设置OCR引擎和页面分割模式
    custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    print(pytesseract.image_to_string(rgb_img, config=custom_config))
    cv2.imshow('RGB_img', rgb_img)
    cv2.waitKey(0)

参数说明:

  • --oem 3:使用默认的混合OCR引擎模式
  • --psm 6:假设图片是单一的统一文本块
  • tessedit_char_whitelist:指定只识别白名单内的字符

内容的提问来源于stack exchange,提问作者Mubashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:40:20