image.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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.atom.RuleImageMallResourceMixin import RuleImageMallResourceMixin
  9. from module.base.decorator import cached_property
  10. from module.logger import logger
  11. from module.base.utils import is_approx_rectangle
  12. class RuleImage(RuleImageMallResourceMixin):
  13. debug_mode: bool = False
  14. def __init__(self, roi_front: tuple, roi_back: tuple, method: str, threshold: float, file: str) -> None:
  15. """
  16. 初始化
  17. :param roi_front: 前置roi
  18. :param roi_back: 后置roi 用于匹配的区域
  19. :param method: 匹配方法 "Template matching"
  20. :param threshold: 阈值 0.8
  21. :param file: 相对路径, 带后缀
  22. """
  23. self._match_init = False # 这个是给后面的 等待图片稳定
  24. self._image = None # 这个是匹配的目标
  25. self._kp = None #
  26. self._des = None
  27. self.method = method
  28. self.roi_front: list = list(roi_front)
  29. self.roi_back = roi_back
  30. self.threshold = threshold
  31. self.file = file
  32. @cached_property
  33. def name(self) -> str:
  34. """
  35. :return:
  36. """
  37. return Path(self.file).stem.upper()
  38. def __str__(self):
  39. return self.name
  40. __repr__ = __str__
  41. def __eq__(self, other):
  42. return str(self) == str(other)
  43. def __hash__(self):
  44. return hash(self.name)
  45. def __bool__(self):
  46. return True
  47. def load_image(self) -> None:
  48. """
  49. 加载图片
  50. :return:
  51. """
  52. if self._image is not None:
  53. return
  54. img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
  55. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  56. self._image = img
  57. height, width, channels = self._image.shape
  58. if height != self.roi_front[3] or width != self.roi_front[2]:
  59. self.roi_front[2] = width
  60. self.roi_front[3] = height
  61. logger.debug(f"{self.name} roi_front size changed to {width}x{height}")
  62. def load_kp_des(self) -> None:
  63. if self._kp is not None and self._des is not None:
  64. return
  65. self._kp, self._des = self.sift.detectAndCompute(self.image, None)
  66. @property
  67. def image(self):
  68. """
  69. 获取图片
  70. :return:
  71. """
  72. if self._image is None:
  73. self.load_image()
  74. return self._image
  75. @cached_property
  76. def is_template_match(self) -> bool:
  77. """
  78. 是否是模板匹配
  79. :return:
  80. """
  81. return self.method == "Template matching"
  82. @cached_property
  83. def is_sift_flann(self) -> bool:
  84. return self.method == "Sift Flann"
  85. @cached_property
  86. def sift(self):
  87. return cv2.SIFT_create()
  88. @cached_property
  89. def kp(self):
  90. if self._kp is None:
  91. self.load_kp_des()
  92. return self._kp
  93. @cached_property
  94. def des(self):
  95. if self._des is None:
  96. self.load_kp_des()
  97. return self._des
  98. def corp(self, image: np.array, roi: list = None) -> np.array:
  99. """
  100. 截取图片
  101. :param image:
  102. :param roi
  103. :return:
  104. """
  105. if roi is None:
  106. x, y, w, h = self.roi_back
  107. else:
  108. x, y, w, h = roi
  109. x, y, w, h = int(x), int(y), int(w), int(h)
  110. return image[y:y + h, x:x + w]
  111. def match(self, image: np.array, threshold: float = None) -> bool:
  112. """
  113. :param threshold:
  114. :param image:
  115. :return:
  116. """
  117. if threshold is None:
  118. threshold = self.threshold
  119. if not self.is_template_match:
  120. return self.sift_match(image)
  121. # raise Exception(f"unknown method {self.method}")
  122. source = self.corp(image)
  123. mat = self.image
  124. if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
  125. logger.error(f"Template image is invalid: {mat.shape}")
  126. return False # 模板无效,匹配失败
  127. res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  128. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
  129. if self.debug_mode:
  130. logger.attr(self.name, f'matching score {max_val:.5f}')
  131. if max_val > threshold:
  132. self.roi_front[0] = max_loc[0] + self.roi_back[0]
  133. self.roi_front[1] = max_loc[1] + self.roi_back[1]
  134. return True
  135. else:
  136. return False
  137. def match_multi_scale(self, image: np.array, threshold: float = None,
  138. scales: list = None, scale_range: tuple = None) -> bool:
  139. """
  140. 多尺度模板匹配,自动尝试多个缩放比例以适应图片大小的变化
  141. :param image: 原始截图
  142. :param threshold: 匹配阈值
  143. :param scales: 缩放比例列表
  144. :param scale_range: 缩放范围 (start, end, step),例如 (0.8, 1.2, 0.1),step 默认为 0.1
  145. :return: 匹配是否成功
  146. """
  147. if threshold is None:
  148. threshold = self.threshold
  149. # 如果指定了 scale_range,自动生成 scales 列表
  150. if scale_range is not None:
  151. if len(scale_range) == 2:
  152. # 只有 start, end,默认 step=0.1
  153. start, end = scale_range
  154. scales = [round(x * 10) / 10 for x in np.arange(start, end + 0.1, 0.1)]
  155. else:
  156. start, end, step = scale_range
  157. scales = [round(x * 10) / 10 for x in np.arange(start, end + step, step)]
  158. if scales is None:
  159. scales = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
  160. source = self.corp(image)
  161. mat = self.image
  162. if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
  163. logger.error(f"Template image is invalid: {mat.shape}")
  164. return False # 模板无效,匹配失败
  165. best_score = 0
  166. best_loc = None
  167. best_scale = 1.0
  168. for scale in scales:
  169. try:
  170. # 按比例缩放模板
  171. scaled_w = int(mat.shape[1] * scale)
  172. scaled_h = int(mat.shape[0] * scale)
  173. # 跳过太大或太小的缩放
  174. if scaled_w < 10 or scaled_h < 10:
  175. continue
  176. if scaled_w > source.shape[1] * 1.5 or scaled_h > source.shape[0] * 1.5:
  177. continue
  178. scaled_mat = cv2.resize(mat, (scaled_w, scaled_h))
  179. res = cv2.matchTemplate(source, scaled_mat, cv2.TM_CCOEFF_NORMED)
  180. _, max_val, _, max_loc = cv2.minMaxLoc(res)
  181. if max_val > best_score:
  182. best_score = max_val
  183. best_loc = max_loc
  184. best_scale = scale
  185. except Exception as e:
  186. continue
  187. if self.debug_mode:
  188. logger.attr(self.name, f'best scale: {best_scale:.2f}, best score: {best_score:.5f}')
  189. if best_score > threshold and best_loc is not None:
  190. # 计算缩放后的模板尺寸
  191. scaled_w = int(mat.shape[1] * best_scale)
  192. scaled_h = int(mat.shape[0] * best_scale)
  193. # 设置 roi_front 为匹配位置 + 缩放后的尺寸
  194. self.roi_front[0] = best_loc[0] + self.roi_back[0]
  195. self.roi_front[1] = best_loc[1] + self.roi_back[1]
  196. self.roi_front[2] = scaled_w
  197. self.roi_front[3] = scaled_h
  198. return True
  199. else:
  200. return False
  201. def match_all(self, image: np.array, threshold: float = None, roi: list = None) -> list[tuple]:
  202. """
  203. 区别于match,这个是返回所有的匹配结果
  204. :param roi:
  205. :param image:
  206. :param threshold:
  207. :return:
  208. """
  209. if roi is not None:
  210. self.roi_back = roi
  211. if threshold is None:
  212. threshold = self.threshold
  213. if not self.is_template_match:
  214. raise Exception(f"unknown method {self.method}")
  215. source = self.corp(image)
  216. mat = self.image
  217. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  218. locations = np.where(results >= threshold)
  219. matches = []
  220. for pt in zip(*locations[::-1]): # (x, y) coordinates
  221. score = results[pt[1], pt[0]]
  222. # 得分, x, y, w, h
  223. x = self.roi_back[0] + pt[0]
  224. y = self.roi_back[1] + pt[1]
  225. matches.append((score, x, y, mat.shape[1], mat.shape[0]))
  226. return matches
  227. def match_all_any(self, image: np.array, threshold: float = None, roi: list = None, nms_threshold: float = 0.3) -> list[tuple]:
  228. """
  229. 区别于match,这个是返回所有的匹配结果,去除冗余匹配项(例如:多个框选区域重叠的情况)时使用。
  230. :param roi:
  231. :param image:
  232. :param threshold:
  233. :return:
  234. """
  235. if roi is not None:
  236. self.roi_back = roi
  237. if threshold is None:
  238. threshold = self.threshold
  239. if not self.is_template_match:
  240. raise Exception(f"unknown method {self.method}")
  241. source = self.corp(image)
  242. mat = self.image
  243. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  244. locations = np.where(results >= threshold)
  245. matches = []
  246. for pt in zip(*locations[::-1]): # (x, y) coordinates
  247. score = results[pt[1], pt[0]]
  248. # 得分, x, y, w, h
  249. x = self.roi_back[0] + pt[0]
  250. y = self.roi_back[1] + pt[1]
  251. matches.append((score, x, y, mat.shape[1], mat.shape[0]))
  252. if len(matches) > 0:
  253. scores = np.array([m[0] for m in matches])
  254. boxes = np.array([[m[1], m[2], m[3], m[4]] for m in matches])
  255. # 使用OpenCV的NMSBoxes
  256. indices = cv2.dnn.NMSBoxes(boxes.tolist(), scores.tolist(), score_threshold=threshold, nms_threshold=nms_threshold)
  257. filtered_matches = [matches[i] for i in indices]
  258. return filtered_matches
  259. return matches
  260. def coord(self) -> tuple:
  261. """
  262. 获取roi_front的随机的点击的坐标
  263. :return:
  264. """
  265. x, y, w, h = self.roi_front
  266. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  267. def coord_more(self) -> tuple:
  268. """
  269. 获取roi_back的随机的点击的坐标
  270. :return:
  271. """
  272. x, y, w, h = self.roi_back
  273. return x + np.random.randint(0, w), y + np.random.randint(0, h)
  274. def front_center(self) -> tuple:
  275. """
  276. 获取roi_front的中心坐标
  277. :return:
  278. """
  279. x, y, w, h = self.roi_front
  280. return int(x + w//2), int(y + h//2)
  281. def test_match(self, image: np.array):
  282. self.debug_mode = True
  283. if self.is_template_match:
  284. return self.match(image)
  285. if self.is_sift_flann:
  286. return self.sift_match(image, show=True)
  287. def sift_match(self, image: np.array, show=False) -> bool:
  288. """
  289. 特征匹配,同样会修改 roi_front
  290. :param image: 是游戏的截图,就是转通道后的截图
  291. :param show: 测试用的
  292. :return:
  293. """
  294. source = self.corp(image)
  295. kp, des = self.sift.detectAndCompute(source, None)
  296. # 参数1:index_params
  297. # 对于SIFT和SURF,可以传入参数index_params=dict(algorithm=FLANN_INDEX_KDTREE, trees=5)。
  298. # 对于ORB,可以传入参数index_params=dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12)。
  299. index_params = dict(algorithm=1, trees=5)
  300. # 参数2:search_params 指定递归遍历的次数,值越高结果越准确,但是消耗的时间也越多。
  301. search_params = dict(checks=50)
  302. # 根据设置的参数创建特征匹配器 指定匹配的算法和kd树的层数,指定返回的个数
  303. flann = cv2.FlannBasedMatcher(index_params, search_params)
  304. # 利用创建好的特征匹配器利用k近邻算法来用模板的特征描述符去匹配图像的特征描述符,k指的是返回前k个最匹配的特征区域
  305. # 返回的是最匹配的两个特征点的信息,返回的类型是一个列表,列表元素的类型是Dmatch数据类型,具体是什么我也不知道
  306. # 第一个参数是小图的des, 第二个参数是大图的des
  307. matches = flann.knnMatch(self.des, des, k=2)
  308. good = []
  309. result = True
  310. for i, (m, n) in enumerate(matches):
  311. # 设定阈值, 距离小于对方的距离的0.7倍我们认为是好的匹配点.
  312. if m.distance < 0.6 * n.distance:
  313. good.append(m)
  314. if len(good) >= 10:
  315. src_pts = float32([self.kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  316. dst_pts = float32([kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  317. # 计算透视变换矩阵m, 要求点的数量>=4
  318. m, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
  319. # 创建一个包含模板图像四个角坐标的数组
  320. w, h = self.roi_front[2], self.roi_front[3]
  321. pts = float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
  322. if m is None:
  323. result = False
  324. else:
  325. dst = int32(cv2.perspectiveTransform(pts, m))
  326. self.roi_front[0] = dst[0, 0, 0] + self.roi_back[0]
  327. self.roi_front[1] = dst[0, 0, 1] + self.roi_back[1]
  328. if show:
  329. cv2.polylines(source, [dst], isClosed=True, color=(0, 0, 255), thickness=2)
  330. if not is_approx_rectangle(np.array([pos[0] for pos in dst])):
  331. result = False
  332. else:
  333. result = False
  334. # https://blog.csdn.net/cungudafa/article/details/105399278
  335. # https://blog.csdn.net/qq_45832961/article/details/122776322
  336. if show:
  337. # 准备一个空的掩膜来绘制好的匹配
  338. mask_matches = [[0, 0] for i in range(len(matches))]
  339. # 向掩膜中添加数据
  340. for i, (m, n) in enumerate(matches):
  341. if m.distance < 0.6 * n.distance: # 理论上0.7最好
  342. mask_matches[i] = [1, 0]
  343. img_matches = cv2.drawMatchesKnn(self.image, self.kp, source, kp, matches, None,
  344. matchColor=(0, 255, 0), singlePointColor=(255, 0, 0),
  345. matchesMask=mask_matches, flags=0)
  346. cv2.imshow(f'Sift Flann: {self.name}', img_matches)
  347. cv2.waitKey(0)
  348. cv2.destroyAllWindows()
  349. return result
  350. def match_mean_color(self, image, color: tuple, bias=10) -> bool:
  351. """
  352. :param image:
  353. :param color: rgb
  354. :param bias:
  355. :return:
  356. """
  357. image = self.corp(image)
  358. average_color = cv2.mean(image)
  359. # logger.info(f'{self.name} average_color: {average_color}')
  360. for i in range(3):
  361. if abs(average_color[i] - color[i]) > bias:
  362. return False
  363. return True
  364. if __name__ == "__main__":
  365. from dev_tools.assets_test import detect_image
  366. IMAGE_FILE = './log/test/QQ截图20240223151924.png'
  367. from tasks.Restart.assets import RestartAssets
  368. jade = RestartAssets.I_HARVEST_JADE
  369. jade.method = 'Sift Flann'
  370. sign = RestartAssets.I_HARVEST_SIGN
  371. sign.method = 'Sift Flann'
  372. print(jade.roi_front)
  373. detect_image(IMAGE_FILE, jade)
  374. detect_image(IMAGE_FILE, sign)
  375. print(jade.roi_front)