使用pytesseract识别屏幕时间遇1:00格式报错排查
pytesseract识别时间格式时的int转换错误问题
我用pytesseract识别屏幕上的时间数据,“0:15”“0:35”这类分钟:秒格式能正常识别,但识别“1:00”这类时间时抛出错误:
invalid literal for int() with base 10: ''
相关代码:
timeText = pytesseract.image_to_string( timeImg, lang='eng', config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789,: -c page_separator=''') seperatedTime = timeText.split(':') minutes = int(seperatedTime[0]) seconds = int(seperatedTime[1]) totalSeconds = (minutes*60) + seconds
问题原因
错误提示说明int()无法将空字符串转为整数,也就是seperatedTime[1]是空值。核心问题出在tesseract的PSM参数设置错误:你用了--psm 10,这个参数是把图像当作单个字符处理,但时间是多字符的短文本,导致识别“1:00”时无法完整识别所有字符,最终输出的timeText可能是“1:”或者带空白的异常格式,split后第二个元素为空。
另外,识别结果可能带有换行、空格等冗余字符,也会导致split后出现空元素。
解决方法
- 调整PSM参数:把
--psm 10换成适合短文本的参数,比如--psm 7(将图像视为单行文本)或--psm 8(将图像视为单个单词),能大幅提升多字符文本的识别准确率。 - 清洗识别结果:对
timeText做预处理,去除首尾空白和换行符,避免冗余字符干扰split操作。 - 增加异常处理:捕获转换失败的情况,方便排查异常的识别结果。
修改后的代码示例:
timeText = pytesseract.image_to_string( timeImg, lang='eng', config='--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789,: -c page_separator=""') # 清洗文本:去除首尾空白、换行符 cleaned_time = timeText.strip().replace('\n', '').replace('\r', '') seperatedTime = cleaned_time.split(':') # 增加异常判断 if len(seperatedTime) == 2 and seperatedTime[0].isdigit() and seperatedTime[1].isdigit(): minutes = int(seperatedTime[0]) seconds = int(seperatedTime[1]) totalSeconds = (minutes*60) + seconds else: print(f"识别异常,结果为:{cleaned_time}") # 这里可以添加异常处理逻辑,比如重试或记录日志
内容的提问来源于stack exchange,提问作者Mendax
相关产品推荐
相关产品推荐

