defect_service.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import cv2
  2. import numpy as np
  3. from ..core.model_loader import get_predictor
  4. from app.utils.CardDefectAggregator import CardDefectAggregator
  5. from app.utils.arean_anylize_draw import DefectProcessor, DrawingParams
  6. from app.core.config import settings
  7. from app.core.logger import logger
  8. import json
  9. from typing import Tuple
  10. class DefectInferenceService:
  11. def defect_inference(self, inference_type: str, image_bytes: bytes,
  12. is_draw_image=False) -> dict:
  13. """
  14. 执行卡片识别推理。
  15. Args:
  16. inference_type: 模型类型 (e.g., 'outer_box').
  17. image_bytes: 从API请求中获得的原始图像字节。
  18. Returns:
  19. 一个包含推理结果的字典。
  20. """
  21. if inference_type == "pokemon_front_face_no_reflect_defect":
  22. # 1. 获取对应的预测器实例
  23. predictor = get_predictor(inference_type)
  24. # 2. 将字节流解码为OpenCV图像
  25. # 将字节数据转换为numpy数组
  26. np_arr = np.frombuffer(image_bytes, np.uint8)
  27. # 从numpy数组中解码图像
  28. img_bgr = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
  29. if img_bgr is None:
  30. raise ValueError("无法解码图像,请确保上传的是有效的图片格式 (JPG, PNG, etc.)")
  31. # 3. 调用我们新加的 predict_from_image 方法进行推理
  32. # result = predictor.predict_from_image(img_bgr)
  33. # 3. 实例化我们聚合器,传入预测器
  34. aggregator = CardDefectAggregator(
  35. predictor=predictor,
  36. tile_size=512,
  37. overlap_ratio=0.1, # 10% 重叠
  38. )
  39. json_data = aggregator.process_image(
  40. image=img_bgr,
  41. mode='face'
  42. )
  43. merge_json_path = settings.TEMP_WORK_DIR / 'merge.json'
  44. with open(merge_json_path, 'w', encoding='utf-8') as f:
  45. json.dump(json_data, f, ensure_ascii=False, indent=4)
  46. logger.info(f"合并结束")
  47. processor = DefectProcessor(pixel_resolution=settings.pixel_resolution)
  48. if is_draw_image:
  49. drawing_params_with_rect = DrawingParams(draw_min_rect=True)
  50. drawn_image_rect, result_rect = processor.analyze_and_draw(img_bgr, json_data,
  51. drawing_params_with_rect)
  52. temp_img_path = settings.TEMP_WORK_DIR / 'temp_area_result.jpg'
  53. cv2.imwrite(temp_img_path, drawn_image_rect)
  54. return result_rect
  55. else:
  56. result = processor.analyze_from_json(json_data)
  57. area_json_path = settings.TEMP_WORK_DIR / 'temp_area_result.json'
  58. with open(area_json_path, 'w', encoding='utf-8') as f:
  59. json.dump(result, f, ensure_ascii=False, indent=4)
  60. logger.info("面积计算结束")
  61. return result
  62. else:
  63. return {}
  64. # 创建一个单例服务
  65. defect_service = DefectInferenceService()