PaddleOCR 中,det
、rec
、cls
分别代表 OCR 流水线中的三个关键模块。
1. det - 文本检测(Text Detection)
功能
-
定位:在图像中找出文本所在的位置
-
边界框:为每个文本区域生成边界框
-
文本行检测:检测文本行或单词的位置
from paddleocr import PaddleOCR import cv2 import numpy as np# 只使用检测模型 ocr_det = PaddleOCR(det=True, rec=False, cls=False, use_gpu=False)def text_detection_only(image_path):"""仅进行文本检测"""result = ocr_det.ocr(image_path, cls=False)# 可视化检测结果image = cv2.imread(image_path)if result is not None:for line in result:if line:for word_info in line:# 获取检测框坐标points = np.array(word_info[0], dtype=np.int32)# 绘制检测框(绿色)cv2.polylines(image, [points], True, (0, 255, 0), 2)cv2.imshow('Detection Result', image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用示例 text_detection_only('test_image.jpg')
# 检测结果示例 [[[[10, 20], [100, 20], [100, 40], [10, 40]], 0.95], # 边界框坐标 + 置信度[[[50, 60], [200, 60], [200, 80], [50, 80]], 0.92] ]
2. rec - 文本识别(Text Recognition)
功能
-
字符识别:识别检测到的文本区域中的具体文字内容
-
序列识别:将图像中的文本转换为字符串
-
多语言支持:支持中文、英文、日文等多种语言
# 只使用识别模型(需要先有检测框) ocr_rec = PaddleOCR(det=False, rec=True, cls=False, use_gpu=False)def text_recognition_only(image_path, bboxes):"""仅进行文本识别(需要提供检测框)"""image = cv2.imread(image_path)recognition_results = []for bbox in bboxes:# 裁剪文本区域x_coords = [point[0] for point in bbox]y_coords = [point[1] for point in bbox]x_min, x_max = min(x_coords), max(x_coords)y_min, y_max = min(y_coords), max(y_coords)text_region = image[y_min:y_max, x_min:x_max]# 保存临时图片进行识别cv2.imwrite('temp_crop.jpg', text_region)# 识别文本result = ocr_rec.ocr('temp_crop.jpg', cls=False)if result and result[0]:text = result[0][0][1][0]confidence = result[0][0][1][1]recognition_results.append((text, confidence))return recognition_results# 使用示例 bboxes = [[[10, 20], [100, 20], [100, 40], [10, 40]], # 假设的检测框[[50, 60], [200, 60], [200, 80], [50, 80]] ] results = text_recognition_only('test_image.jpg', bboxes) for text, confidence in results:print(f"识别结果: {text}, 置信度: {confidence:.4f}")
3. cls - 方向分类(Text Orientation Classification)
功能
-
方向判断:判断文本是正向、反向、倒向还是侧向
-
自动校正:自动旋转文本到正确方向以提高识别准确率
-
多角度支持:支持0°、90°、180°、270°等方向
# 只使用方向分类模型 ocr_cls = PaddleOCR(det=False, rec=False, cls=True, use_gpu=False)def orientation_classification_only(image_path):"""仅进行方向分类"""result = ocr_cls.ocr(image_path, rec=False, det=False)if result is not None:for line in result:if line:for word_info in line:# 方向分类结果orientation = word_info[1][0] # 0, 90, 180, 270confidence = word_info[1][1]angle_map = {0: "0° (正向)", 90: "90° (顺时针)", 180: "180° (倒向)", 270: "270° (逆时针)"}print(f"文本方向: {angle_map.get(orientation, '未知')}")print(f"方向置信度: {confidence:.4f}")# 使用示例 orientation_classification_only('rotated_text.jpg')
4. 完整的 OCR 流水线
def complete_ocr_pipeline(image_path):""" 完整的OCR处理流程:det → cls → rec""" # 使用所有三个模块ocr = PaddleOCR(det=True, rec=True, cls=True, use_gpu=False)# 执行完整OCRresult = ocr.ocr(image_path, cls=True)print("=== 完整OCR处理流程 ===")if result is not None:for page_num, page in enumerate(result):print(f"\n--- 第 {page_num + 1} 页 ---")for line_num, line in enumerate(page):if line:print(f"\n文本行 {line_num + 1}:")for word_num, word_info in enumerate(line):if len(word_info) >= 2:# 检测结果bbox = word_info[0]text = word_info[1][0]confidence = word_info[1][1]print(f" 单词 {word_num + 1}:")print(f" 位置: {bbox}")print(f" 文本: {text}")print(f" 置信度: {confidence:.4f}")return result# 使用示例 complete_result = complete_ocr_pipeline('document.jpg')
5.实际应用场景
def practical_applications():""" 不同场景下的模块选择建议""" scenarios = {"文档扫描": "使用完整OCR (det+cls+rec) - 需要高精度","实时视频文字识别": "使用检测+识别 (det+rec) - 需要速度快","文字区域分析": "仅使用检测 (det) - 只需要位置信息","已有定位的文字识别": "仅使用识别 (rec) - 已有检测框","旋转文本处理": "使用分类+识别 (cls+rec) - 处理方向问题"}print("应用场景建议:")for scenario, recommendation in scenarios.items():print(f" {scenario}: {recommendation}")# 各模块的作用总结 def module_summary():""" 三模块功能总结""" summary = {'det': {'功能': '文本检测','输入': '原始图像','输出': '文本边界框坐标','用途': '找出图像中文本的位置','类似功能': 'YOLO、Faster R-CNN等目标检测'},'rec': {'功能': '文本识别', '输入': '裁剪的文本区域图像','输出': '识别出的文本内容','用途': '将图像文字转换为可读文本','类似功能': 'CRNN、TRBA等文字识别模型'},'cls': {'功能': '方向分类','输入': '文本区域图像', '输出': '文本方向角度','用途': '校正文本方向提高识别率','类似功能': '图像分类模型'}}for module, info in summary.items():print(f"\n=== {module.upper()} 模块 ===")for key, value in info.items():print(f" {key}: {value}")# 使用示例 module_summary() practical_applications()