image.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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: 匹配方法 "Template matching"
  17. :param threshold: 阈值 0.8
  18. :param file: 相对路径, 带后缀
  19. """
  20. self._match_init = False # 这个是给后面的 等待图片稳定
  21. self._image = None # 这个是匹配的目标
  22. self._kp = None #
  23. self._des = None
  24. self.method = method
  25. self.roi_front: list = list(roi_front)
  26. self.roi_back = roi_back
  27. self.threshold = threshold
  28. self.file = file
  29. @cached_property
  30. def name(self) -> str:
  31. """
  32. :return:
  33. """
  34. return Path(self.file).stem.upper()
  35. def __str__(self):
  36. return self.name
  37. __repr__ = __str__
  38. def __eq__(self, other):
  39. return str(self) == str(other)
  40. def __hash__(self):
  41. return hash(self.name)
  42. def __bool__(self):
  43. return True
  44. def load_image(self) -> None:
  45. """
  46. 加载图片
  47. :return:
  48. """
  49. if self._image is not None:
  50. return
  51. img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
  52. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  53. self._image = img
  54. height, width, channels = self._image.shape
  55. if height != self.roi_front[3] or width != self.roi_front[2]:
  56. self.roi_front[2] = width
  57. self.roi_front[3] = height
  58. logger.info(f"roi_front size changed to {width}x{height}")
  59. def load_kp_des(self) -> None:
  60. if self._kp is not None and self._des is not None:
  61. return
  62. self._kp, self._des = self.sift.detectAndCompute(self.image, None)
  63. @property
  64. def image(self):
  65. """
  66. 获取图片
  67. :return:
  68. """
  69. if self._image is None:
  70. self.load_image()
  71. return self._image
  72. @cached_property
  73. def is_template_match(self) -> bool:
  74. """
  75. 是否是模板匹配
  76. :return:
  77. """
  78. return self.method == "Template matching"
  79. @cached_property
  80. def is_sift_flann(self) -> bool:
  81. return self.method == "Sift Flann"
  82. @cached_property
  83. def sift(self):
  84. return cv2.SIFT_create()
  85. @cached_property
  86. def kp(self):
  87. if self._kp is None:
  88. self.load_kp_des()
  89. return self._kp
  90. @cached_property
  91. def des(self):
  92. if self._des is None:
  93. self.load_kp_des()
  94. return self._des
  95. def corp(self, image: np.array, roi: list = None) -> np.array:
  96. """
  97. 截取图片
  98. :param image:
  99. :param roi
  100. :return:
  101. """
  102. if roi is None:
  103. x, y, w, h = self.roi_back
  104. else:
  105. x, y, w, h = roi
  106. x, y, w, h = int(x), int(y), int(w), int(h)
  107. return image[y:y + h, x:x + w]
  108. def match(self, image: np.array, threshold: float = None) -> bool:
  109. """
  110. :param threshold:
  111. :param image:
  112. :return:
  113. """
  114. if threshold is None:
  115. threshold = self.threshold
  116. if not self.is_template_match:
  117. return self.sift_match(image)
  118. # raise Exception(f"unknown method {self.method}")
  119. source = self.corp(image)
  120. mat = self.image
  121. res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  122. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
  123. # logger.attr(self.name, max_val)
  124. if max_val > threshold:
  125. self.roi_front[0] = max_loc[0] + self.roi_back[0]
  126. self.roi_front[1] = max_loc[1] + self.roi_back[1]
  127. return True
  128. else:
  129. return False
  130. def match_all(self, image: np.array, threshold: float = None, roi: list = None) -> list[tuple]:
  131. """
  132. 区别于match,这个是返回所有的匹配结果
  133. :param roi:
  134. :param image:
  135. :param threshold:
  136. :return:
  137. """
  138. if roi is not None:
  139. self.roi_back = roi
  140. if threshold is None:
  141. threshold = self.threshold
  142. if not self.is_template_match:
  143. raise Exception(f"unknown method {self.method}")
  144. source = self.corp(image)
  145. mat = self.image
  146. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  147. locations = np.where(results >= threshold)
  148. matches = []
  149. for pt in zip(*locations[::-1]): # (x, y) coordinates
  150. score = results[pt[1], pt[0]]
  151. # 得分, x, y, w, h
  152. x = self.roi_back[0] + pt[0]
  153. y = self.roi_back[1] + pt[1]
  154. matches.append((score, x, y, mat.shape[1], mat.shape[0]))
  155. return matches
  156. def coord(self) -> tuple:
  157. """
  158. 获取roi_front的随机的点击的坐标
  159. :return:
  160. """
  161. x, y, w, h = self.roi_front
  162. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  163. def coord_more(self) -> tuple:
  164. """
  165. 获取roi_back的随机的点击的坐标
  166. :return:
  167. """
  168. x, y, w, h = self.roi_back
  169. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  170. def front_center(self) -> tuple:
  171. """
  172. 获取roi_front的中心坐标
  173. :return:
  174. """
  175. x, y, w, h = self.roi_front
  176. return int(x + w//2), int(y + h//2)
  177. def test_match(self, image: np.array):
  178. if self.is_template_match:
  179. return self.match(image)
  180. if self.is_sift_flann:
  181. return self.sift_match(image, show=True)
  182. def sift_match(self, image: np.array, show=False) -> bool:
  183. """
  184. 特征匹配,同样会修改 roi_front
  185. :param image: 是游戏的截图,就是转通道后的截图
  186. :param show: 测试用的
  187. :return:
  188. """
  189. source = self.corp(image)
  190. kp, des = self.sift.detectAndCompute(source, None)
  191. # 参数1:index_params
  192. # 对于SIFT和SURF,可以传入参数index_params=dict(algorithm=FLANN_INDEX_KDTREE, trees=5)。
  193. # 对于ORB,可以传入参数index_params=dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12)。
  194. index_params = dict(algorithm=1, trees=5)
  195. # 参数2:search_params 指定递归遍历的次数,值越高结果越准确,但是消耗的时间也越多。
  196. search_params = dict(checks=50)
  197. # 根据设置的参数创建特征匹配器 指定匹配的算法和kd树的层数,指定返回的个数
  198. flann = cv2.FlannBasedMatcher(index_params, search_params)
  199. # 利用创建好的特征匹配器利用k近邻算法来用模板的特征描述符去匹配图像的特征描述符,k指的是返回前k个最匹配的特征区域
  200. # 返回的是最匹配的两个特征点的信息,返回的类型是一个列表,列表元素的类型是Dmatch数据类型,具体是什么我也不知道
  201. # 第一个参数是小图的des, 第二个参数是大图的des
  202. matches = flann.knnMatch(self.des, des, k=2)
  203. good = []
  204. result = True
  205. for i, (m, n) in enumerate(matches):
  206. # 设定阈值, 距离小于对方的距离的0.7倍我们认为是好的匹配点.
  207. if m.distance < 0.6 * n.distance:
  208. good.append(m)
  209. if len(good) >= 10:
  210. src_pts = float32([self.kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  211. dst_pts = float32([kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  212. # 计算透视变换矩阵m, 要求点的数量>=4
  213. m, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
  214. # 创建一个包含模板图像四个角坐标的数组
  215. w, h = self.roi_front[2], self.roi_front[3]
  216. pts = float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
  217. if m is None:
  218. result = False
  219. else:
  220. dst = int32(cv2.perspectiveTransform(pts, m))
  221. self.roi_front[0] = dst[0, 0, 0] + self.roi_back[0]
  222. self.roi_front[1] = dst[0, 0, 1] + self.roi_back[1]
  223. if show:
  224. cv2.polylines(source, [dst], isClosed=True, color=(0, 0, 255), thickness=2)
  225. else:
  226. result = False
  227. # https://blog.csdn.net/cungudafa/article/details/105399278
  228. # https://blog.csdn.net/qq_45832961/article/details/122776322
  229. if show:
  230. # 准备一个空的掩膜来绘制好的匹配
  231. mask_matches = [[0, 0] for i in range(len(matches))]
  232. # 向掩膜中添加数据
  233. for i, (m, n) in enumerate(matches):
  234. if m.distance < 0.6 * n.distance: # 理论上0.7最好
  235. mask_matches[i] = [1, 0]
  236. img_matches = cv2.drawMatchesKnn(self.image, self.kp, source, kp, matches, None,
  237. matchColor=(0, 255, 0), singlePointColor=(255, 0, 0),
  238. matchesMask=mask_matches, flags=0)
  239. cv2.imshow(f'Sift Flann: {self.name}', img_matches)
  240. cv2.waitKey(0)
  241. cv2.destroyAllWindows()
  242. return result
  243. def match_mean_color(self, image, color: tuple, bias=10) -> bool:
  244. """
  245. :param image:
  246. :param color: rgb
  247. :param bias:
  248. :return:
  249. """
  250. image = self.corp(image)
  251. average_color = cv2.mean(image)
  252. # logger.info(f'{self.name} average_color: {average_color}')
  253. for i in range(3):
  254. if abs(average_color[i] - color[i]) > bias:
  255. return False
  256. return True
  257. if __name__ == "__main__":
  258. from dev_tools.assets_test import detect_image
  259. IMAGE_FILE = './log/test/QQ截图20240223151924.png'
  260. from tasks.Restart.assets import RestartAssets
  261. jade = RestartAssets.I_HARVEST_JADE
  262. jade.method = 'Sift Flann'
  263. sign = RestartAssets.I_HARVEST_SIGN
  264. sign.method = 'Sift Flann'
  265. print(jade.roi_front)
  266. detect_image(IMAGE_FILE, jade)
  267. detect_image(IMAGE_FILE, sign)
  268. print(jade.roi_front)