feat: Enhance yanghao detection with polygon support and template matching
- Updated config.json to include new parameters for yanghao template paths and match thresholds. - Adjusted default icon match threshold in config to 0.70 for better detection. - Implemented polygon detection logic in yanghao_idle function to allow for flexible ROI configurations. - Added support for per-action ROI scaling and sizes in the configuration. - Introduced new methods in fudai_analyse for capturing ROI screenshots and matching templates. - Created a test script to validate polygon detection against provided templates. - Improved error handling and logging for better debugging during detection processes.
This commit is contained in:
1 parent
3678ff7e31
commit
a61ba62864
8 files changed
+848
-26
No files matched your search
+274
-1
@@ -226,7 +226,12 @@ class fudai_analyse:
|
||||
self.yanghao_fav_prob: float = 0.05
|
||||
self.yanghao_comment_prob: float = 0.0
|
||||
self.yanghao_icon_roi_size: int = 180
|
||||
self.yanghao_icon_match_threshold: float = 0.72
|
||||
# 调整默认阈值为 0.70(更宽松,减少漏检)
|
||||
self.yanghao_icon_match_threshold: float = 0.70
|
||||
self.yanghao_like_roi_scale: float = 1.5
|
||||
self.yanghao_fav_roi_scale: float = 1.5
|
||||
self.yanghao_like_icon_match_threshold: float | None = None
|
||||
self.yanghao_fav_icon_match_threshold: float | None = None
|
||||
# icon 坐标(基于 1080x2400)
|
||||
self.yanghao_like_icon_x: int = 0
|
||||
self.yanghao_like_icon_y: int = 0
|
||||
@@ -316,6 +321,42 @@ class fudai_analyse:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||||
douyin_helpers.HelperFunctions.click(self, x, y)
|
||||
|
||||
def swipe(self, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300) -> None:
|
||||
"""兼容原版 fudai_analyse.swipe:转发到底层 operation.swipe。
|
||||
|
||||
参数使用像素坐标,duration_ms 为滑动持续时间(毫秒)。
|
||||
"""
|
||||
try:
|
||||
# 首选底层 operation 的 swipe 实现
|
||||
try:
|
||||
self.operation.swipe(self.device_id, start_x, start_y, end_x, end_y, duration_ms)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 回退:尝试使用 douyin.handlers.douyin_swipe_ops 的 adb 命令直接发送
|
||||
try:
|
||||
from douyin.handlers import douyin_swipe_ops
|
||||
|
||||
ok = douyin_swipe_ops._adb_swipe_direct(
|
||||
getattr(self, "device_id", ""), start_x, start_y, end_x, end_y, duration_ms, self.operation
|
||||
)
|
||||
if ok:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 最后兜底:记录滑动失败
|
||||
try:
|
||||
self._log_kv("滑动", "swipe 失败 - 无可用实现", start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y, duration_ms=duration_ms)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
try:
|
||||
self._log_kv("滑动", "swipe 异常", start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y, duration_ms=duration_ms)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def load_config(self) -> None:
|
||||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||||
douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined]
|
||||
@@ -632,6 +673,238 @@ class fudai_analyse:
|
||||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
|
||||
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label)
|
||||
|
||||
def _capture_roi_screenshot(self, label: str, sx: int, sy: int, size: int) -> str:
|
||||
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。
|
||||
|
||||
返回 ROI 图片路径(绝对路径),失败返回空字符串。
|
||||
"""
|
||||
try:
|
||||
import path_config
|
||||
from PIL import Image
|
||||
|
||||
# 确保有最新全图
|
||||
try:
|
||||
self.operation.get_screenshot(self.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(pic_path):
|
||||
return ""
|
||||
|
||||
# 计算裁剪框(保证正方形,size 基于像素)
|
||||
half = int(size // 2)
|
||||
left = int(max(0, sx - half))
|
||||
top = int(max(0, sy - half))
|
||||
right = int(sx + half)
|
||||
bottom = int(sy + half)
|
||||
|
||||
# 以原子方式读取文件内容再由 PIL 解析,避免因文件替换/锁定导致的半写入问题
|
||||
import io
|
||||
from PIL import UnidentifiedImageError
|
||||
|
||||
data = None
|
||||
# 增强读取:多次尝试并在每次读到字节后用 PIL 验证,避免半写入/损坏 PNG 导致解析异常
|
||||
for attempt in range(6):
|
||||
try:
|
||||
try:
|
||||
# 主动请求最新截图以尽量获得完整文件
|
||||
self.operation.get_screenshot(self.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not os.path.exists(pic_path):
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
sz = os.path.getsize(pic_path)
|
||||
if sz < 1024:
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
with open(pic_path, "rb") as f:
|
||||
data = f.read()
|
||||
if not data or not data.startswith(b"\x89PNG"):
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
# quick tail check
|
||||
if b"IEND" not in data[-512:]:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
# 尝试由 PIL 快速验证(不加载像素,仅检查文件完整性)
|
||||
try:
|
||||
img_test = Image.open(io.BytesIO(data))
|
||||
img_test.verify()
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
continue
|
||||
|
||||
# 通过基本校验,退出重试循环
|
||||
break
|
||||
except Exception:
|
||||
data = None
|
||||
time.sleep(0.08)
|
||||
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
except UnidentifiedImageError:
|
||||
return ""
|
||||
except Exception:
|
||||
# 如果首次解析仍然失败,尝试再获取一次截图并重试一次
|
||||
try:
|
||||
try:
|
||||
self.operation.get_screenshot(self.device_id, use_service=False)
|
||||
except Exception:
|
||||
pass
|
||||
with open(pic_path, "rb") as f:
|
||||
data2 = f.read()
|
||||
if data2 and data2.startswith(b"\x89PNG") and b"IEND" in data2[-512:]:
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data2))
|
||||
img.load()
|
||||
except Exception:
|
||||
return ""
|
||||
else:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
w, h = img.size
|
||||
# 修正边界
|
||||
left = max(0, min(left, w - 1))
|
||||
top = max(0, min(top, h - 1))
|
||||
right = max(1, min(right, w))
|
||||
bottom = max(1, min(bottom, h))
|
||||
|
||||
roi = img.crop((left, top, right, bottom))
|
||||
# 保存到 pic 目录,使用 label 区分
|
||||
out_dir = path_config.get_pic_dir()
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
fname = f"roi_{label}_{getattr(self, '_run_id', 'run')}_{int(time.time())}.png"
|
||||
out_path = os.path.join(out_dir, fname)
|
||||
roi.save(out_path)
|
||||
return out_path
|
||||
except Exception:
|
||||
try:
|
||||
self._log_kv("截图", "_capture_roi_screenshot 失败", label=label, sx=sx, sy=sy, size=size)
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
def _match_icon_template(self, roi_path: str, template_path: str, threshold: float | None = None) -> Tuple[bool, float]:
|
||||
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
|
||||
|
||||
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
|
||||
如果提供 `threshold` 则使用该阈值判断匹配,否则回退到配置 `yanghao_icon_match_threshold`。
|
||||
返回 (detected, score),若发生错误或文件缺失返回 (False, 0.0)。
|
||||
"""
|
||||
try:
|
||||
if not roi_path or not os.path.exists(roi_path):
|
||||
return False, 0.0
|
||||
if not template_path or not os.path.exists(template_path):
|
||||
return False, 0.0
|
||||
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
roi_img = Image.open(roi_path).convert("RGB")
|
||||
tpl_img = Image.open(template_path).convert("RGB")
|
||||
|
||||
rw, rh = roi_img.size
|
||||
tw, th = tpl_img.size
|
||||
# 若模板比 ROI 大,等比缩小模板
|
||||
if tw > rw or th > rh:
|
||||
scale = min(rw / tw, rh / th, 1.0)
|
||||
new_w = max(1, int(tw * scale))
|
||||
new_h = max(1, int(th * scale))
|
||||
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
tw, th = tpl_img.size
|
||||
|
||||
# 转为灰度数组
|
||||
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
|
||||
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
|
||||
|
||||
# 若模板尺寸等于 ROI,则直接计算相关系数
|
||||
if roi_gray.shape[0] == tpl_gray.shape[0] and roi_gray.shape[1] == tpl_gray.shape[1]:
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
else:
|
||||
# 若模板小于 ROI,则优先取 ROI 中心区域与模板尺寸一致的裁剪进行比对(更稳健),
|
||||
# 如果中心裁剪分数很低再退回到滑动搜索(成本较高)
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
# 计算中心裁剪窗口
|
||||
if ih >= th and iw >= tw:
|
||||
cy = ih // 2 - th // 2
|
||||
cx = iw // 2 - tw // 2
|
||||
cy = max(0, min(cy, ih - th))
|
||||
cx = max(0, min(cx, iw - tw))
|
||||
window = roi_gray[cy : cy + th, cx : cx + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = (np.linalg.norm(a) * np.linalg.norm(b))
|
||||
if denom > 1e-6:
|
||||
score = float(np.dot(a, b) / denom)
|
||||
else:
|
||||
score = -1.0
|
||||
# 若中心裁剪得分足够好则直接返回
|
||||
if score >= 0.55:
|
||||
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
# 退回到滑动搜索(简易版),保留原有步长策略
|
||||
ih, iw = roi_gray.shape
|
||||
th, tw = tpl_gray.shape
|
||||
best = -1.0
|
||||
step_y = max(1, th // 6)
|
||||
step_x = max(1, tw // 6)
|
||||
for y in range(0, ih - th + 1, step_y):
|
||||
for x in range(0, iw - tw + 1, step_x):
|
||||
window = roi_gray[y : y + th, x : x + tw]
|
||||
a = window.flatten()
|
||||
b = tpl_gray.flatten()
|
||||
a = a - a.mean()
|
||||
b = b - b.mean()
|
||||
denom = (np.linalg.norm(a) * np.linalg.norm(b))
|
||||
if denom <= 1e-6:
|
||||
continue
|
||||
score = float(np.dot(a, b) / denom)
|
||||
if score > best:
|
||||
best = score
|
||||
if best < -0.5:
|
||||
return False, 0.0
|
||||
score = float(best)
|
||||
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
|
||||
# 同尺寸直接计算相关系数
|
||||
A = roi_gray.flatten()
|
||||
B = tpl_gray.flatten()
|
||||
A = A - A.mean()
|
||||
B = B - B.mean()
|
||||
denom = (np.linalg.norm(A) * np.linalg.norm(B))
|
||||
if denom <= 1e-6:
|
||||
return False, 0.0
|
||||
score = float(np.dot(A, B) / denom)
|
||||
used_thr = float(threshold) if threshold is not None else float(getattr(self, "yanghao_icon_match_threshold", 0.70) or 0.70)
|
||||
detected = score >= used_thr
|
||||
return bool(detected), float(score)
|
||||
except Exception:
|
||||
try:
|
||||
self._log_kv("检测", "_match_icon_template 异常", roi_path=roi_path, template_path=template_path)
|
||||
except Exception:
|
||||
pass
|
||||
return False, 0.0
|
||||
|
||||
def _check_in_live_room_by_icon(
|
||||
self,
|
||||
) -> Tuple[bool, float]: # pyright: ignore[reportAttributeAccessIssue]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"updated_ts": 1767442907.6341074,
|
||||
"updated_ts": 1767488733.548808,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
|
||||
Reference in new issue
Block a user