如何修复Tesseract OCR数字识别中将3误识别为4的代码问题
待识别原图

错误原因
- 原代码二值化阈值设置为200过高,数字3顶部的浅灰色像素被判定为背景涂黑,导致3的轮廓缺失,被误识别为4
- 预处理未做去噪,少量噪点会干扰Tesseract判断
- PSM模式选择不当,
--psm 11是稀疏文本模式,对连续数字串的识别适配性不如单字串模式
修改后的代码
from PIL import Image, ImageEnhance, ImageFilter import pytesseract pytesseract.pytesseract.tesseract_cmd = r"C:\\Users\\Никитос\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe" img = Image.open('C:\\Users\\Никитос\\Desktop\\unknown.jpg') # 先小幅提高亮度再提对比度,保留暗部轮廓细节 enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(1.2) enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(2.2) # 调低二值化阈值,保留数字3顶部的浅色像素 thresh = 180 fn = lambda x : 255 if x > thresh else 0 res = img.convert('L').point(fn, mode='1') # 加中值滤波去噪,消除细碎杂点干扰 res = res.filter(ImageFilter.MedianFilter(size=3)) res.save("res.jpg") # 改用psm 8模式(将整张图识别为单个词),明确限定只识别0-9数字,排除其他字符干扰 text = pytesseract.image_to_string("res.jpg",config='--psm 8 -c tessedit_char_whitelist=0123456789') print(text)
验证效果
修改后运行代码即可输出正确结果35860。
内容的提问来源于stack exchange,提问作者Никита Давыдов
相关产品推荐
相关产品推荐

