Alex Korzunov
Alex Korzunov

Reputation: 7

How can I remove points that are too close to each other using Shapely?

I've got the following code:

from shapely.geometry import LineString, Point
xs = range(10)
ys = range(10)
points = [Point(x, y) for x, y in zip(x, y)]
line = LineString(points)

Now I want to edit points such that if the two adjacent points are close than MIN_DISTANCE, then I want to remove the latter one: i.e., from line=[(1, 1), (1.1, 1.1), (3, 3)], MIN_DISTANCE=2 I'd get line=[(1, 1), (3, 3)].

Is it OK to write a bruteforce solution (i.e., for point in line) and overwrite the points in line or is there a built in function instead?

Upvotes: 0

Views: 3193

Answers (1)

dzang
dzang

Reputation: 2260

You can use the simplify method to achieve that:

new_line = line.simplify(tolerance=MIN_DISTANCE)

with your example it would be:

from shapely.geometry import LineString, Point
xs = range(10)
ys = range(10)
x, y = zip(*[(1, 1), (1.1, 1.1), (3, 3)])
points = [Point(x, y) for x, y in zip(x, y)]
line = LineString(points)

MIN_DISTANCE = 2
new_line = line.simplify(tolerance=MIN_DISTANCE)

print(f"Original coordinates: {line.xy}")
print(f"Simplified coordinates: {new_line.xy}")


# Original coordinates: (array('d', [1.0, 1.1, 3.0]), array('d', [1.0, 1.1, 3.0]))
# Simplified coordinates: (array('d', [1.0, 3.0]), array('d', [1.0, 3.0]))

Upvotes: 3

Related Questions