How can I remove points from a list which are close to points in another list by some distance

痴心易碎 提交于 2019-12-23 02:18:49

问题


I have 2 lists of coordinates of points in an image.

Say,

List1 = [[2,3],[4,5],[10,20],[45,60]]
List2 = [[100,50],[65,48],[58,32],[98,45]...............[655,254],[232,545]]

dist = 20

List1 would have 5 or 6 elements. List2 could have more than 1000 elements.

I want to generate a list3 in which I have only the coordinates from List2 whose euclidean distance from all the points in List1 is more than dist=20.

Basically my aim is to remove all points from List2 which are near to points in List1 by some distance.

Currently, I am doing something like this

from scipy.spatial.distance import cdist

def newlist(list1, list2, dist):
    edist = cdist(list2, list1)
    highvalues = edist > dist
    edist[highvalues] = 0
    edist[~highvalues] = 1
    indx = edist.sum(axis=1)
    list3 = [list2[i] for i, e in enumerate(indx) if e == 0]

    return list3

Runtime: 52us


回答1:


List3= [p for p in List2 if all(cdist(i,p)>20 for i in List1)]



回答2:


simply for cal euclidean distance you must import euclidean from scipy.spatial.distance

from scipy.spatial.distance import euclidean
new_list=[]
for i in List2:
    for j in List1:
        if euclidean(i,j)>20:
            continue        
    new_list.append(i)



回答3:


Instead of using inefficient for-loops, one can use boolean array indexing in NumPy with np.all:

import numpy as np
from scipy.spatial.distance import cdist

points = np.array([[0,1], [2,0], [4,5], [6,7], [9,9], [8,10]])
reference = np.array([[0,0], [10,10]])
distance = 3

filtered_points = points[np.all(cdist(points, reference) >= distance, axis=1)]
print(filtered_points)
# array([[4, 5],
#        [6, 7]])

Note that you can also change Euclidian metric to any other one. See docs on scipy.spatial.distance.cdist for details. For example for Manhattan distance one would write cdist(points, reference, metric='cityblock') instead.



来源:https://stackoverflow.com/questions/25660892/how-can-i-remove-points-from-a-list-which-are-close-to-points-in-another-list-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!