| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- # -*- coding: utf-8 -*-
- """测谎出现后:YOLO + ByteTrack 跟踪白形目标,Interception 鼠标跟红准星(预测中心)。"""
- from __future__ import annotations
- import sys
- import threading
- import time
- from pathlib import Path
- from typing import Callable, Optional, Tuple
- import cv2
- import numpy as np
- CH_ROOT = Path(__file__).resolve().parent.parent
- if str(CH_ROOT) not in sys.path:
- sys.path.insert(0, str(CH_ROOT))
- from tracker import mouse_control
- from tracker.mot_tracker import MotYoloTracker
- from tracker.paths import MODELS_DIR
- LogFn = Callable[[str], None]
- RegionFn = Callable[[], Optional[Tuple[int, int, int, int]]] # x,y,w,h screen
- def _default_log(msg: str) -> None:
- print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
- def grab_region_bgr(x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
- """按屏幕矩形截 BGR(mss)。"""
- try:
- import mss
- except ImportError:
- return None
- w, h = max(1, int(w)), max(1, int(h))
- with mss.mss() as sct:
- shot = sct.grab({"left": int(x), "top": int(y), "width": w, "height": h})
- return cv2.cvtColor(np.array(shot), cv2.COLOR_BGRA2BGR)
- class AimSession:
- """一次测谎瞄准会话:跑满 duration 或连续丢目标就停。"""
- def __init__(
- self,
- *,
- weights: Optional[str] = None,
- backend: str = "bytetrack",
- conf: float = 0.25,
- imgsz: int = 640,
- duration_seconds: float = 25.0,
- miss_stop_frames: int = 45,
- gain: float = 1.0,
- deadzone: float = 1.5,
- min_conf: float = 0.20,
- show_overlay: bool = False,
- log: Optional[LogFn] = None,
- ):
- self.weights = str(weights or (MODELS_DIR / "best.pt"))
- self.backend = backend
- self.conf = float(conf)
- self.imgsz = int(imgsz)
- self.duration_seconds = float(duration_seconds)
- self.miss_stop_frames = max(5, int(miss_stop_frames))
- self.gain = float(gain)
- self.deadzone = float(deadzone)
- self.min_conf = float(min_conf)
- self.show_overlay = bool(show_overlay)
- self.log = log or _default_log
- self._stop = threading.Event()
- self._thread: Optional[threading.Thread] = None
- self._tracker: Optional[MotYoloTracker] = None
- self.running = False
- self.frames = 0
- self.hits = 0
- self.last_conf = 0.0
- self.last_center: Optional[Tuple[float, float]] = None
- @property
- def alive(self) -> bool:
- return self._thread is not None and self._thread.is_alive()
- def stop(self) -> None:
- self._stop.set()
- def _build_tracker(self) -> MotYoloTracker:
- if self.backend not in ("bytetrack", "deepsort"):
- # 瞄准默认 ByteTrack;其它名字也落到 bytetrack
- method = "bytetrack"
- else:
- method = self.backend
- return MotYoloTracker(
- weights=self.weights,
- method=method,
- conf=self.conf,
- imgsz=self.imgsz,
- include_decoy_dets=False, # 瞄准只要主目标,干扰项别抢鼠标
- )
- def start(self, region_fn: RegionFn) -> bool:
- """异步启动。region_fn 每帧返回游戏客户区屏幕矩形。"""
- if self.alive:
- self.log("瞄准已在跑,忽略重复启动")
- return False
- if not Path(self.weights).exists():
- self.log("找不到 YOLO 权重:%s" % self.weights)
- return False
- if not mouse_control.ensure_ready():
- self.log("Interception 未就绪:%s" % (mouse_control.last_error() or "?"))
- return False
- self._stop.clear()
- self.frames = self.hits = 0
- self.last_conf = 0.0
- self.last_center = None
- self._thread = threading.Thread(
- target=self._run, args=(region_fn,), daemon=True, name="aim-session"
- )
- self._thread.start()
- return True
- def _run(self, region_fn: RegionFn) -> None:
- self.running = True
- t0 = time.time()
- miss = 0
- try:
- self.log("瞄准启动:backend=%s conf=%.2f 最长 %.0fs"
- % (self.backend, self.conf, self.duration_seconds))
- self._tracker = self._build_tracker()
- # 先抓一帧做 warmup,避免首帧卡顿
- region = region_fn()
- if region:
- frame = grab_region_bgr(*region)
- if frame is not None:
- self._tracker.warmup(frame)
- self._tracker.reset()
- while not self._stop.is_set():
- if time.time() - t0 >= self.duration_seconds:
- self.log("瞄准结束:到达时长上限")
- break
- region = region_fn()
- if not region or region[2] < 64 or region[3] < 64:
- time.sleep(0.05)
- continue
- rx, ry, rw, rh = region
- frame = grab_region_bgr(rx, ry, rw, rh)
- if frame is None:
- time.sleep(0.03)
- continue
- det = self._tracker.track(frame)
- self.frames += 1
- if det.center is None or det.conf < self.min_conf:
- miss += 1
- self.last_conf = float(det.conf or 0.0)
- if miss >= self.miss_stop_frames:
- self.log("瞄准结束:连续 %d 帧丢目标" % miss)
- break
- else:
- miss = 0
- self.hits += 1
- self.last_conf = float(det.conf)
- cx, cy = det.center
- self.last_center = (cx, cy)
- sx, sy = rx + cx, ry + cy
- try:
- mouse_control.follow_screen_point(
- sx, sy, gain=self.gain, deadzone=self.deadzone
- )
- except Exception as exc:
- self.log("鼠标移动失败:%s" % exc)
- break
- if self.show_overlay and det.center is not None:
- vis = frame.copy()
- x, y = int(det.center[0]), int(det.center[1])
- cv2.drawMarker(vis, (x, y), (0, 0, 255), cv2.MARKER_CROSS, 24, 2)
- if det.xyxy:
- x1, y1, x2, y2 = map(int, det.xyxy)
- cv2.rectangle(vis, (x1, y1), (x2, y2), (0, 140, 255), 2)
- cv2.imshow("aim-assist", vis)
- if cv2.waitKey(1) & 0xFF == ord("q"):
- self.log("瞄准结束:手动关闭预览")
- break
- else:
- # 控制节奏,别把 GPU/CPU 打满;约 30~40 FPS 足够跟准星
- time.sleep(0.01)
- except Exception as exc:
- self.log("瞄准异常:%s" % exc)
- finally:
- self.running = False
- if self.show_overlay:
- try:
- cv2.destroyWindow("aim-assist")
- except Exception:
- pass
- elapsed = time.time() - t0
- self.log("瞄准收工:%.1fs · %d 帧 · 命中 %d · 末置信度 %.2f"
- % (elapsed, self.frames, self.hits, self.last_conf))
- class AimAssistController:
- """给测谎提醒用的薄封装:配置 + 按需起停会话。"""
- def __init__(self, cfg: dict, region_fn: RegionFn, log: Optional[LogFn] = None):
- self.cfg = cfg or {}
- self.region_fn = region_fn
- self.log = log or _default_log
- self._session: Optional[AimSession] = None
- self._lock = threading.Lock()
- @property
- def enabled(self) -> bool:
- return bool(self.cfg.get("enabled", True))
- def stop(self) -> None:
- with self._lock:
- if self._session is not None:
- self._session.stop()
- def trigger(self, *, manual: bool = False) -> bool:
- """测谎报警后调用。返回是否真正启动了会话。"""
- if not self.enabled:
- return False
- if manual and not self.cfg.get("on_manual_test", False):
- return False
- with self._lock:
- if self._session is not None and self._session.alive:
- # 已在跟:刷新也不另起,避免两套抢鼠标
- return False
- weights = self.cfg.get("weights")
- if weights:
- wpath = Path(weights)
- if not wpath.is_absolute():
- wpath = CH_ROOT / wpath
- else:
- wpath = MODELS_DIR / "best.pt"
- self._session = AimSession(
- weights=str(wpath),
- backend=str(self.cfg.get("backend", "bytetrack")),
- conf=float(self.cfg.get("conf", 0.25)),
- imgsz=int(self.cfg.get("imgsz", 640)),
- duration_seconds=float(self.cfg.get("duration_seconds", 25)),
- miss_stop_frames=int(self.cfg.get("miss_stop_frames", 45)),
- gain=float(self.cfg.get("gain", 1.0)),
- deadzone=float(self.cfg.get("deadzone", 1.5)),
- min_conf=float(self.cfg.get("min_conf", 0.20)),
- show_overlay=bool(self.cfg.get("show_overlay", False)),
- log=self.log,
- )
- return self._session.start(self.region_fn)
|