【问题标题】:How can I get the nearest entity in python如何在python中获取最近的实体
【发布时间】:2022-11-15 15:35:22
【问题描述】:

我的代码:

from mss import mss
import math
import cv2
import numpy as np
import torch

model = torch.hub.load(r'yolov5-master', 'custom', path=r'8.pt', source='local')



with mss() as sct:
   monitor = {"top": 220, "left": 640, "width": 640, "height":640}    

while True:
    screenshot = np.array(sct.grab(monitor))
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2RGB)
    results = model(screenshot, size=640)
    df = results.pandas().xyxy[0]
    distances = [] 
    closest = 1000
           
    for i in range(len(results.xyxy[0])):                        
       try:

          xmin = int(df.iloc[i, 0])
          ymin = int(df.iloc[i, 1])
          xmax = int(df.iloc[i, 2])
          ymax = int(df.iloc[i, 3])
          
          centerX = (xmax + xmin) / 2 + xmin
          centerY = (ymax + ymin) / 2 + ymin
          
          distance2 = math.sqrt(((centerX - 320) ** 2) + ((centerY - 320) ** 2))
          distances.append(distance2)
          if closest > distances[i]:
              closest = distances[i]
              closestEnemy = i

现在唯一的问题是它似乎没有找到最近的敌人,我的数学错了吗?如果我的数学应该是错误的,我该如何改进它?此外,如果我的数学是正确的,我该如何改进它以实现获得最近实体的目标?任何帮助都会非常感激。提前感谢所有投入时间帮助我的人:)

【问题讨论】:

  • minimal reproducible example 是必需的。请查看How to Ask
  • 嘿@ChristophRackwitz,谢谢你的遮阳篷,你需要哪些信息?我很乐意添加它。
  • 如果你需要复习数学:思考 (xmax + xmin) / 2 + xmin 的含义,你可能想要一些稍微不同的东西。 -- MRE 表示 MRE。这个问题缺少输入数据。你没有说它是什么游戏,你没有提供屏幕截图数据......你的整个问题没有解释你在做什么或为什么。您只是跳入问题中,希望读者将难题拼凑起来。
  • 它基本上是用于用 python 编写的人体检测软件。它与 mss 和 CV2 一起使用,因此您可以有一个实时窗口来显示对人类的检测。

标签: python pandas math pytorch mss


【解决方案1】:

目前还不完全清楚,你在追求什么......但我的猜测是,在计算敌人的中心时有一个小错误。要么使用:

centerX = (xmax + xmin) / 2  # do not add xmin here
centerY = (ymax + ymin) / 2  # do not add xmax here

或计算最小值和最大值之间的距离并再次添加最小值:

centerX = (xmax - xmin) / 2 + xmin  # subtract minimum from maximum
centerY = (ymax - ymin) / 2 + ymin # subtract minimum from maximum

补充说明:性能方面,主要是不是遍历 pandas 数据框是个好主意。另一种方法是向数据框添加一个新列distance,然后查看最小值的索引:

df['distance'] = (
    (( (df['xmax']+df['xmin'])/2 - 320) ** 2) + 
    (( (df['ymax']+df['ymin'])/2 - 320) ** 2)
    ) **0.5
         
closest_enemy = df['distance'].idxmin()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2018-12-11
    • 2016-11-12
    • 2016-10-31
    • 2022-07-06
    相关资源
    最近更新 更多