pytesseract文字识别,提高准确率的方法

该代码实现了一个Python类,用于识别图像中的文本。它首先通过欧几里得距离计算对图像进行颜色对比,转化为白底黑字,然后使用pytesseract库进行文字识别,主要针对数字进行识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import math ,pytesseract ,cv2
from PIL import Image


class identifyText:

    def __init__(self) -> None:
        # 定义相似颜色的阈值,5~200之间为最佳值,5~500为有效值
        self.threshold = 100

        img_path = r'screen\screen.png'
        new_img_path = r'screen\new_screen.png'

        if self.transformedImage(img_path ,new_img_path):
            print(self.characterRecognition(new_img_path))


    # 计算两个颜色之间的欧几里得距离
    def color_distance(self ,c1 ,c2):
        # 如果图片没有透明通道则不需要传入和计算a通道
        r1, g1, b1, a1 = c1
        r2, g2, b2, a2 = c2
        return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2 + (a1-a2)**2)

    # 转化图像为白底黑字,以提高识别准确性
    def transformedImage(self ,img_path ,new_img_path):

        # 打开原图
        img = Image.open(img_path)
        # 创建一个白色的背景图像
        new_img = Image.new('RGBA', img.size, (255, 255, 255, 255))

        # 遍历所有像素点
        for x in range(img.width):
            for y in range(img.height):
                # 获取当前像素点的颜色
                color = img.getpixel((x, y))
                # 如果原图当前坐标颜色与给定颜色相似,则在背景图中相同的坐标写入黑色像素点
                if self.color_distance(color, (247, 245, 244, 255)) < self.threshold:
                    new_img.putpixel((x, y), (0,0,0,255))

        # 保存新图像
        new_img.save(new_img_path)
        return True

    # 文字识别
    def characterRecognition(self ,new_img_path):
        # 感觉好像没有必要进行灰度和二值化处理了,白底黑字的准确性挺高的,代码留这,你们自己看着整

            # 读取新图像
            # img = cv2.imread(new_img_path)
            # # 将图片转换为灰度图像
            # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # # 对图像进行二值化处理
            # thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
            # config = "--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789"
            # text = pytesseract.image_to_string(thresh, config=config)

        # 读取新图像
        img = cv2.imread(new_img_path)
        # 进行文字识别
        # --psm 7 单行识别 , --oem 3 使用 LSTM OCR 引擎 , -c tessedit_char_whitelist=0123456789 只识别数字字符
        config = "--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789"
        text = pytesseract.image_to_string(img, config=config)

        # 防止识别不到报错
        try:
            # 去除其他符号,对数字进行重新整合
            return int(''.join(filter(str.isdigit, text)))
        except Exception:
            return '未能识别文字'

if __name__ == "__main__":
    identifyText()
### 提高 Pytesseract 对中文字符的识别准确性 为了提升 Pytesseract 处理中文字符时的识别精度,可以从以下几个方面入手: #### 1. 安装并配置 Tesseract 中文支持包 确保安装了适用于中文的语言数据文件 `chi_sim.traineddata` 或者 `chi_tra.traineddata`。这些训练好的模型能够显著改善对于简体或繁体中文的支持。 ```bash # 下载官方提供的语言包到指定目录下 wget https://github.com/tesseract-ocr/tessdata/raw/main/chi_sim.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/ ``` 设置好路径之后,在 Python 脚本里加载对应的语种参数: ```python import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' custom_config = '--oem 3 --psm 6 -l chi_sim' text = pytesseract.image_to_string(Image.open('chinese_image.png'), config=custom_config) print(text) ``` 此处 `-l chi_sim` 表示使用简体中文作为目标语言[^1]。 #### 2. 图像预处理优化 图像质量直接影响 OCR 结果的好坏。可以通过调整对比度、亮度以及去除噪声等方式来增强输入图片的质量,从而间接提高识别成功率。 ```python from PIL import ImageEnhance, ImageFilter def preprocess_image(image_path): img = Image.open(image_path).convert('L') # 转灰度图 enhancer = ImageEnhance.Contrast(img) enhanced_img = enhancer.enhance(2) # 增加对比度 cleaned_img = enhanced_img.filter(ImageFilter.MedianFilter()) # 减少噪点 return cleaned_img ``` 经过上述方法处理后的图像再传递给 Pytesseract 进行解析通常可以获得更好的效果[^3]。 #### 3. 版面分析模式的选择 适当选择页面分割模式 (Page Segmentation Mode),即 PSM 参数可以帮助系统更好地理解文档结构,进而改进整体性能。例如当面对单行文本时可以选择更合适的 psm 模式以获得更高的准确率。 ```python configurations_for_single_line_text = '--oem 3 --psm 7 -l chi_sim' single_line_text = pytesseract.image_to_string(preprocess_image('line_of_chinese_characters.jpg'), config=configurations_for_single_line_text) print(single_line_text.strip()) ``` 这里选择了PSM值为7表示假设输入是一整行文字[^4]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值