image.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. from module.base.utils.utils import random_normal_distribution_int
  13. class RuleImage(RuleImageMallResourceMixin):
  14. debug_mode: bool = False
  15. def __init__(self, roi_front: tuple, roi_back: tuple, method: str, threshold: float, file: str) -> None:
  16. """
  17. 初始化
  18. :param roi_front: 前置roi
  19. :param roi_back: 后置roi 用于匹配的区域
  20. :param method: 匹配方法 "Template matching" / "Masked template matching" / "Multi-scale template matching" / "Sift Flann"
  21. :param threshold: 阈值 0.8
  22. :param file: 相对路径, 带后缀
  23. """
  24. self._match_init = False # 这个是给后面的 等待图片稳定
  25. self._image = None # 这个是匹配的目标
  26. self._kp = None #
  27. self._des = None
  28. self._mask_loaded = False # 掩码懒加载标记: False=未加载, 加载后看 _mask
  29. self._mask = None # 掩码图, None 表示无掩码(回退普通匹配)
  30. self.last_score = -1.0 # 最近一次匹配的真实分数, -1 表示本次未产生分数
  31. self.last_scale = None # 最近一次多尺度匹配命中的缩放倍数, 仅 Multi-scale 方法写入
  32. self.method = method
  33. self.roi_front: list = list(roi_front)
  34. self.roi_back = roi_back
  35. self.threshold = threshold
  36. self.file = file
  37. @cached_property
  38. def name(self) -> str:
  39. """
  40. :return:
  41. """
  42. return Path(self.file).stem.upper()
  43. def __str__(self):
  44. return self.name
  45. __repr__ = __str__
  46. def __eq__(self, other):
  47. return str(self) == str(other)
  48. def __hash__(self):
  49. return hash(self.name)
  50. def __bool__(self):
  51. return True
  52. def load_image(self) -> None:
  53. """
  54. 加载图片
  55. :return:
  56. """
  57. if self._image is not None:
  58. return
  59. img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
  60. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  61. self._image = img
  62. height, width, channels = self._image.shape
  63. if height != self.roi_front[3] or width != self.roi_front[2]:
  64. self.roi_front[2] = width
  65. self.roi_front[3] = height
  66. logger.debug(f"{self.name} roi_front size changed to {width}x{height}")
  67. def load_kp_des(self) -> None:
  68. if self._kp is not None and self._des is not None:
  69. return
  70. self._kp, self._des = self.sift.detectAndCompute(self.image, None)
  71. @property
  72. def image(self):
  73. """
  74. 获取图片
  75. :return:
  76. """
  77. if self._image is None:
  78. self.load_image()
  79. return self._image
  80. @cached_property
  81. def is_template_match(self) -> bool:
  82. """
  83. 是否是模板匹配
  84. :return:
  85. """
  86. return self.method == "Template matching"
  87. @cached_property
  88. def is_masked_template_match(self) -> bool:
  89. """
  90. 是否是掩码模板匹配,掩码取自同目录下 `xxx_mask.png`
  91. :return:
  92. """
  93. return self.method == "Masked template matching"
  94. @cached_property
  95. def is_multi_scale_template_match(self) -> bool:
  96. return self.method == "Multi-scale template matching"
  97. @cached_property
  98. def is_sift_flann(self) -> bool:
  99. return self.method == "Sift Flann"
  100. @cached_property
  101. def sift(self):
  102. return cv2.SIFT_create()
  103. @cached_property
  104. def kp(self):
  105. if self._kp is None:
  106. self.load_kp_des()
  107. return self._kp
  108. @cached_property
  109. def des(self):
  110. if self._des is None:
  111. self.load_kp_des()
  112. return self._des
  113. @property
  114. def mask(self):
  115. """
  116. 掩码图,取模板同目录下 `xxx_mask.png`(`xxx.png` -> `xxx_mask.png`)。
  117. 语义为「非零参与匹配,零忽略」。文件缺失、读取失败或尺寸与模板不一致时
  118. 返回 None,由调用方回退到普通匹配,避免一张画错尺寸的掩码直接让规则报错。
  119. :return:
  120. """
  121. if not self._mask_loaded:
  122. self._mask_loaded = True
  123. path = Path(self.file)
  124. mask_path = path.with_name(f"{path.stem}_mask{path.suffix}")
  125. try:
  126. mask = cv2.imdecode(fromfile(str(mask_path), dtype=uint8), cv2.IMREAD_GRAYSCALE)
  127. except OSError:
  128. mask = None
  129. if mask is None:
  130. logger.debug(f"{self.name} template mask unavailable, fallback to plain matching: {mask_path}")
  131. elif mask.shape[:2] != self.image.shape[:2]:
  132. logger.error(
  133. f"{self.name} template mask size mismatch "
  134. f"{mask.shape[:2]} != {self.image.shape[:2]}, fallback to plain matching"
  135. )
  136. else:
  137. self._mask = mask
  138. return self._mask
  139. @staticmethod
  140. def _template_is_degenerate(template: np.ndarray, mask: np.ndarray | None = None) -> bool:
  141. """
  142. 判断模板在参与匹配的区域内是否逐通道恒为常量。
  143. CCOEFF_NORMED 归一化时分母来自各通道的方差,参与区域内所有通道都完全没有起伏时,
  144. 分母才是 0,OpenCV 会走特判:无掩码时整张结果矩阵被填成 1.0(恒假阳性,且落点固定
  145. 在 roi_back 左上角),带掩码时整张变成 0/0 的 nan。两种都让这条规则失去意义,
  146. 这里提前拦掉,而不是把异常数值当成命中。
  147. """
  148. if template is None or template.size == 0:
  149. return True
  150. region = template if mask is None else template[mask > 0]
  151. if region.size == 0:
  152. return True
  153. # 掩码取值后是 `(N, C)`、整体模板是 `(H, W, C)`、灰度图是 `(H, W)` 或 `(N,)`,
  154. # 通道数只认模板本身,再统一摊平成 `(N, C)` 逐通道判断。
  155. channels = 1 if template.ndim == 2 else template.shape[-1]
  156. samples = region.reshape(-1, channels)
  157. return all(float(samples[:, channel].std()) == 0.0 for channel in range(channels))
  158. @staticmethod
  159. def _sanitize_match_result(result: np.ndarray) -> np.ndarray:
  160. """
  161. 压掉匹配结果矩阵里的非有限值。
  162. 源图窗口整块同色时 CCOEFF_NORMED 会算出 nan/inf:nan 会让
  163. `max_val > threshold` 恒为假而静默漏检,inf 则会越过阈值并把命中位置指到随机
  164. 坐标(假阳性,点错位置)。这里统一替换为 -1.0,等价于「该位置判不匹配」。
  165. """
  166. if np.isfinite(result).all():
  167. return result
  168. logger.error("match result contains nan/inf (solid-color region), treated as not matched")
  169. return np.nan_to_num(result, nan=-1.0, posinf=-1.0, neginf=-1.0)
  170. def corp(self, image: np.array, roi: list = None) -> np.array:
  171. """
  172. 截取图片
  173. :param image:
  174. :param roi
  175. :return:
  176. """
  177. if roi is None:
  178. x, y, w, h = self.roi_back
  179. else:
  180. x, y, w, h = roi
  181. x, y, w, h = int(x), int(y), int(w), int(h)
  182. return image[y:y + h, x:x + w]
  183. def match(self, image: np.array, threshold: float = None) -> bool:
  184. """
  185. :param threshold:
  186. :param image:
  187. :return:
  188. """
  189. if threshold is None:
  190. threshold = self.threshold
  191. if self.is_multi_scale_template_match:
  192. return self.match_multi_scale(image, threshold, scale_range=(0.6, 1.2))
  193. if not (self.is_template_match or self.is_masked_template_match):
  194. return self.sift_match(image)
  195. # raise Exception(f"unknown method {self.method}")
  196. source = self.corp(image)
  197. mat = self.image
  198. if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
  199. logger.error(f"Template image is invalid: {mat.shape}")
  200. return False # 模板无效, 匹配失败
  201. if mat.shape[0] > source.shape[0] or mat.shape[1] > source.shape[1]:
  202. # 模板大于源图, 视为无效匹配(避免 matchTemplate 的异常行为)
  203. return False
  204. mask = self.mask if self.is_masked_template_match else None
  205. if self._template_is_degenerate(mat, mask):
  206. logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
  207. return False
  208. if mask is None:
  209. res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  210. else:
  211. res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
  212. res = self._sanitize_match_result(res)
  213. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
  214. self.last_score = float(max_val)
  215. if self.debug_mode:
  216. logger.attr(self.name, f'matching score {max_val:.5f}')
  217. if max_val > threshold:
  218. self.roi_front[0] = max_loc[0] + self.roi_back[0]
  219. self.roi_front[1] = max_loc[1] + self.roi_back[1]
  220. return True
  221. else:
  222. return False
  223. def match_multi_scale(self, image: np.array, threshold: float = None,
  224. scales: list = None, scale_range: tuple = None) -> bool:
  225. """
  226. 多尺度模板匹配,自动尝试多个缩放比例以适应图片大小的变化
  227. :param image: 原始截图
  228. :param threshold: 匹配阈值
  229. :param scales: 缩放比例列表
  230. :param scale_range: 缩放范围 (start, end, step),例如 (0.8, 1.2, 0.1),step 默认为 0.1
  231. :return: 匹配是否成功
  232. """
  233. if threshold is None:
  234. threshold = self.threshold
  235. # 如果指定了 scale_range,自动生成 scales 列表
  236. if scale_range is not None:
  237. start, end = scale_range[:2]
  238. step = scale_range[2] if len(scale_range) > 2 else 0.1
  239. scales = sorted(set(round(x, 1) for x in np.arange(start, end + step, step)))
  240. if scales is None:
  241. scales = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
  242. else:
  243. scales = sorted(set(round(x, 1) for x in scales))
  244. source = self.corp(image)
  245. mat = self.image
  246. if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
  247. logger.error(f"Template image is invalid: {mat.shape}")
  248. return False
  249. if self._template_is_degenerate(mat):
  250. logger.error(f"{self.name} template is flat (no variance), treated as not matched")
  251. return False
  252. # 预计算模板尺寸
  253. mat_h, mat_w = mat.shape[:2]
  254. source_h, source_w = source.shape[:2]
  255. best_score = 0
  256. best_loc = None
  257. best_scale = 1.0
  258. best_shape = None # 最佳得分对应的是哪一档缩放尺寸, 回写 roi_front 只能用它
  259. self.last_scale = None
  260. for scale in scales:
  261. scaled_w = int(mat_w * scale)
  262. scaled_h = int(mat_h * scale)
  263. # 跳过无效缩放
  264. if scaled_w < 10 or scaled_h < 10:
  265. continue
  266. # 缩放后仍大于源图则跳过该尺度(避免 matchTemplate 契约问题)
  267. if scaled_w > source_w or scaled_h > source_h:
  268. continue
  269. try:
  270. scaled_mat = cv2.resize(mat, (scaled_w, scaled_h))
  271. res = cv2.matchTemplate(source, scaled_mat, cv2.TM_CCOEFF_NORMED)
  272. res = self._sanitize_match_result(res)
  273. _, max_val, _, max_loc = cv2.minMaxLoc(res)
  274. if max_val > best_score:
  275. best_score = max_val
  276. best_loc = max_loc
  277. best_scale = scale
  278. best_shape = (scaled_w, scaled_h)
  279. except Exception as e:
  280. continue
  281. if self.debug_mode:
  282. logger.attr(self.name, f'best scale: {best_scale:.2f}, best score: {best_score:.5f}')
  283. self.last_score = float(best_score)
  284. if best_loc is not None:
  285. self.last_scale = float(best_scale)
  286. if best_score > threshold and best_loc is not None and best_shape is not None:
  287. self.roi_front[0] = best_loc[0] + self.roi_back[0]
  288. self.roi_front[1] = best_loc[1] + self.roi_back[1]
  289. self.roi_front[2] = best_shape[0]
  290. self.roi_front[3] = best_shape[1]
  291. return True
  292. else:
  293. return False
  294. def match_all(self, image: np.array, threshold: float = None, roi: list = None) -> list[tuple]:
  295. """
  296. 区别于match,这个是返回所有的匹配结果
  297. :param roi:
  298. :param image:
  299. :param threshold:
  300. :return:
  301. """
  302. if roi is not None:
  303. self.roi_back = roi
  304. if threshold is None:
  305. threshold = self.threshold
  306. if not (self.is_template_match or self.is_masked_template_match):
  307. raise Exception(f"unknown method {self.method}")
  308. source = self.corp(image)
  309. mat = self.image
  310. mask = self.mask if self.is_masked_template_match else None
  311. if self._template_is_degenerate(mat, mask):
  312. logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
  313. return []
  314. if mask is None:
  315. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  316. else:
  317. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
  318. results = self._sanitize_match_result(results)
  319. if results.size:
  320. self.last_score = float(results.max())
  321. locations = np.where(results >= threshold)
  322. matches = []
  323. for pt in zip(*locations[::-1]): # (x, y) coordinates
  324. score = results[pt[1], pt[0]]
  325. # 得分, x, y, w, h
  326. x = self.roi_back[0] + pt[0]
  327. y = self.roi_back[1] + pt[1]
  328. matches.append((score, x, y, mat.shape[1], mat.shape[0]))
  329. return matches
  330. def match_all_any(self, image: np.array, threshold: float = None, roi: list = None, nms_threshold: float = 0.3) -> list[tuple]:
  331. """
  332. 区别于match,这个是返回所有的匹配结果,去除冗余匹配项(例如:多个框选区域重叠的情况)时使用。
  333. :param roi:
  334. :param image:
  335. :param threshold:
  336. :return:
  337. """
  338. if roi is not None:
  339. self.roi_back = roi
  340. if threshold is None:
  341. threshold = self.threshold
  342. if not (self.is_template_match or self.is_masked_template_match):
  343. raise Exception(f"unknown method {self.method}")
  344. source = self.corp(image)
  345. mat = self.image
  346. mask = self.mask if self.is_masked_template_match else None
  347. if self._template_is_degenerate(mat, mask):
  348. logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
  349. return []
  350. if mask is None:
  351. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
  352. else:
  353. results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
  354. results = self._sanitize_match_result(results)
  355. if results.size:
  356. self.last_score = float(results.max())
  357. locations = np.where(results >= threshold)
  358. matches = []
  359. for pt in zip(*locations[::-1]): # (x, y) coordinates
  360. score = results[pt[1], pt[0]]
  361. # 得分, x, y, w, h
  362. x = self.roi_back[0] + pt[0]
  363. y = self.roi_back[1] + pt[1]
  364. matches.append((score, x, y, mat.shape[1], mat.shape[0]))
  365. if len(matches) > 0:
  366. scores = np.array([m[0] for m in matches])
  367. boxes = np.array([[m[1], m[2], m[3], m[4]] for m in matches])
  368. # 使用OpenCV的NMSBoxes
  369. indices = cv2.dnn.NMSBoxes(boxes.tolist(), scores.tolist(), score_threshold=threshold, nms_threshold=nms_threshold)
  370. filtered_matches = [matches[i] for i in indices]
  371. return filtered_matches
  372. return matches
  373. def coord(self) -> tuple:
  374. """
  375. 获取roi_front的随机的点击的坐标
  376. :return:
  377. """
  378. x, y, w, h = self.roi_front
  379. return x + random_normal_distribution_int(0, w), y + random_normal_distribution_int(0, h)
  380. def coord_more(self) -> tuple:
  381. """
  382. 获取roi_back的随机的点击的坐标
  383. :return:
  384. """
  385. x, y, w, h = self.roi_back
  386. return x + random_normal_distribution_int(0, w), y + random_normal_distribution_int(0, h)
  387. def front_center(self) -> tuple:
  388. """
  389. 获取roi_front的中心坐标
  390. :return:
  391. """
  392. x, y, w, h = self.roi_front
  393. return int(x + w//2), int(y + h//2)
  394. def test_match(self, image: np.array):
  395. self.debug_mode = True
  396. if self.is_template_match or self.is_masked_template_match or self.is_multi_scale_template_match:
  397. return self.match(image)
  398. if self.is_sift_flann:
  399. return self.sift_match(image, show=True)
  400. def sift_match(self, image: np.array, show=False) -> bool:
  401. """
  402. 特征匹配,同样会修改 roi_front
  403. :param image: 是游戏的截图,就是转通道后的截图
  404. :param show: 测试用的
  405. :return:
  406. """
  407. source = self.corp(image)
  408. kp, des = self.sift.detectAndCompute(source, None)
  409. # 参数1:index_params
  410. # 对于SIFT和SURF,可以传入参数index_params=dict(algorithm=FLANN_INDEX_KDTREE, trees=5)。
  411. # 对于ORB,可以传入参数index_params=dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12)。
  412. index_params = dict(algorithm=1, trees=5)
  413. # 参数2:search_params 指定递归遍历的次数,值越高结果越准确,但是消耗的时间也越多。
  414. search_params = dict(checks=50)
  415. # 根据设置的参数创建特征匹配器 指定匹配的算法和kd树的层数,指定返回的个数
  416. flann = cv2.FlannBasedMatcher(index_params, search_params)
  417. # 利用创建好的特征匹配器利用k近邻算法来用模板的特征描述符去匹配图像的特征描述符,k指的是返回前k个最匹配的特征区域
  418. # 返回的是最匹配的两个特征点的信息,返回的类型是一个列表,列表元素的类型是Dmatch数据类型,具体是什么我也不知道
  419. # 第一个参数是小图的des, 第二个参数是大图的des
  420. matches = flann.knnMatch(self.des, des, k=2)
  421. good = []
  422. result = True
  423. for i, (m, n) in enumerate(matches):
  424. # 设定阈值, 距离小于对方的距离的0.7倍我们认为是好的匹配点.
  425. if m.distance < 0.6 * n.distance:
  426. good.append(m)
  427. if len(good) >= 10:
  428. src_pts = float32([self.kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  429. dst_pts = float32([kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  430. # 计算透视变换矩阵m, 要求点的数量>=4
  431. m, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
  432. # 创建一个包含模板图像四个角坐标的数组
  433. w, h = self.roi_front[2], self.roi_front[3]
  434. pts = float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
  435. if m is None:
  436. result = False
  437. else:
  438. dst = int32(cv2.perspectiveTransform(pts, m))
  439. self.roi_front[0] = dst[0, 0, 0] + self.roi_back[0]
  440. self.roi_front[1] = dst[0, 0, 1] + self.roi_back[1]
  441. if show:
  442. cv2.polylines(source, [dst], isClosed=True, color=(0, 0, 255), thickness=2)
  443. if not is_approx_rectangle(np.array([pos[0] for pos in dst])):
  444. result = False
  445. else:
  446. result = False
  447. # https://blog.csdn.net/cungudafa/article/details/105399278
  448. # https://blog.csdn.net/qq_45832961/article/details/122776322
  449. if show:
  450. # 准备一个空的掩膜来绘制好的匹配
  451. mask_matches = [[0, 0] for i in range(len(matches))]
  452. # 向掩膜中添加数据
  453. for i, (m, n) in enumerate(matches):
  454. if m.distance < 0.6 * n.distance: # 理论上0.7最好
  455. mask_matches[i] = [1, 0]
  456. img_matches = cv2.drawMatchesKnn(self.image, self.kp, source, kp, matches, None,
  457. matchColor=(0, 255, 0), singlePointColor=(255, 0, 0),
  458. matchesMask=mask_matches, flags=0)
  459. cv2.imshow(f'Sift Flann: {self.name}', img_matches)
  460. cv2.waitKey(0)
  461. cv2.destroyAllWindows()
  462. return result
  463. def match_mean_color(self, image, color: tuple, bias=10) -> bool:
  464. """
  465. :param image:
  466. :param color: rgb
  467. :param bias:
  468. :return:
  469. """
  470. image = self.corp(image)
  471. average_color = cv2.mean(image)
  472. if self.debug_mode:
  473. logger.info(f'{self.name} average_color: {average_color}')
  474. for i in range(3):
  475. if abs(average_color[i] - color[i]) > bias:
  476. return False
  477. return True
  478. def match_brightness(
  479. self, image: np.array,
  480. threshold: float = 0.9,
  481. roi: list = None,
  482. gray: bool = False) -> bool:
  483. source = self.corp(image, roi) if roi is not None else self.corp(image)
  484. template = self.image
  485. if len(source.shape) != 3:
  486. raise Exception(f'{self.name} source image must be 3-channel RGB, got shape={source.shape}')
  487. source_gray = cv2.cvtColor(source, cv2.COLOR_RGB2GRAY)
  488. source_hsv = cv2.cvtColor(source, cv2.COLOR_RGB2HSV)
  489. if len(template.shape) != 3:
  490. raise Exception(f'{self.name} template image must be 3-channel RGB, got shape={template.shape}')
  491. template_gray = cv2.cvtColor(template, cv2.COLOR_RGB2GRAY)
  492. template_hsv = cv2.cvtColor(template, cv2.COLOR_RGB2HSV)
  493. source_value = float(source_gray.mean()) if gray else float(source_hsv[:, :, 2].mean())
  494. template_value = float(template_gray.mean()) if gray else float(template_hsv[:, :, 2].mean())
  495. score = 1.0 - abs(source_value - template_value) / 255.0
  496. score = max(0.0, min(1.0, score))
  497. if self.debug_mode:
  498. logger.attr(self.name, f'brightness similarity {score:.5f}')
  499. logger.info(f'Template value: {template_value}, Source value: {source_value}')
  500. return score >= threshold
  501. def match_saturation(self, image: np.array, threshold: float = 0.9, roi: list = None) -> bool:
  502. source = self.corp(image, roi) if roi is not None else self.corp(image)
  503. template = self.image
  504. if len(source.shape) != 3:
  505. raise Exception(f'{self.name} source image must be 3-channel RGB, got shape={source.shape}')
  506. source_hsv = cv2.cvtColor(source, cv2.COLOR_RGB2HSV)
  507. if len(template.shape) != 3:
  508. raise Exception(f'{self.name} template image must be 3-channel RGB, got shape={template.shape}')
  509. template_hsv = cv2.cvtColor(template, cv2.COLOR_RGB2HSV)
  510. source_value = float(source_hsv[:, :, 1].mean())
  511. template_value = float(template_hsv[:, :, 1].mean())
  512. score = 1.0 - abs(source_value - template_value) / 255.0
  513. score = max(0.0, min(1.0, score))
  514. if self.debug_mode:
  515. logger.attr(self.name, f'saturation similarity {score:.5f}')
  516. logger.info(f'Template value: {template_value}, Source value: {source_value}')
  517. return score >= threshold
  518. if __name__ == "__main__":
  519. from dev_tools.assets_test import detect_image
  520. IMAGE_FILE = './log/test/QQ截图20240223151924.png'
  521. from tasks.Restart.assets import RestartAssets
  522. jade = RestartAssets.I_HARVEST_JADE
  523. jade.method = 'Sift Flann'
  524. sign = RestartAssets.I_HARVEST_SIGN
  525. sign.method = 'Sift Flann'
  526. print(jade.roi_front)
  527. detect_image(IMAGE_FILE, jade)
  528. detect_image(IMAGE_FILE, sign)
  529. print(jade.roi_front)