MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / ramer_douglas_peucker

Function ramer_douglas_peucker

geometry/ramer_douglas_peucker.py:79–178  ·  view source on GitHub ↗

Simplify a polyline using the Ramer-Douglas-Peucker algorithm. Given a sequence of 2-D points and a maximum allowable deviation *epsilon* (>= 0), returns a simplified list of points such that no discarded point is farther than *epsilon* from the simplified polyline. Parameters

(
    pts: list[tuple[float, float]],
    epsilon: float,
)

Source from the content-addressed store, hash-verified

77
78
79def ramer_douglas_peucker(
80 pts: list[tuple[float, float]],
81 epsilon: float,
82) -> list[tuple[float, float]]:
83 """Simplify a polyline using the Ramer-Douglas-Peucker algorithm.
84
85 Given a sequence of 2-D points and a maximum allowable deviation
86 *epsilon* (>= 0), returns a simplified list of points such that no
87 discarded point is farther than *epsilon* from the simplified polyline.
88
89 Parameters
90 ----------
91 pts:
92 Ordered sequence of ``(x, y)`` points describing the polyline.
93 epsilon:
94 Maximum allowable distance of any discarded point from the
95 simplified polyline. Must be non-negative.
96
97 Returns
98 -------
99 list[tuple[float, float]]
100 Simplified list of ``(x, y)`` points. The first and last points of
101 *pts* are always preserved.
102
103 Raises
104 ------
105 ValueError
106 If *epsilon* is negative.
107
108 References
109 ----------
110 https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
111
112 Examples
113 --------
114 >>> ramer_douglas_peucker([], epsilon=1.0)
115 []
116 >>> ramer_douglas_peucker([(0.0, 0.0)], epsilon=1.0)
117 [(0.0, 0.0)]
118 >>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.0)], epsilon=1.0)
119 [(0.0, 0.0), (1.0, 0.0)]
120 >>> # middle point is within epsilon - it is discarded
121 >>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.1), (2.0, 0.0)], epsilon=0.5)
122 [(0.0, 0.0), (2.0, 0.0)]
123 >>> # middle point exceeds epsilon - it is kept
124 >>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)], epsilon=0.5)
125 [(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)]
126 >>> ramer_douglas_peucker([(0.0, 0.0), (1.0, 0.5), (2.0, 0.0)], epsilon=-1.0)
127 Traceback (most recent call last):
128 ...
129 ValueError: epsilon must be non-negative, got -1.0
130 """
131 if epsilon < 0:
132 msg = f"epsilon must be non-negative, got {epsilon!r}"
133 raise ValueError(msg)
134
135 if len(pts) < 3:
136 return list(pts)

Callers

nothing calls this directly

Calls 3

_perpendicular_distanceFunction · 0.85
popMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected