I have the following question. I have a box full of coordinates and three points, which build up a line. Now i want to calculate the shortest distance of all box coordinates to that line. I have three methods to do that and the vtk and numpy version always have the same result but not the distance method of shapely. But i need the shapely version, because i want to measure the closest distance from a point to the hwole line and not to the seperate line segments. Here is an example code so far. So the problem is the "pdist":
from shapely.geometry import LineString, Point
import vtk, numpy as np
import itertools
import math
from numpy.linalg import norm
x1=np.arange(4,21)
y1=np.arange(4,21)
z1=np.arange(-7,6)
linepoints = np.array([[1,10,0],[10,10,0],[15,15,0]])
for i in itertools.product(x1,y1,z1):
for m in range(len(linepoints)-1):
line3 = LineString([linepoints[m],linepoints[m+1]])
p = Point(i)
d = norm(np.cross(linepoints[m]-linepoints[m+1], linepoints[m]-i))/norm(linepoints[m+1]-linepoints[m])
dist=math.sqrt(vtk.vtkLine().DistanceToLine(i,linepoints[m],linepoints[m+1]))
pdist = p.distance(line3)
print(d,dist,pdist)
The problem is that with cross-product you are calculating orthogonal distance to the line spanned by the segment defined by points
linepoints[m]
andlinepoints[m+1]
. On the other hand, Shapely calculates distance to the segment, i.e., it returns the distance either to the orthogonal projection or to one of the boundary points should the orthogonal projection fall "outside" of the segment.To get consistent results, you could calculate the orthogonal projection yourself and then invoke the Shapely distance method:
However, note that Shapely effectively ignores the z-coordinate. Thus for example:
return as distance merely 1.
EDIT: based on your comment, here would be a version which calculates the distance (for arbitrary number of dimensions) to the segment: