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

OCR识别数字输出异常,如何调整以获取正确结果?

解决pytesseract识别特定数字图片出错的问题

问题说明

  • 识别目标:图片显示内容为0068,768,目标数字图片
  • 当前异常:使用pytesseract识别后输出为|,但用Word生成的“123”图片测试识别正常
  • 当前使用代码:
from PIL import Image
from pytesseract import pytesseract
  
# 定义tesseract.exe路径和目标图片路径
path_to_tesseract = r"tesseract.exe"
image_path = r"capture.png"
  
# 打开图片并存储为图片对象
img = Image.open(image_path)
  
# 为pytesseract指定tesseract可执行文件位置
pytesseract.tesseract_cmd = path_to_tesseract
  
# 将图片对象传入image_to_string()函数提取文本
text = pytesseract.image_to_string(img)
  
# 显示提取的文本
print(text[:-1]) 

调整方案

1. 指定数字专属识别规则

Tesseract默认识别通用文本,针对纯数字场景,通过config参数限制识别范围,强制只识别数字和逗号:

# 修改文本提取代码,添加专属配置
text = pytesseract.image_to_string(img, config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789,')

参数说明:

  • --psm 6:假设图片是单一均匀文本块,适合连续数字场景;如果是分散单字符,可改用--psm 10
  • --oem 3:使用默认OCR引擎模式
  • tessedit_char_whitelist:仅允许识别数字和逗号,过滤其他干扰字符

2. 图片预处理提升识别精度

目标图片可能存在对比度不足、字体特殊等问题,通过预处理强化特征:

from PIL import Image
from pytesseract import pytesseract

path_to_tesseract = r"tesseract.exe"
image_path = r"capture.png"

# 打开图片并执行预处理
img = Image.open(image_path).convert('L')  # 转为灰度图
threshold = 150  # 可根据图片实际亮度调整
img = img.point(lambda x: 0 if x < threshold else 255, '1')  # 二值化增强对比度

pytesseract.tesseract_cmd = path_to_tesseract
# 应用数字识别配置
text = pytesseract.image_to_string(img, config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789,')
print(text.strip())

3. 检查Tesseract环境

  • 确保安装最新版Tesseract,避免旧版本的识别bug
  • 确认已安装英文/数字语言包(默认包含,若缺失需补充安装)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:05:16