用途,在截图中寻找离屏幕中心(人物所在位置)最近的怪物坐标。
import cv2
import torch
import numpy as np
import math
yolov7 = torch.hub.load('d:/yolov7', 'custom', 'D:/yolov7/weights/best.pt', source='local', force_reload=False)
img = cv2.imread('22.png')
img = img.copy()[:, :, ::-1]
results = yolov7(img, size=640) # 图片尺寸
bboxes = np.array(results.pandas().xyxy[0])
# 定义图像的宽度和高度
width = 640
height = 640
# 计算中心点的坐标
center_x = width / 2
center_y = height / 2
# 初始化最近目标的距离和位置
min_distance = float('inf')
closest_target = None
# 遍历所有检测到的目标
for target in bboxes:
# 计算目标的中心点坐标
x1, y1, x2, y2 = target[:4]
target_x = (x1 + x2) / 2
target_y = (y1 + y2) / 2
# 计算目标与中心点的欧几里得距离
distance = math.sqrt((target_x - center_x) ** 2 + (target_y - center_y) ** 2)
# 更新最近目标的距离和位置
if distance < min_distance:
min_distance = distance
closest_target = int((target[0]+ target[2])/2), int((target[1]+ target[3])/2)
# 打印最近目标的位置
# mouse_move(closest_target)
print(closest_target)
评论0