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

使用Python的pytesseract提取图片内容时,无法获取数字且返回空值求助

解决py-tesseract无法识别黑底白字数字的问题

你的问题出在图像颜色不符合Tesseract默认识别逻辑(它更适配白底黑字),加上参数配置没有针对性优化,导致识别为空。以下是修正方案:

1. 加入图像预处理+优化参数配置

对黑底白字图片做颜色反转,同时增强对比度,再调整Tesseract的识别参数:

from PIL import Image, ImageOps
import pytesseract

def ImageReader(image_path):
    image = Image.open(image_path)
    # 颜色反转:黑底白字转白底黑字,匹配Tesseract训练数据逻辑
    inverted_image = ImageOps.invert(image)
    # 二值化处理,强化文字与背景的对比度
    thresholded_image = inverted_image.point(lambda x: 0 if x < 128 else 255, '1')
    
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
    # 配置参数:指定OCR引擎+单字符识别模式+限定数字识别范围
    extracted_text = pytesseract.image_to_string(
        thresholded_image, 
        lang='eng', 
        config='--oem 3 --psm 10 -c tessedit_char_whitelist=0123456789'
    )
    print("提取文本:" + extracted_text.strip())
    return extracted_text.strip()

2. 参数说明

  • --oem 3:使用混合OCR引擎(结合传统与LSTM模型),适配多数场景
  • --psm 10:单字符识别模式,对应你图片中单个数字的识别需求(原--psm 7是单行文本识别,不适用单字符场景)
  • tessedit_char_whitelist=0123456789:限定只识别数字,过滤无关干扰,提升识别精准度

效果验证

经过预处理和参数调整后,能精准识别出图片中的数字2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:43:15