使用 Python 和 pytesseract 识别中文文字 - 完整代码和异常处理

本代码使用 Python 中的 pytesseract 库和 PIL 库,实现从图片中识别中文文字的功能。代码包含详细注释和异常处理机制,并提供安装说明,方便用户使用。

代码示例

import pytesseract
from PIL import Image

def recognize_chinese_text(img_path):
    '''
    使用 pytesseract 识别图片中的中文文字

    Args:
        img_path (str): 图片路径

    Returns:
        str: 识别出来的中文文字,如果发生异常则返回 None
    '''
    try:
        # 读取图片
        img = Image.open(img_path)
        # 转化为灰度图像
        img = img.convert('L')
        # 二值化处理
        threshold = 140
        table = []
        for i in range(256):
            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        img = img.point(table, '1')
        # 识别中文文字
        text = pytesseract.image_to_string(img, lang='chi_sim')
        return text
    except Exception as e:
        print(e)
        return None

安装依赖库

使用该代码前,需要先安装 pytesseractPillow 库:

pip install pytesseract
pip install Pillow

使用方法

该函数输入参数为图片路径,返回值为识别出来的中文文字。如果发生异常,会输出异常信息并返回 None

例如:

img_path = 'path/to/your/image.jpg'
text = recognize_chinese_text(img_path)

if text:
    print(f'识别结果:{text}')
else:
    print('识别失败')

注意事项

  • 为了确保识别效果,建议使用清晰度较高的图片。
  • 可以根据图片的具体情况调整二值化阈值 threshold
  • 如果识别结果不理想,可以尝试调整 pytesseract 库的配置参数,例如 config 参数。

希望本代码能够帮助您顺利实现图片中文文字识别功能。

Python 使用 pytesseract 识别中文文字 - 完整代码和异常处理

原文地址: https://www.cveoy.top/t/topic/mRBu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录