Python 实现简单OCR文本识别

Ubuntu系统:22.04

python版本:3.9

安装依赖库:

bash 复制代码
# 安装Tesseract引擎和开发库
sudo apt update && sudo apt install tesseract-ocr libtesseract-dev

# 安装英语+中文语言包
sudo apt install tesseract-ocr-eng tesseract-ocr-chi-sim

# 安装Python依赖
pip install pytesseract pillow -i https://mirrors.aliyun.com/pypi/simple

代码实现:

python 复制代码
# 安装必要依赖(Ubuntu/Debian)
# 先执行以下终端命令:
# sudo apt update && sudo apt install tesseract-ocr libtesseract-dev
# sudo apt install tesseract-ocr-chi-sim  # 中文支持(可选)
# pip3 install pytesseract pillow

from PIL import Image
import pytesseract
import sys
import os

def ocr_core(image_path):
    """
    核心OCR函数
    :param image_path: 图片路径
    :return: 识别后的文本
    """
    try:
        if not os.path.exists(image_path):
            raise FileNotFoundError(f"文件 {image_path} 不存在")

        img = Image.open(image_path)
        
        # 多语言识别示例(英语+中文)
        text = pytesseract.image_to_string(img, lang='eng+chi_sim')
        
        return text.strip() if text else "未识别到文字"
    
    except Exception as e:
        return f"错误: {str(e)}"

if __name__ == "__main__":
    if len(sys.argv) > 1:
        image_path = sys.argv[1]
    else:
        image_path = input("请输入图片路径:").strip()
    
    print("\n识别中...")
    result = ocr_core(image_path)
    
    print("\n识别结果:")
    print("-" * 30)
    print(result)
    print("-" * 30)

下载测试图片:

bash 复制代码
# 下载测试图片(可选)
wget https://tesseract.projectnaptha.com/img/eng_bw.png -O test.png

# 执行识别
python ocr_demo.py test.png
相关推荐
Pyeako1 分钟前
opencv计算机视觉--DNN模块实现风格迁移
python·opencv·计算机视觉·pycharm·dnn·预处理·风格迁移
m0_706653231 分钟前
用Python创建一个Discord聊天机器人
jvm·数据库·python
枫叶丹43 分钟前
【Qt开发】Qt系统(十一)-> Qt 音频
c语言·开发语言·c++·qt·音视频
tlwlmy7 分钟前
python excel图片批量导出
开发语言·python·excel
ValhallaCoder9 分钟前
hot100-矩阵
数据结构·python·算法·矩阵
散峰而望9 分钟前
【基础算法】穷举的艺术:在可能性森林中寻找答案
开发语言·数据结构·c++·算法·随机森林·github·动态规划
那年我七岁11 分钟前
android ndk c++ 绘制图片方式
android·c++·python
Java后端的Ai之路11 分钟前
【Python教程10】-开箱即用
android·开发语言·python
散峰而望12 分钟前
【基础算法】算法的“预谋”:前缀和如何改变游戏规则
开发语言·数据结构·c++·算法·github·动态规划·推荐算法
深蓝电商API16 分钟前
异步爬虫中代理池的并发管理
开发语言·爬虫·python