ocr-onnx.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. 使用 OnnxOCR 对图片做 OCR,结果输出为 JSON 到 stdout。
  5. 用法1: python ocr-onnx.py --image <图片路径> [--project-root <项目根目录>]
  6. 输出: {"success": true, "text": "识别结果"} 或 {"success": false, "error": "..."}
  7. 用法2: python ocr-onnx.py --image <图片路径> --find-text "要查找的文字" [--project-root <项目根目录>]
  8. 在图中查找该文字,返回中心点: {"success": true, "x": 123, "y": 456} 或 {"success": false, "error": "..."}
  9. """
  10. import sys
  11. import os
  12. import json
  13. import argparse
  14. def box_center(box):
  15. """box 为 4 个点 [[x1,y1],[x2,y2],[x3,y3],[x4,y4]],返回中心 (cx, cy)"""
  16. if not box or len(box) < 4:
  17. return None
  18. xs = [p[0] for p in box]
  19. ys = [p[1] for p in box]
  20. return (sum(xs) / len(xs), sum(ys) / len(ys))
  21. def normalize_for_match(s):
  22. """规范化后用于匹配:去空格、全角括号/数字转半角,便于 OCR 变体(如 下一步(1)、下一步(1))都能匹配 下一步"""
  23. if not s:
  24. return ''
  25. s = (s or '').strip().replace(' ', '').replace('\u3000', '')
  26. # 全角括号、数字 → 半角
  27. t = []
  28. for c in s:
  29. if c in ('(', '[', '{'): t.append('(')
  30. elif c in (')', ']', '}'): t.append(')')
  31. elif '\uff10' <= c <= '\uff19': t.append(chr(ord(c) - 0xfee0))
  32. else: t.append(c)
  33. return ''.join(t)
  34. def main():
  35. ap = argparse.ArgumentParser()
  36. ap.add_argument('--image', required=True, help='图片路径(绝对或相对)')
  37. ap.add_argument('--find-text', default=None, help='要查找的文字;若指定则返回该文字在图中的中心点 x,y')
  38. ap.add_argument('--project-root', default=None, help='项目根目录,用于解析相对路径及加载 onnxocr')
  39. args = ap.parse_args()
  40. project_root = args.project_root
  41. if not project_root:
  42. project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
  43. project_root = os.path.normpath(project_root)
  44. # 确保可导入 onnxocr(包在 python/onnxocr/onnxocr/,故将 python/onnxocr 加入 path)
  45. onnxocr_root = os.path.join(project_root, 'python', 'onnxocr')
  46. if onnxocr_root not in sys.path:
  47. sys.path.insert(0, onnxocr_root)
  48. image_path = args.image
  49. if not os.path.isabs(image_path):
  50. image_path = os.path.normpath(os.path.join(project_root, image_path))
  51. if not os.path.isfile(image_path):
  52. out = {'success': False, 'error': f'图片不存在: {image_path}'}
  53. print(json.dumps(out, ensure_ascii=False))
  54. return
  55. try:
  56. import cv2
  57. except ImportError:
  58. out = {'success': False, 'error': 'OpenCV 未安装,请安装: pip install opencv-python'}
  59. print(json.dumps(out, ensure_ascii=False))
  60. sys.exit(1)
  61. try:
  62. from onnxocr.onnx_paddleocr import ONNXPaddleOcr
  63. except ImportError as e:
  64. out = {'success': False, 'error': f'OnnxOCR 导入失败: {e}。请确保 python/onnxocr 已存在且可导入。'}
  65. print(json.dumps(out, ensure_ascii=False))
  66. sys.exit(1)
  67. try:
  68. img = cv2.imread(image_path)
  69. if img is None:
  70. out = {'success': False, 'error': f'无法读取图片: {image_path}'}
  71. print(json.dumps(out, ensure_ascii=False))
  72. sys.exit(1)
  73. model = ONNXPaddleOcr(
  74. use_angle_cls=True,
  75. use_gpu=False,
  76. det_db_thresh=0.2,
  77. det_db_box_thresh=0.45,
  78. drop_score=0.3,
  79. )
  80. result = model.ocr(img)
  81. find_text = (args.find_text or '').strip()
  82. find_norm = normalize_for_match(find_text)
  83. if find_text:
  84. # 模式2:查找文字,返回中心点(支持包含匹配与规范化匹配,如 "下一步" 可匹配 "下一步(1)"、"下一步(1)")
  85. if not result or not result[0]:
  86. out = {'success': False, 'error': f'图中未识别到文字,或未找到: "{find_text}"'}
  87. print(json.dumps(out, ensure_ascii=False))
  88. sys.exit(1)
  89. for line in result[0]:
  90. box, rec = line[0], line[1] if len(line) > 1 else None
  91. if not rec:
  92. continue
  93. text = (rec[0] or '').strip()
  94. text_norm = normalize_for_match(text)
  95. if (find_text in text or text == find_text or
  96. (find_norm and (find_norm in text_norm or text_norm == find_norm))):
  97. center = box_center(box)
  98. if center is not None:
  99. cx, cy = int(round(center[0])), int(round(center[1]))
  100. out = {'success': True, 'x': cx, 'y': cy}
  101. print(json.dumps(out, ensure_ascii=False))
  102. return
  103. out = {'success': False, 'error': f'图中未找到文字: "{find_text}"'}
  104. print(json.dumps(out, ensure_ascii=False))
  105. sys.exit(1)
  106. else:
  107. # 模式1:整图 OCR,返回全文
  108. if not result or not result[0]:
  109. text = ''
  110. else:
  111. lines = [line[1][0] for line in result[0] if line[1]]
  112. text = '\n'.join(lines) if lines else ''
  113. out = {'success': True, 'text': text}
  114. print(json.dumps(out, ensure_ascii=False))
  115. except Exception as e:
  116. out = {'success': False, 'error': str(e)}
  117. print(json.dumps(out, ensure_ascii=False))
  118. sys.exit(1)
  119. if __name__ == '__main__':
  120. main()