rapidocr文本识别

 

  最近项目又需要识别文本了,且要求速度快,需要从图片里提取文字。最初考虑用大厂的云端API后改用glm-ocr,使用ollama部署,但速度不是足够快(可能使用tensorrt-LLM部署会更快)。折腾了一圈,最后发现了RapidOCR这个宝藏项目——完全离线、开源免费、而且真的很快。RapidOCR是一个基于深度学习的跨平台离线OCR框架,支持在Windows、Linux、macOS甚至Android和iOS上运行,所有计算都在本地完成,无需联网。项目最初是基于百度的PaddleOCR模型,但开发者发现PaddleOCR的工程化不太方便,于是把它转换成了ONNX格式,用Python/C++/Java/C#等多种语言移植到各个平台。

  这篇文章就当作一份学习笔记,分享给同样对OCR技术感兴趣的朋友。

 

 1.GPU版rapidocr测试代码

import os
import time
import traceback
import cv2
import numpy as np

# ==========================================
# 💡 黑科技:动态注入独立的 cuDNN 9 路径 (保护系统环境)
# ==========================================
try:
    import nvidia.cudnn

    cudnn_path = os.path.join(os.path.dirname(nvidia.cudnn.__file__), 'bin')
    os.environ['PATH'] = cudnn_path + ';' + os.environ.get('PATH', '')
    print(f"🔧 已动态注入 cuDNN 9 路径: {cudnn_path}")
except ImportError:
    print("⚠️ 未安装 nvidia-cudnn-cu12,如果 GPU 启动失败请先 pip install")

# 导入 ONNX 版的 RapidOCR
from rapidocr_onnxruntime import RapidOCR
import onnxruntime as ort

print("========================================================")
print(f"🔍 ONNX 当前可用后端: {ort.get_available_providers()}")
print("========================================================\n")

print("🚀 正在全局初始化【GPU】模型...")
engine_gpu = RapidOCR(det_use_cuda=True, cls_use_cuda=False, rec_use_cuda=True)  # cls_use_cuda=False,   # 👈 这里改成 False,让方向分类回归 CPU
print("✅ GPU 模型加载完毕!\n")

print("💻 正在全局初始化【CPU】模型...")
engine_cpu = RapidOCR(det_use_cuda=False, cls_use_cuda=False, rec_use_cuda=False)
print("✅ CPU 模型加载完毕!\n")


def detect_rapid_ocr(engine, image):
    if image is None:
        return None, None

    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    t1 = time.perf_counter()

    try:
        result, elapse_list = engine(image_rgb)
    except Exception as e:
        print(f"❌ OCR推理失败: {e}")
        return None, None

    t2 = time.perf_counter()
    total_time = (t2 - t1) * 1000

    if elapse_list and len(elapse_list) >= 3:
        det_t, cls_t, rec_t = elapse_list[0] * 1000, elapse_list[1] * 1000, elapse_list[2] * 1000
        print(f"⏱ 推理耗时: {total_time:.2f} ms (检测: {det_t:.1f}ms, 方向: {cls_t:.1f}ms, 识别: {rec_t:.1f}ms)")
    else:
        print(f"⏱ 推理耗时: {total_time:.2f} ms")

    return result


def get_original_data(result_gpu): #单个图片的
    single_image_text=[]
    for item in result_gpu:
        text=item[1]
        single_image_text.append(text)
    str_text="\n".join(single_image_text)
    return str_text





if __name__ == '__main__':
    TEST_IMAGE_PATH = "0_3-rectangle.jpg"
    image = cv2.imread(TEST_IMAGE_PATH)

    if image is None:
        print(f"❌ 无法读取图像: {TEST_IMAGE_PATH}")
    else:
        # ---------------------------------------------------
        print("\n" + "🟩" * 20 + " GPU 测试 " + "🟩" * 20)
        print("▶️ GPU 第一次 (包含显存分配预热):")
        detect_rapid_ocr(engine_gpu, image)

        print("\n▶️ GPU 第二次 (满血极速):")
        detect_rapid_ocr(engine_gpu, image)

        print("\n▶️ GPU 第三次 (满血极速):")
        result_gpu = detect_rapid_ocr(engine_gpu, image)
        str_text=get_original_data(result_gpu)
        print(str_text)


        # ---------------------------------------------------
        # print("\n" + "🟦" * 20 + " CPU 测试 " + "🟦" * 20)
        # print("▶️ CPU 第一次:")
        # detect_rapid_ocr(engine_cpu, image)
        #
        # print("\n▶️ CPU 第二次:")
        # detect_rapid_ocr(engine_cpu, image)
        #
        # # ---------------------------------------------------
        # if result_gpu:
        #     print("\n" + "=" * 60)
        #     print(f"📋 成功检测到 {len(result_gpu)} 行文字!(输出第一行确认: {result_gpu[0][1]})")
        #     print("=" * 60)
        #
        # print("gpu识别的内容",result_gpu) #[[[[86.0, 154.0], [914.0, 143.0], [915.0, 268.0], [87.0, 279.0]], 'COMMSCOPE', 0.9432738688257005],.......

  识别结果包括文本内容,文本位置,置信度。

image_001

image

 

识别效果不好时先调参数:官方提供了三个核心参数:

  • box_thresh:控制文本检测的灵敏度,调低可以检出更模糊的文字

  • text_score:控制识别结果的可信度阈值

  • unclip_ratio:控制检测框的大小,调大可以让检测框更宽松

 

2. 优点

1. 隐私安全,离线运行

这是最打动我的一点。所有图像处理都在本地完成,不需要把任何数据上传到服务器。对于处理合同、病历、身份证这类敏感信息来说,这个优势很关键

2. 轻量但能打

核心模型压缩后只有几MB,但识别精度相当不错。RapidOCR采用了CRNN+CTC的轻量级网络结构,参数量相比传统模型减少了约70%,同时通过知识蒸馏和8位整数量化技术进一步压缩模型体积,推理速度能提升2-3倍

3. 跨平台,多语言

不仅支持常见的桌面操作系统,还能跑到移动端和嵌入式设备上(比如树莓派)。内置了50+种语言模型,中英日韩阿拉伯文都能处理

4. API设计极其简洁

from rapidocr import RapidOCR

ocr = RapidOCR()
result = ocr.ocr("test.jpg")

for line in result:
    print(f"文本: {line['text']}, 置信度: {line['confidence']:.2f}")

 

 

 小结:前面代码中给的是gpu版本的rapidocr,相对于前面介绍的glm-ocr而言,rapidocr模型识别准确率稍逊,但也非常高,而且速度无论是CPu还是GPU都非常快,对于1300x1400文本标签,十多行内容,3060显卡就达到了 300多毫秒,对于如果是印刷体,且很清晰,且需要知道每段文本的具体位置,直接使用rapidocr即可。

 

posted @ 2026-07-25 10:23  wancy  阅读(4)  评论(0)    收藏  举报