pandas 如何在python中获取最近的实体[已关闭]

lsmd5eda  于 2022-11-20  发布在  Python
关注(0)|答案(1)|浏览(154)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
4天前关闭。
Improve this question
我的代码:

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

现在唯一的问题是,它似乎没有得到最近的敌人,是我的数学错误吗?如果我的数学应该是错误的,我如何改善它?同样,如果我的数学是正确的,我如何改善它,以实现我的目标,得到最近的实体?任何帮助将非常感谢。提前感谢每一个人谁投资他/她的时间在帮助我:)

xeufq47z

xeufq47z1#

不太清楚,你到底在找什么......不过我猜,在计算敌人的中心位置时,可能会出现一个小错误用途:

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

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

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

**附加备注:**从性能Angular 来看,在panda Dataframe 上进行迭代并不是一个好主意。另一种方法是在 Dataframe 中添加一个新列distance,然后搜索最小值的索引:

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

相关问题