PaddleOCR批量文件识别与Excel导出全流程指南

一、环境准备与脚本配置

1.1 虚拟环境激活脚本

在Windows系统中,建议通过批处理脚本实现环境自动化启动。新建start_ocr.bat文件,内容如下:

  1. @echo off
  2. start cmd /k "activate ocr_env && cd /d D:\OCR_Project && python main_process.py"

关键参数说明:

  • activate ocr_env:激活预先创建的Python虚拟环境(名称可自定义)
  • cd /d:跨磁盘跳转目录的DOS命令
  • python main_process.py:指定主处理脚本

1.2 环境依赖管理

推荐使用conda创建隔离环境:

  1. conda create -n ocr_env python=3.8
  2. conda activate ocr_env
  3. pip install paddlepaddle paddleocr openpyxl pandas

版本选择建议:

  • PaddlePaddle:2.4+(支持动态图模式)
  • PaddleOCR:最新稳定版
  • Excel处理库:openpyxl(轻量)或pandas(复杂数据处理)

二、核心代码改造

2.1 识别结果结构优化

原始paddleocr.py的识别结果处理逻辑存在冗余,修改__call__方法返回结构:

  1. # 修改前(原代码片段)
  2. if not dt_boxes and not rec_res:
  3. ocr_res.append(None)
  4. continue
  5. tmp_res = [[box.tolist(), res] for box, res in zip(dt_boxes, rec_res)]
  6. ocr_res.append(tmp_res)
  7. # 修改后(优化版)
  8. if not dt_boxes or not rec_res:
  9. ocr_res.append({"text": "", "boxes": [], "confidence": 0})
  10. continue
  11. # 结构化存储:文本内容+坐标+置信度
  12. structured_res = []
  13. for box, text in zip(dt_boxes, rec_res):
  14. structured_res.append({
  15. "text": text[0],
  16. "boxes": box.tolist(),
  17. "confidence": text[1]
  18. })
  19. ocr_res.append(structured_res)

改进点:

  1. 使用字典结构替代嵌套列表,提升可读性
  2. 增加置信度字段,便于后续质量筛选
  3. 统一空结果处理逻辑

2.2 批量处理增强

tools/infer/utility.py中添加批量处理接口:

  1. def batch_ocr(image_dir, output_excel):
  2. """
  3. 批量OCR处理主函数
  4. :param image_dir: 图片目录路径
  5. :param output_excel: 输出Excel路径
  6. """
  7. from paddleocr import PaddleOCR
  8. import os
  9. import pandas as pd
  10. ocr = PaddleOCR(use_angle_cls=True, lang='ch')
  11. results = []
  12. for img_name in os.listdir(image_dir):
  13. if not img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
  14. continue
  15. img_path = os.path.join(image_dir, img_name)
  16. result = ocr.ocr(img_path, cls=True)
  17. # 提取首个有效结果(根据实际需求调整)
  18. if result and result[0]:
  19. text_data = []
  20. for line in result[0]:
  21. text_data.append({
  22. 'image': img_name,
  23. 'text': line[1][0],
  24. 'position': str(line[0]),
  25. 'confidence': line[1][1]
  26. })
  27. results.extend(text_data)
  28. # 写入Excel
  29. df = pd.DataFrame(results)
  30. df.to_excel(output_excel, index=False,
  31. engine='openpyxl',
  32. sheet_name='OCR_Results')

三、自动化工作流构建

3.1 主处理脚本设计

创建main_process.py实现完整流程:

  1. import os
  2. from batch_ocr import batch_ocr # 假设上述函数保存在此模块
  3. def main():
  4. # 配置参数
  5. config = {
  6. "input_dir": "./input_images",
  7. "output_file": "./results/ocr_output.xlsx",
  8. "log_file": "./logs/ocr_process.log"
  9. }
  10. # 创建必要目录
  11. os.makedirs(os.path.dirname(config["output_file"]), exist_ok=True)
  12. try:
  13. # 执行OCR处理
  14. batch_ocr(config["input_dir"], config["output_file"])
  15. with open(config["log_file"], 'w') as f:
  16. f.write("OCR处理完成,结果已保存至:%s" % config["output_file"])
  17. except Exception as e:
  18. with open(config["log_file"], 'w') as f:
  19. f.write(f"处理失败:{str(e)}")
  20. if __name__ == "__main__":
  21. main()

3.2 异常处理机制

建议增加以下增强功能:

  1. 重试机制:对识别失败的图片自动重试3次

    1. def robust_ocr(ocr_instance, img_path, max_retries=3):
    2. for attempt in range(max_retries):
    3. try:
    4. result = ocr_instance.ocr(img_path, cls=True)
    5. if result and result[0]:
    6. return result
    7. except Exception as e:
    8. if attempt == max_retries - 1:
    9. raise
    10. continue
  2. 结果验证:检查关键字段是否存在

    1. def validate_result(result):
    2. if not result or not isinstance(result, list):
    3. return False
    4. for line in result[0]:
    5. if not all(k in line[1] for k in ['text', 'confidence']):
    6. return False
    7. return True

四、性能优化建议

4.1 多线程加速

使用concurrent.futures实现并行处理:

  1. from concurrent.futures import ThreadPoolExecutor
  2. def parallel_ocr(image_paths, ocr_instance, max_workers=4):
  3. results = []
  4. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  5. future_to_path = {
  6. executor.submit(ocr_instance.ocr, path, True): path
  7. for path in image_paths
  8. }
  9. for future in concurrent.futures.as_completed(future_to_path):
  10. path = future_to_path[future]
  11. try:
  12. results.append((path, future.result()))
  13. except Exception as e:
  14. results.append((path, None))
  15. return results

4.2 资源管理

  1. GPU加速:安装GPU版PaddlePaddle
  2. 内存优化
    • 分批处理超大规模图片集
    • 及时释放不再使用的变量
      1. import gc
      2. del large_variable
      3. gc.collect()

五、部署方案选择

5.1 本地部署

适用场景:

  • 数据敏感性高
  • 网络环境受限
  • 定制化需求强

5.2 容器化部署

Dockerfile示例:

  1. FROM python:3.8-slim
  2. WORKDIR /app
  3. COPY requirements.txt .
  4. RUN pip install -r requirements.txt --no-cache-dir
  5. COPY . .
  6. CMD ["python", "main_process.py"]

5.3 定时任务集成

通过Windows任务计划或crontab实现自动化:

  1. # 每日凌晨2点执行
  2. 0 2 * * * /usr/bin/python3 /path/to/main_process.py >> /var/log/ocr.log 2>&1

六、结果可视化扩展

6.1 Excel高级处理

使用pandas实现数据透视:

  1. import pandas as pd
  2. df = pd.read_excel('ocr_output.xlsx')
  3. # 按图片分组统计字数
  4. pivot_table = df.groupby('image')['text'].agg({
  5. 'total_chars': 'count',
  6. 'avg_confidence': 'mean'
  7. })

6.2 生成可视化报告

结合matplotlib创建统计图表:

  1. import matplotlib.pyplot as plt
  2. # 字数分布直方图
  3. plt.figure(figsize=(10,6))
  4. df['text_length'] = df['text'].apply(len)
  5. plt.hist(df['text_length'], bins=20, edgecolor='black')
  6. plt.title('Text Length Distribution')
  7. plt.xlabel('Character Count')
  8. plt.ylabel('Frequency')
  9. plt.savefig('length_distribution.png')

通过以上系统化改造,原始的简单脚本可升级为企业级OCR处理解决方案,具备高可用性、可扩展性和可维护性。实际部署时建议增加监控告警模块,实时跟踪处理进度和异常情况。