RuleImageMallResourceMixin.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # module/atom/image/image_mall_resource.py
  2. from module.logger import logger
  3. from module.atom.ocr import RuleOcr
  4. class RuleImageMallResourceMixin:
  5. """
  6. RuleImage 的 mall_resource 能力扩展
  7. """
  8. # mall_resource 专用偏移参数
  9. MALL_RESOURCE_X_OFFSET = 40
  10. MALL_RESOURCE_RIGHT_EXTEND = 70
  11. def match_and_get_roi(self, image, threshold=None):
  12. """
  13. - match 成功 → 返回 (x, y, w, h)
  14. - match 失败 / 异常 → 返回 None
  15. """
  16. try:
  17. ok = self.match(image, threshold)
  18. except Exception as e:
  19. logger.error(f"match exception: {e}")
  20. return None
  21. if not ok:
  22. return None
  23. try:
  24. mat = self.image
  25. if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
  26. return None
  27. h, w = mat.shape[:2]
  28. x = int(self.roi_front[0])
  29. y = int(self.roi_front[1])
  30. return (x, y, int(w), int(h))
  31. except Exception:
  32. return None
  33. def get_mall_resource_text_roi(self, image, threshold=None):
  34. """
  35. mall_resource 专用:
  36. - 定位 icon
  37. - 推导文本 OCR ROI
  38. return: roi or None
  39. """
  40. try:
  41. icon_roi = self.match_and_get_roi(image, threshold)
  42. if icon_roi is None:
  43. # 回退 roi_front
  44. ix, iy, iw, ih = self.roi_front
  45. else:
  46. ix, iy, iw, ih = icon_roi
  47. x = int(ix) + self.MALL_RESOURCE_X_OFFSET
  48. y = int(iy)
  49. w = int(iw) + self.MALL_RESOURCE_RIGHT_EXTEND
  50. h = int(ih)
  51. return (x, y, w, h)
  52. except Exception:
  53. return None
  54. def build_mall_resource_ocr(self, image, threshold=None, name="mall_resource"):
  55. """
  56. mall_resource 专用快捷方法:
  57. - 定位 icon
  58. - 推导 OCR ROI
  59. - 构造 RuleOcr
  60. return: RuleOcr | None
  61. """
  62. try:
  63. roi = self.get_mall_resource_text_roi(image, threshold)
  64. if roi is None:
  65. return None
  66. return RuleOcr(
  67. roi=roi,
  68. area=roi,
  69. mode="Quantity",
  70. method="Default",
  71. keyword="",
  72. name=name
  73. )
  74. except Exception:
  75. return None