基于YOLO检测实现蓝色气泡悬停时自动鼠标点击的技术问询
解决YOLO检测后自动点击蓝色气泡的问题
问题分析与修复方案
1. 替换mouse.click为更可靠的Windows API模拟点击
mouse.click常存在模拟精度不足、系统兼容性差的问题,改用win32api直接模拟硬件级点击,稳定性更高:
import win32api import win32con def simulate_click(x, y): # 确保鼠标移动到目标位置 win32api.SetCursorPos((x, y)) # 模拟左键按下 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) # 模拟左键抬起(必须配对,否则会持续按住左键) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
2. 优化点击触发时机
避免检测到目标瞬间就点击(此时鼠标可能还在移动),需等鼠标稳定悬停在气泡上后再执行点击。可以通过连续帧验证或添加延迟实现:
import time # 假设detect_blue_bubble()返回气泡屏幕坐标(x,y),无目标返回None last_target = None stable_frame_count = 0 while True: target_pos = detect_blue_bubble() if target_pos and is_click_enabled(): # 检查是否连续3帧检测到同一区域的目标(误差范围5像素) if last_target and abs(target_pos[0]-last_target[0]) < 5 and abs(target_pos[1]-last_target[1]) <5: stable_frame_count +=1 if stable_frame_count >=3: simulate_click(*target_pos) stable_frame_count = 0 # 点击后重置计数,避免重复触发 else: last_target = target_pos stable_frame_count =1 win32api.SetCursorPos(target_pos) else: last_target = None stable_frame_count =0 time.sleep(0.05) # 控制检测频率,避免资源占用过高
3. 结合现有函数完善逻辑
利用你提供的is_click_enabled()控制自动点击开关,用is_targeted()判断是否手动按住鼠标,此时跳过自动点击避免冲突:
def auto_click_on_bubble(target_pos): if not is_click_enabled(): return # 手动按住左键时,不执行自动点击 if is_targeted(): return win32api.SetCursorPos(target_pos) time.sleep(0.1) # 短暂延迟确保鼠标稳定 simulate_click(*target_pos)
4. 验证坐标准确性
如果点击总是偏位,先确认YOLO返回的坐标是否为屏幕坐标系:部分模型返回的是图像相对坐标,需要转换为屏幕坐标(需先获取目标窗口的位置参数):
# 示例:图像坐标转屏幕坐标 def image_to_screen(img_x, img_y, window_rect): # window_rect为目标窗口的(left, top, right, bottom) screen_x = window_rect[0] + int(img_x) screen_y = window_rect[1] + int(img_y) return (screen_x, screen_y)
内容的提问来源于stack exchange,提问作者Snn
相关产品推荐
相关产品推荐

