在 OCR(光学字符识别)领域,国产开源项目 PaddleOCR 凭借其超轻量级、高精度和多语言支持,已成为事实上的工业级标杆。无论你是 AI 初学者还是寻找落地方案的工程师,这篇文章都能帮你快速上手 PP-OCRv4 模型。
PaddleOCR 简介:为什么选择它?
PaddleOCR 是基于百度飞桨(PaddlePaddle)开发的 OCR 工具库。它的核心优势在于:
- PP-OCR 系列模型:提供超轻量模型(适合移动端/嵌入式)和通用模型(适合服务器),在速度和精度之间取得了极佳平衡。目前最新的 PP-OCRv4 效果显著。
- 功能丰富:支持文本检测、文本识别、关键信息提取(KIE)、表格识别等。
- 多语言:支持中、英、法、德、韩、日等 80 多种语言。
环境搭建 (Environment Setup)
在开始之前,请确保你的环境安装了 Python 3.8+。
安装 PaddlePaddle
根据你的机器是否有 NVIDIA 显卡选择安装版本。
CPU 版本(通用,适合快速测试):
python -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
GPU 版本(推荐,速度更快,需安装 CUDA):
# 具体的 CUDA 版本号请参考官网 python -m pip install paddlepaddle-gpu -i https://mirror.baidu.com/pypi/simple
安装 PaddleOCR 及其依赖
一行命令安装核心库:
pip install "paddleocr>=2.0.1"
同时,为了后续可视化,建议安装 OpenCV 和 Matplotlib:
pip install opencv-python matplotlib
Python 核心实战:文字识别
接下来,我们编写一个 Python 脚本,使用 PP-OCRv4 模型识别一张包含中文的图片。
准备一张测试图片
假设你有一张名为 test_img.jpg 的图片(可以是发票、路牌或文档截图)。
编写代码
新建文件 ocr_demo.py:
from paddleocr import PaddleOCR, draw_ocr
import cv2
import matplotlib.pyplot as plt
# 1. 初始化 OCR 模型
# use_angle_cls=True: 自动加载方向分类器,用于纠正翻转的文字
# lang="ch": 设置语言为中文
print("正在加载模型...")
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
img_path =
()
result = ocr.ocr(img_path, cls=)
()
idx ((result)):
res = result[idx]
line res:
()
()
PIL Image
image = Image.(img_path).convert()
boxes = [line[] line result[]]
txts = [line[][] line result[]]
scores = [line[][] line result[]]
im_show = draw_ocr(image, boxes, txts, scores, font_path=)
im_show = Image.fromarray(im_show)
im_show.save()
()


