How can I get the nearest entity in python

Question:

My code:

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

Only problem now is that it doesn’t seem to get the closest enemy, is my math wrong? If my math should be wrong, how can I improve it? Also if my math is correct, how can I improve it in order to achieve my goal of getting the nearest entity? Any help will be very appriciated. Thanks in advance to everyone who invests his / her time in helping me 🙂

Asked By: JorgTV

||

Answers:

It’s not entirely clear, what you are after… but my guess is, that there is a small mistake when calculating the center of the enemies. Either use:

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

or calculate the distance between the minimum and maximum values and add the minim again:

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

Additional remark:
Performance wise it is mostly not a good idea to iterate over a pandas data frame. Another approach is to add a new column distance to the data frame and then search for the index of the minimum value:

df['distance'] = (
    (( (df['xmax']+df['xmin'])/2 - 320) ** 2) + 
    (( (df['ymax']+df['ymin'])/2 - 320) ** 2)
    ) **0.5
         
closest_enemy = df['distance'].idxmin()
Answered By: rosa b.
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.