如何用pytesseract高效识别屏幕数字?优化精度与速度
数字识别问题:pytesseract识别慢且准确率低
我尝试用pytesseract识别屏幕上的数字,能运行但速度慢、识别效果极差。比如原图像经阈值处理后,识别结果是5852而非正确的585;不同阈值下还会出现更严重的错误,比如把1 000 000识别成1 aaa eee,或是给585无端加字符变成5385r。想知道有没有办法强制pytesseract只识别数字,或者有没有比它更好的工具?
我的主代码
from PIL import Image from pytesseract import pytesseract as pyt import test pyt.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe' def tti2(location) : image_file = location im = Image.open(image_file) text = pyt.image_to_string(im) print(text) for character in "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*^&\n" : text = text.replace(character, "") return text test.th("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TEST.png") print(tti2("C:\\Users\\Utilisateur\\Pictures\\greenshot\\flea market sniper\\TESTbis.png"))
test模块代码(阈值处理)
import cv2 from PIL import Image def th(Path) : img = cv2.imread(Path) # 如果图像不是灰度图: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) threshold = 60 # 需要调整 _, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) pil_img = Image.fromarray(img_binarized) Path = Path.replace(".png","") pil_img.save(Path+"bis.png")
解决方案
一、强制pytesseract仅识别数字
pytesseract支持通过配置参数限制识别的字符集,不用手动替换非数字字符,既能提升准确率又能加快识别速度。修改image_to_string的调用代码:
text = pyt.image_to_string(im, config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789')
参数说明:
--psm 6:告诉Tesseract图像是单一规整文本块(适合数字这类格式统一的内容)--oem 3:使用默认的OCR引擎模式tessedit_char_whitelist=0123456789:仅允许识别0-9的数字
另外,你的阈值处理代码存在语法错误:Path = Path.replace(".png","")后面缺少闭合括号,需要修正才能正常运行。
二、推荐更优的数字识别工具
如果优化pytesseract后仍达不到需求,可以尝试以下工具:
- EasyOCR:轻量级OCR库,对数字识别优化较好,支持直接指定识别字符类型,配置简单
- OpenCV轮廓检测+模板匹配:若数字的字体、大小固定,先通过轮廓提取单个数字区域,再与预设数字模板匹配,准确率极高且速度快
- Google ML Kit:移动端或云端OCR服务,数字识别准确率高,云端版需联网使用
- Amazon Textract:云端OCR服务,针对结构化文本(如数字、表格)优化,准确率高,但有使用成本
内容的提问来源于stack exchange,提问作者the shadow
相关产品推荐
相关产品推荐

