## 一、从一次深夜调试说起
上周三凌晨两点,我盯着屏幕上一行诡异的报错发愣——游戏窗口突然失去焦点,YOLO模型连续十几帧检测不到任何怪物,但脚本还在机械地点击最后记住的坐标。日志里堆满了`cv2.error`和`NoneType`异常,而我的`try...except`像个筛子,漏掉了最关键的状态异常。
那一刻我意识到:把YOLO检测、鼠标操作、窗口控制这些模块拼在一起,只是“能跑起来”的demo。要让它真正稳定运行,得用工程化的思维重新审视整个系统。
---
## 二、工程化封装:别把脚本写成意大利面
早期版本的主循环大概长这样:
```python
while True:
img = grab_screen()
results = model(img)
for box in results:
x, y = calc_center(box)
click(x, y)
time.sleep(0.1)
```
看起来清晰?等你要加状态监控、异常恢复、配置热更新时,代码就会变成面条。我的重构方案是分层封装:
```python
class DetectionPipeline:
"""把检测流程包起来,这里踩过坑——原来把预处理和后处理拆开了,结果帧率掉了一半"""
def __init__(self, model, preprocess=None):
self.model = model
self.preprocess = preprocess or self._default_preprocess # 给个默认预处理,避免外面传None
self._last_valid_result = None # 缓存上次结果,断帧时用得上
def run(self, frame):
# 这里加个帧有效性检查,避免黑屏帧进模型
if frame is None or frame.size == 0:
logger.warning("空帧输入,返回上次结果")
return self._last_valid_result
processed = self.preprocess(frame)
results = self.model(processed)
self._last_valid_result = results
return results
class ActionExecuto
768



被折叠的 条评论
为什么被折叠?



