app-service.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import cv2
  2. import time
  3. import base64
  4. import numpy as np
  5. from flask import Flask, request, jsonify,render_template
  6. from onnxocr.onnx_paddleocr import ONNXPaddleOcr
  7. # 初始化 Flask 应用
  8. app = Flask(__name__)
  9. # 初始化 OCR 模型
  10. model = ONNXPaddleOcr(use_angle_cls=True, use_gpu=False)
  11. @app.route('/')
  12. def index():
  13. return render_template('index.html')
  14. @app.route('/ocr', methods=['POST'])
  15. def ocr_service():
  16. try:
  17. # 获取请求数据
  18. data = request.get_json()
  19. if not data or "image" not in data:
  20. return jsonify({"error": "Invalid request, 'image' field is required."}), 400
  21. # 解码 base64 图像
  22. image_base64 = data["image"]
  23. try:
  24. image_bytes = base64.b64decode(image_base64)
  25. image_np = np.frombuffer(image_bytes, dtype=np.uint8)
  26. img = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
  27. if img is None:
  28. return jsonify({"error": "Failed to decode image from base64."}), 400
  29. except Exception as e:
  30. return jsonify({"error": f"Image decoding failed: {str(e)}"}), 400
  31. # 执行 OCR
  32. start_time = time.time()
  33. result = model.ocr(img)
  34. end_time = time.time()
  35. processing_time = end_time - start_time
  36. # 格式化结果
  37. ocr_results = []
  38. for line in result[0]:
  39. # 确保 line[0] 是 NumPy 数组或列表
  40. if isinstance(line[0], (list, np.ndarray)):
  41. # 将 bounding_box 转换为 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] 格式
  42. bounding_box = np.array(line[0]).reshape(4, 2).tolist() # 转换为 4x2 列表
  43. else:
  44. bounding_box = []
  45. ocr_results.append({
  46. "text": line[1][0], # 识别文本
  47. "confidence": float(line[1][1]), # 置信度
  48. "bounding_box": bounding_box # 文本框坐标
  49. })
  50. # 返回结果
  51. return jsonify({
  52. "processing_time": processing_time,
  53. "results": ocr_results
  54. })
  55. except Exception as e:
  56. # 捕获所有异常并返回错误信息
  57. return jsonify({"error": f"An error occurred: {str(e)}"}), 500
  58. if __name__ == '__main__':
  59. # 启动 Flask 服务
  60. app.run(host="0.0.0.0", port=5005, debug=False)