Python:如何使用欧几里德算法从列表中选择X、Y点

2024-10-03 23:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个自己的质心跟踪器来跟踪视频中的一些对象

从我的检测函数中,我从给定的数据中得到一个列表,列表的格式如下:

[startX, startY, endX, endY,cX,cY,score]

这是检测到两个对象时的示例:

[[10,10,200,200,105,105,0.9],[350,120,410,500,380,310,0.7]]

我想做一个函数,从给定的质心点X,Y,从我的跟踪器返回列表中最近的(cX,cY)

最好的方法是什么?所有质心跟踪器都使用欧几里德算法来计算距离。这是最好的方式吗?有人能给我解释一下吗

我在一个网站上找到了这个功能:

def pClosest(points, K):
 
    points.sort(key = lambda K: K[0]**2 + K[1]**2)
 
    return points[:K]
 
# Driver program
points = [[3, 3], [5, -1], [-2, 4]]
 
K = 2
 
print(pClosest(points, K))

我怎样才能把它转换成我所需要的


Tags: 数据对象函数列表视频格式pointscx
2条回答

您可以使用np.linalg.normord=2来获得两个numpy数组之间的欧几里德距离。应用于您的示例,您可以使用以下内容:

from collections import namedtuple
import numpy as np

# Introduce a named tuple for named access to start/end/center points
DetectedObject = namedtuple("DetectedObject", 
                            ("start", "end", "center", "score"))

# I am storing your examples as DetectedObjects, each point is
# a vector of length 2.
examples = [DetectedObject(start=np.asarray([10, 10]),  # store point coordinates in array
                          end=np.asarray([200, 200]),
                          center=np.asarray([105, 105]),
                          score=0.9),
           DetectedObject(start=np.asarray([350, 120]),
                          end=np.asarray([410, 500]),
                          center=np.asarray([380, 310]),
                          score=0.7)]


def get_centers(objects):
    """Retrieve center points from DetectedObject."""
    return np.asarray(list(map(lambda o: o.center, objects)))

def get_closest_object_to_centroid(centroid, objects):
    """Given a centroid, extract the closest object from a collection of DetectedObjects."""
    centers = get_centers(objects)
    # instead of the norm you could also use np.sum((centroid-centers)**2, axis=1)
    closest_index = np.argmin(np.linalg.norm(centroid-centers, ord=2, axis=1))
    return objects[closest_index]

然后您可以按如下方式使用它:

closest = get_closest_object_to_centroid(centroid=np.asarray([10, 10]),
                                         objects=examples)
closest  # DetectedObject(start=array([10, 10]), end=array([200, 200]), center=array([105, 105]), score=0.9)

我的一位朋友向我发送了此功能:

from scipy.spatial.distance import cdist
def closest_node(node, nodes):
    lista = []
    for item in nodes:
      lista.append([item[4],item[5]])
    return nodes[cdist([node], lista).argmin()]
 
# Driver program
points = [[10,10,200,200,105,105,0.9],[350,120,410,500,380,310,0.7]]
 
point = [30,50]

print(closest_node(point,points))

这很有效

相关问题 更多 >