image.py 25 KB

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