card_rectify_and_center.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import cv2
  2. import numpy as np
  3. from ..core.model_loader import get_predictor
  4. from app.utils.defect_inference.img_rectify_and_center import (
  5. FryCardProcessParams, FryCardProcessor, CenterMode, FillMode)
  6. from app.core.config import settings
  7. from app.core.logger import get_logger
  8. import json
  9. logger = get_logger(__name__)
  10. class CardRectifyAndCenter:
  11. def __init__(self):
  12. self.inference_type = "outer_box"
  13. self.outer_box_model = get_predictor(self.inference_type)
  14. def _keep_max_prob_shape(self, json_data: dict) -> dict:
  15. """
  16. 辅助函数:过滤掉低置信度的框,只保留 probability 最大的那一个。
  17. """
  18. if not json_data or 'shapes' not in json_data or not json_data['shapes']:
  19. return json_data
  20. shapes = json_data['shapes']
  21. # 如果只有一个,直接返回
  22. if len(shapes) == 1:
  23. return json_data
  24. logger.info(f"检测到 {len(shapes)} 个外框,开始筛选最大置信度目标...")
  25. # 使用 max 函数找出 probability 最大的 shape
  26. # x.get('probability', 0) 确保如果字段不存在默认为0
  27. best_shape = max(shapes, key=lambda x: x.get('probability', 0))
  28. logger.info(f"筛选结果: 保留置信度为 {best_shape.get('probability')} 的目标,"
  29. f"丢弃了其他 {len(shapes) - 1} 个目标。")
  30. # 重新赋值给 shapes,保持列表结构
  31. json_data['shapes'] = [best_shape]
  32. # 同时更新 num 数量,保持数据一致性
  33. if 'num' in json_data:
  34. json_data['num'] = 1
  35. return json_data
  36. def rectify_and_center(self, img_bgr: np.ndarray) -> np.ndarray:
  37. # 1. 设置处理参数
  38. params = FryCardProcessParams(
  39. debug_level="detail",
  40. label_name="outer_box",
  41. center_mode=CenterMode.BOUNDING_RECT,
  42. fill_mode=FillMode.BLACK
  43. )
  44. # 2. 初始化处理器
  45. processor = FryCardProcessor()
  46. seg_json = self.outer_box_model.predict_from_image(img_bgr)
  47. # 过滤噪点,只留最大置信度的外框
  48. seg_json = self._keep_max_prob_shape(seg_json)
  49. # 4. 执行处理
  50. final_image = processor.process_image_with_json(img_bgr, seg_json, params)
  51. temp_img_path = settings.TEMP_WORK_DIR / "rectify_center_img.jpg"
  52. cv2.imwrite(temp_img_path, final_image)
  53. return final_image