I want to add interpolated points in a LineString using shapely. The interpolated points should be in the middle of every two Points present in the LineString. The shapely interpolate
function adds the Points for the specified distance.
-
1What have you tried so far? Please add a sample script so that the users don't have to build a script from scratch.– NouraCommented Jan 15, 2021 at 10:45
Add a comment
|
1 Answer
This should work using Shapely and its centroid logic.
>>> from shapely.geometry import LineString
>>> line = LineString([(-99.156916, 23.731817), (-99.131389, 23.746944)])
>>> line.centroid.x
-99.14415249999999
>>> line.centroid.y
23.7393805
If the linestring has multiple points, you could do something like this:
from shapely.geometry import LineString, Point, MultiPoint
def pairs(lst):
for i in range(1, len(lst)):
yield lst[i-1], lst[i]
line = LineString([(-73.99985280540224153, 40.72083221571505618), (-73.98959491620782103, 40.73375715610002601), (-74.00313532994445609, 40.7397067318327899), (-73.99349291410169371, 40.75160588329831768), (-73.98118344706838911, 40.74627178091721902), (-73.97256682014507589, 40.75776061681496998), (-73.98610723388171095, 40.76371019254773387), (-73.97215650457729907, 40.77909702633935751), (-73.96641208662842359, 40.78648270655934027), (-73.96169345759899727, 40.7932529134276578)])
centroids = []
for pair in pairs(list(line.coords)):
linestring_pair = LineString([pair[0], pair[1]])
centroids.append(Point(linestring_pair.centroid.x, linestring_pair.centroid.y))
print(MultiPoint(points=list(centroids)).wkt)
# MULTIPOINT (-73.99472386080504 40.72729468590754, -73.99636512307615 40.7367319439664, -73.99831412202307 40.74565630756555, -73.98733818058504 40.74893883210777, -73.97687513360674 40.75201619886609, -73.9793370270134 40.76073540468136, -73.97913186922951 40.77140360944355, -73.96928429560286 40.78278986644935, -73.96405277211372 40.7898678099935)
which would look like this:
-
But this would work for LineStrings having two points only. My LineStrings have multiple points. Centroid function will just return a single point.– ArcherCommented Jan 15, 2021 at 10:34
-
-
I updated the response for multiple segments @Archer Commented Jan 15, 2021 at 10:49
-
@TimothyDalton Thanks a lot. This should work. I am just concerned about computation time though. I have 3 million LineStrings to process.– ArcherCommented Jan 15, 2021 at 11:28
-
1@Archer how long are the linestrings? I would use multiprocessing and break the list of linestrings up into chunks pymotw.com/2/multiprocessing/basics.html and let your CPUs do the rest. It shouldn't take very long, just make sure you aren't printing the result. Commented Jan 15, 2021 at 11:37