Skip to content

Commit

Permalink
refactor: remove useless code (#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xWelt authored Dec 29, 2024
1 parent e7959ac commit de51321
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 90 deletions.
45 changes: 1 addition & 44 deletions autowsgr/constants/image_templates.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from functools import partial

from airtest.core.cv import MATCHING_METHODS, ST, InvalidMatchingMethodError, TargetPos, Template
from airtest.core.cv import Template

from autowsgr.constants.data_roots import IMG_ROOT
from autowsgr.utils.io import create_namespace
Expand All @@ -17,49 +17,6 @@ def __add__(self, other) -> list:
return [self, *other] # 添加到列表末尾
return NotImplemented

def match_in(self, screen, this_methods=None):
match_result = self._cv_match(screen, this_methods)
if not match_result:
return None
return TargetPos().getXY(match_result, self.target_pos)

def _cv_match(self, screen, this_methods=None):
ori_image = self._imread()
image = self._resize_image(ori_image, screen, ST.RESIZE_METHOD)
ret = None
if this_methods is None:
this_methods = ST.CVSTRATEGY
for method in this_methods:
# get function definition and execute:
func = MATCHING_METHODS.get(method, None)
if func is None:
raise InvalidMatchingMethodError(
f"Undefined method in CVSTRATEGY: '{method}', try 'kaze'/'brisk'/'akaze'/'orb'/'surf'/'sift'/'brief' instead.",
)
if method in ['mstpl', 'gmstpl']:
ret = self._try_match(
func,
ori_image,
screen,
threshold=self.threshold,
rgb=self.rgb,
record_pos=self.record_pos,
resolution=self.resolution,
scale_max=self.scale_max,
scale_step=self.scale_step,
)
else:
ret = self._try_match(
func,
image,
screen,
threshold=self.threshold,
rgb=self.rgb,
)
if ret:
break
return ret


IMG = create_namespace(
IMG_ROOT,
Expand Down
5 changes: 5 additions & 0 deletions autowsgr/scripts/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging

from airtest.core.settings import Settings as ST # noqa

from autowsgr.game.build import BuildManager
from autowsgr.timer import Timer
from autowsgr.user_config import UserConfig
Expand All @@ -16,6 +18,9 @@ def start_script(settings_path=None) -> Timer:
Returns:
Timer: 该模拟器的记录器
"""
# airtest全局设置
ST.CVSTRATEGY = ['tpl']

# config
config_dict = yaml_to_dict(settings_path)
config = UserConfig.from_dict(config_dict)
Expand Down
56 changes: 16 additions & 40 deletions autowsgr/timer/controllers/android_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import threading as th
import time
from collections.abc import Iterable
from concurrent.futures import ProcessPoolExecutor

import cv2
from airtest.core.android import Android
Expand Down Expand Up @@ -31,6 +32,8 @@ def __init__(
config: UserConfig,
logger: Logger,
) -> None:
self._pool = ProcessPoolExecutor()

self.screen = None
self.dev = dev
self.show_android_input = config.show_android_input
Expand Down Expand Up @@ -246,74 +249,52 @@ def check_pixel(self, position, bgr_color, distance=30, screen_shot=False) -> bo
color.reverse()
return cal_dis(color, bgr_color) < distance**2

def locate_center_on_screen(
self,
query: MyTemplate,
confidence=0.85,
this_methods=None,
):
"""从屏幕中找出和模板图像匹配度最高的矩阵区域的中心坐标
参考 locate_image_center
Returns:
如果找到返回一个二元组表示绝对坐标
否则返回 None
"""
if this_methods is None:
this_methods = ['tpl']
return locate_image_center(self.screen, query, confidence, this_methods)

def get_image_position(
self,
image,
need_screen_shot=True,
confidence=0.85,
this_methods=None,
):
"""从屏幕中找出和多张模板图像匹配度超过阈值的矩阵区域的中心坐标,如果有多个,返回第一个
参考 locate_center_on_screen
Args:
need_screen_shot (int, optional): 是否重新截取屏幕. Defaults to 1.
Returns:
如果找到:返回一个二元组表示相对坐标 (相对 960x540 屏幕)
否则返回 None
"""
if this_methods is None:
this_methods = ['tpl']
images = image
if not isinstance(images, Iterable):
images = [images]
if need_screen_shot:
self.update_screen()
for image in images:
res = self.locate_center_on_screen(image, confidence, this_methods)
res = locate_image_center(self.screen, image, confidence)
if res is not None:
rel_pos = absolute_to_relative(res, self.resolution)
return relative_to_absolute(rel_pos, (960, 540))
# results = self._pool.map(partial(locate_image_center, self.screen, confidence=confidence), images)
# for res in results:
# if res is not None:
# rel_pos = absolute_to_relative(res, self.resolution)
# return relative_to_absolute(rel_pos, (960, 540))
return None

def image_exist(
self,
images,
need_screen_shot=True,
confidence=0.85,
this_methods=None,
):
"""判断图像是否存在于屏幕中
Returns:
bool:如果存在为 True 否则为 False
"""
if this_methods is None:
this_methods = ['tpl']
if not isinstance(images, list):
images = [images]
if need_screen_shot:
self.update_screen()
return any(
self.get_image_position(image, False, confidence, this_methods) is not None
for image in images
)
return self.get_image_position(images, False, confidence) is not None

def wait_image(
self,
Expand All @@ -322,7 +303,6 @@ def wait_image(
timeout=10,
gap=0.15,
after_get_delay=0,
this_methods=None,
):
"""等待一张图片出现在屏幕中,置信度超过一定阈值(支持多图片)
Expand All @@ -333,13 +313,11 @@ def wait_image(
否则返回 False
"""
if this_methods is None:
this_methods = ['tpl']
if timeout < 0:
raise ValueError("arg 'timeout' should at least be 0 but is ", str(timeout))
start_time = time.time()
while True:
x = self.get_image_position(image, True, confidence, this_methods)
x = self.get_image_position(image, True, confidence)
if x is not None:
time.sleep(after_get_delay)
return x
Expand Down Expand Up @@ -394,6 +372,11 @@ def wait_images(
if self.image_exist(image, False, confidence):
time.sleep(after_get_delay)
return res
# exists = self._pool.map(partial(self.image_exist, confidence=confidence), [image for _, image in images])
# for (res, _), exist in zip(images, exists):
# if exist:
# time.sleep(after_get_delay)
# return res
time.sleep(gap)
if time.time() - start_time > timeout:
return None
Expand Down Expand Up @@ -445,13 +428,6 @@ def click_image(self, image, must_click=False, timeout=0, delay=0.5):
self.click(*pos, delay=delay)
return pos

def click_images(self, images, must_click=False, timeout=0, delay=0.5):
"""点击一些图片中第一张出现的,如果有多个,点击第一个
Returns:
bool:如果找到图片返回匹配位置,未找到则返回None
"""
return self.click_image(images, must_click, timeout, delay)

def log_screen(
self,
need_screen_shot=False,
Expand Down
7 changes: 1 addition & 6 deletions autowsgr/utils/api_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,26 +245,21 @@ def locate_image_center(
image: np.ndarray,
query: MyTemplate,
confidence=0.85,
this_methods=None,
):
"""从原图像中尝试找出一个置信度相对于模板图像最高的矩阵区域的中心坐标
Args:
image (np.ndarray): 原图像
query (MyTemplate): 模板图像
confidence (float, optional): 置信度阈值. Defaults to 0.85.
this_methods (list, optional): 匹配方式. Defaults to ['tpl'].
Returns:
如果匹配结果中有超过阈值的,返回置信度最高的结果的中心绝对坐标:Tuple(int,int)
否则返回 None
"""
if this_methods is None:
this_methods = ['tpl']
query.threshold = confidence
match_pos = query.match_in(image, this_methods=this_methods)
return match_pos or None
return query.match_in(image)


def match_nearest_index(
Expand Down

0 comments on commit de51321

Please sign in to comment.