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
相关推荐
The丶Star6 分钟前
【解决CMD命令行下无法正常打开jupyter notebook的特殊办法(关闭防火墙版)】
ide·python·jupyter
不讲魔法讲道理8 分钟前
(202506最新)Jupyter Notebook显示目录的导航栏
ide·python·jupyter
iCxhust18 分钟前
PC16550 UART接收中断处理完整示例代码
c语言·开发语言·stm32·单片机·嵌入式硬件
wt_cs22 分钟前
C#财政票查验接口集成-医疗发票查验-非税收入票据查验接口
开发语言·科技·安全·金融·ocr
苦学LCP的小猪37 分钟前
LeeCode94二叉树的中序遍历
数据结构·python·算法·leetcode
苗杨1 小时前
【Faster-Whisper】离线识别本地视频并生成字幕
python·whisper·音视频
Takoony1 小时前
HuggingFace镜像配置失效问题深度解析:Python模块导入机制的陷阱
python·ai
站大爷IP1 小时前
当Scrapy遇上分布式:让爬虫飞起来的实战指南
python
蓝婷儿1 小时前
Python 数据分析与可视化 Day 1 - Pandas 数据分析基础入门
python·数据分析·pandas
BillKu1 小时前
Vue3 + TypeScript 中 hook 优化记录
开发语言·javascript·typescript