基于yolov8的游戏人物自动锁定功能

news/2024/9/27 21:30:08 标签: YOLO, 游戏, python

1️⃣加载模型
2️⃣获取屏幕内容
3️⃣获取人物坐标
4️⃣鼠标移动到指定位置

python">import math
import random
import time
import mss
from PIL import Image
import pyautogui
import torch
from pynput.mouse import Controller
from ultralytics import YOLO
#import win32api, win32con

# 加载本地模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = YOLO('yolov8.pt').to(device)
print("Model loaded.")

# 定义屏幕宽高
screen_width, screen_height = pyautogui.size()
game_width = screen_width
game_height = screen_height

rect = (0, 0, game_width, game_height)
m = mss.mss()
mouse_controller = Controller()  # 初始化鼠标控制器
#Windows
# def move(dx, dy):
#     # 鼠标相对当前位置移动
#     win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE,
#                          int(dx * 65536 / game_width), int(dy * 65536 / game_height), 0, 0)
#mac
def move(dx, dy):
    # 鼠标相对当前位置移动
    pyautogui.moveRel(dx, dy)



def window_capture():
    # 使用mss库进行截图
    with mss.mss() as sct:
        sct_img = sct.grab(rect)
        img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')
    return img

# 主循环
while True:

    start_time = time.time()

    try:
        # 截取屏幕
        screen_shot = window_capture()

        # 使用模型进行推理
        results = model(screen_shot)

        # 提取检测结果
        boxes = results[0].boxes.cpu().numpy()

        # 存储有效检测结果
        detections = []
        for box in boxes:
            class_id = int(box.cls)
            confidence = float(box.conf)
            if class_id == 0 and confidence > 0.5:
                xmin, ymin, xmax, ymax = box.xyxy[0]
                center_x = int((xmin + xmax) / 2)
                #center_y = int((ymin + ymax) / 2)
                center_y = int(ymax-(ymax - ymin) * 0.82)
                detections.append((center_x, center_y))
        print(detections)
        if detections:
            # 获取鼠标当前位置
            mouse_x, mouse_y = mouse_controller.position

            # 计算每个检测结果与鼠标位置的距离,并找到最近的目标
            distances = [math.sqrt((mouse_x - x) ** 2 + (mouse_y - y) ** 2) for x, y in detections]
            closest_index = distances.index(min(distances))
            closest_target = detections[closest_index]

            # 控制鼠标移动到最近目标处
            delta_x = closest_target[0] - mouse_x
            delta_y = closest_target[1] - mouse_y
            move(delta_x, delta_y)

    except Exception as e:
        print(f"An error occurred: {e}")

    elapsed_time = time.time() - start_time
    print(f"Elapsed time: {elapsed_time:.2f} seconds")

http://www.niftyadmin.cn/n/5679596.html

相关文章

python用两类循环嵌套打印正置九九乘法口诀表和倒置九九乘法口诀表

一、正置九九乘法口诀表&#xff1a; 1&#xff09;while循环嵌套&#xff1a; i 1 #定义外层循环控制变量 while i < 9:j 1 #定义内层循环控制变量while j < i:print(f"{j}*{i}{j*i}\t",end ) #内层循环要求打印每个表达式后对…

【Linux第五课-进程上】PCB内部属性、标识符、进程状态、Linux下的进程状态、进程的优先级、Linux进程的调度与切换

目录 体系结构 -- 硬件上操作系统 -- 软件上进程PCB内部属性1、在linux里面看程序2、标识符获取程序的标识符父进程标识符 PPID查看进程的另一种方法通过系统调用创建进程 - fork杀掉一个进程for循环创建多个代码 3、进程状态进程排队 - 队列教程上关于进程状态表述运行阻塞&am…

tomcat 文件上传 (CVE-2017-12615)

漏洞描述&#xff1a; 当 Tomcat 运行在 Windows 主机上&#xff0c;且启用了 HTTP PUT 请求方法 影响范围&#xff1a; Apache Tomcat 7.0.0 - 7.0.79 漏洞复现&#xff1a; 创建vulfocus靶场容器 poc #CVE-2017-12615 POC import requests import optparse import ospar…

服务器的地址如何伪装起来

要伪装服务器的地址&#xff0c;可以通过多种方式来隐藏或改变其实际IP地址&#xff0c;使得外部无法轻易知道服务器的真实位置。这些方法通常用于保护隐私、提高安全性、绕过地理限制或防止攻击。以下是几种常见的伪装服务器地址的方法&#xff1a; 1. 使用代理服务器 概念&…

字节豆包C++一面-面经总结

talk is cheap show me the code lc206&#xff1a;链表反转&#xff1a;给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 class Solution { public:ListNode* reverseList(ListNode* head) {if(headnullptr||!head->next)return head…

Unity角色控制及Animator动画切换如走跑跳攻击

Unity角色控制及 Animator动画切换如走跑跳攻击 目录 Unity角色控制及 一、 概念 1、角色控制 1) CharacterController(角色控制器) 2) CapsuleCollider + Rigidbody(使用物理刚体控制) 2、角色动画-Animation、Animator 1) 旧版动画系统

Efficient DETR: Improving End-to-End Object Detector with Dense Prior

原文链接 [2104.01318] Efficient DETR: Improving End-to-End Object Detector with Dense Prior (arxiv.org)https://arxiv.org/abs/2104.01318 原文笔记 What 1、一种针对DETR的objectquery初始化的方法 2、针对Deformable DETR进行改进&#xff0c;改进之后的模型具有…

只能说是未来可期(AI进阶篇:FLUX-5 ControlNetIP-Adapter)

大家好我是安琪&#xff01;&#xff01;&#xff01; 大部分有了一定AI绘画基础的小伙伴在AI创作的过程中应该都离不开一个东西&#xff0c;那就是ControlNet。 ControlNet一度被视为是AI绘图模型在可控性上的终极解决方案&#xff0c;要知道AI绘画在早期最令人诟病的地方就…