image.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import cv2
  5. import numpy as np
  6. from numpy import float32, int32, uint8, fromfile
  7. from pathlib import Path
  8. from module.base.decorator import cached_property
  9. from module.logger import logger
  10. class RuleImage:
  11. def __init__(self, roi_front: tuple, roi_back: tuple, method: str, threshold: float, file: str) -> None:
  12. """
  13. 初始化
  14. :param roi_front: 前置roi
  15. :param roi_back: 后置roi 用于匹配的区域
  16. :param method: 匹配方法
  17. :param threshold: 阈值
  18. :param file: 相对路径, 带后缀
  19. """
  20. self.roi_front = roi_front
  21. self.roi_back = roi_back
  22. self.method = method
  23. self.threshold = threshold
  24. self.file = file
  25. self._image = None # 这个是匹配的目标
  26. @cached_property
  27. def name(self) -> str:
  28. """
  29. :return:
  30. """
  31. return Path(self.file).stem
  32. def __str__(self):
  33. return self.name
  34. __repr__ = __str__
  35. def __eq__(self, other):
  36. return str(self) == str(other)
  37. def __hash__(self):
  38. return hash(self.name)
  39. def __bool__(self):
  40. return True
  41. def load_image(self) -> None:
  42. """
  43. 加载图片
  44. :return:
  45. """
  46. if self._image is not None:
  47. return
  48. img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
  49. # self._image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  50. self._image = img
  51. height, width, channels = self._image.shape
  52. if height != self.roi_front[3] or width != self.roi_front[2]:
  53. self.roi_front[2] = width
  54. self.roi_front[3] = height
  55. logger.info(f"roi_front size changed to {width}x{height}")
  56. @property
  57. def image(self):
  58. """
  59. 获取图片
  60. :return:
  61. """
  62. if self._image is None:
  63. self.load_image()
  64. return self._image
  65. @cached_property
  66. def is_template_match(self) -> bool:
  67. """
  68. 是否是模板匹配
  69. :return:
  70. """
  71. return self.method == "Template matching"
  72. def corp(self, image: np.array) -> np.array:
  73. """
  74. 截取图片
  75. :param image:
  76. :return:
  77. """
  78. x, y, w, h = self.roi_back
  79. return image[y:y + h, x:x + w]
  80. def match(self, image: np.array, threshold: float = None) -> bool:
  81. """
  82. :param threshold:
  83. :param image:
  84. :return:
  85. """
  86. if threshold is None:
  87. threshold = self.threshold
  88. if not self.is_template_match:
  89. raise Exception(f"unknown method {self.method}")
  90. source = self.corp(image)
  91. mat = self.image
  92. res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  93. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
  94. if max_val > threshold:
  95. return True
  96. else:
  97. return False
  98. def coord(self) -> tuple:
  99. """
  100. 获取roi_front的随机的点击的坐标
  101. :return:
  102. """
  103. x, y, w, h = self.roi_front
  104. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  105. def coord_more(self) -> tuple:
  106. """
  107. 获取roi_back的随机的点击的坐标
  108. :return:
  109. """
  110. x, y, w, h = self.roi_back
  111. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  112. if __name__ == "__main__":
  113. pass