Skip to main content
 首页 » 编程设计

python之到凸包的距离

2025年05月04日8zfyouxi

我一直在寻找一种方法来计算到凸包/多边形的距离,如果点在包内则距离为正,如果点在包外则为负。例如,给定一个船体和一组点,是否可以计算正/负距离?

from scipy.spatial import ConvexHull 
import matplotlib.pyplot as plt 
import numpy as np 
 
# Original points, hull and test points 
points = np.random.rand(30, 2)   # 30 random points in 2-D 
hull = ConvexHull(points) 
newpoints = np.random.rand(30, 2)   # 30 random points in 2-D 
 
# Plot original points, hull and new points 
plt.plot(points[:,0], points[:,1], 'ro') 
plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r--', lw=2) 
plt.plot(newpoints[:,0], newpoints[:,1], 'go') 

所以在上面我想为每个绿点计算这个带符号的距离。非常感谢您的宝贵时间!!

更新,使用来自(http://www.fundza.com/vectors/point2line/index.html)的代码可以计算无符号距离:

from scipy.spatial import ConvexHull 
import matplotlib.pyplot as plt 
import numpy as np 
from vectors import * 
 
# Original points, hull and test points 
points = np.random.rand(30, 2)   # 30 random points in 2-D 
hull = ConvexHull(points) 
newpoints = np.random.rand(30, 2)   # 30 random points in 2-D 
 
 
 
def pnt2line(pnt, start, end): 
    line_vec = vector(start, end) 
    pnt_vec = vector(start, pnt) 
    line_len = length(line_vec) 
    line_unitvec = unit(line_vec) 
    pnt_vec_scaled = scale(pnt_vec, 1.0/line_len) 
    t = dot(line_unitvec, pnt_vec_scaled)     
    if t < 0.0: 
        t = 0.0 
    elif t > 1.0: 
        t = 1.0 
    nearest = scale(line_vec, t) 
    dist = distance(nearest, pnt_vec) 
    nearest = add(nearest, start) 
    return (dist, nearest) 
 
 
 
pt_dist = [] 
for p_idx in range(30): 
    pt = newpoints[p_idx,:] 
    dist_list = [] 
    for v_idx in range(len(hull.vertices)): 
        v1 = hull.vertices[v_idx - 1] 
        v2 = hull.vertices[v_idx] 
        start = points[v1] 
        end = points[v2] 
        temp = pnt2line(pt, start, end) 
        dist_list.append(temp[0]) 
    pt_dist.append(min(dist_list)) 
 
 
# Plot original points, hull and new points 
plt.plot(points[:,0], points[:,1], 'ro') 
plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r--', lw=2) 
plt.plot(newpoints[:,0], newpoints[:,1], 'go') 
for p_idx in range(30): 
    pt = newpoints[p_idx,:] 
    dist = pt_dist[p_idx] 
    distLabel = "%.2f" % dist 
    plt.annotate(distLabel,xy=pt) 

(注意将 vector.py 代码修改为 2d):

import math 
 
def dot(v,w): 
    x,y = v 
    X,Y = w 
    return x*X + y*Y 
 
def length(v): 
    x,y = v 
    return math.sqrt(x*x + y*y) 
 
def vector(b,e): 
    x,y = b 
    X,Y = e 
    return (X-x, Y-y) 
 
def unit(v): 
    x,y = v 
    mag = length(v) 
    return (x/mag, y/mag) 
 
def distance(p0,p1): 
    return length(vector(p0,p1)) 
 
def scale(v,sc): 
    x,y = v 
    return (x * sc, y * sc) 
 
def add(v,w): 
    x,y = v 
    X,Y = w 
    return (x+X, y+Y) 

请您参考如下方法:

您始终可以将这个正距离乘以 Point in Polygon 的真/假结果。计算。我通常喜欢使用缠绕数算法(只是因为我从复杂变量的角度理解它)- 但计算交叉点也很好。