I crafted a function for you.
Here is your line, which I call old_line:
old_line=LineString([(0,0), (9,0)]) # your line with 2 vertices
Here is the function that takes a line geometry as main input, you assign a step (i.e the spacing along the old line) and and additional Coordinate Reference System (crs) to georeference the new densified line.
def densify_geometry (line_geometry, step, crs=None):
# crs: epsg code of a coordinate reference system you want your line to be georeferenced with
# step: add a vertice every step in whatever unit your coordinate reference system use.
length_m=line_geometry.length # get the length
xy=[] # to store new tuples of coordinates
for distance_along_old_line in np.arange(0,int(length_m),step):
point = line_geometry.interpolate(distance_along_old_line) # interpolate a point every step along the old line
xp,yp = point.x, point.y # extract the coordinates
xy.append((xp,yp)) # and store them in xy list
new_line=LineString(xy) # Here, we finally create a new line with densified points.
if crs != None: # If you want to georeference your new geometry, uses crs to do the job.
new_line_geo=gpd.geoseries.GeoSeries(new_line,crs=crs)
return new_line_geo
else:
return new_line
Now, running:
densify_geometry(line_geometry=old_line, step= 0.5, crs= 32754)
returns:
LINESTRING (0.00000 0.00000, 0.50000 0.00000, ...
dtype: geometry
If you want to .apply it to a whole GeoDataFrame
geometry column:
kwargs_dict={'step':0.5,
'crs':32754}
your_gdf["new_geometry"]=your_gdf.geometry.apply(densify_geometry, kwargs=**kwargs_dict)
This should do the job.
interpolate
like BERA suggested. If you want better time complexity, you might try splitting large linestrings several times beforehand. At one point I had written my own interpolate function in python. But the linestrings needed to be very large and the interpolate distance pretty small in order for it to actually be faster than using shapely'sinterpolate
over and over again. And now I realize it would have been much faster just to split a couple times.interpolate
, thensplit
function and finalized it withlinemerge
. @JeremiahEngland @BERA