问题
Given is a path described by an ordered array of points (x,y). I'm looking for an algorithm that describes this path with a given number of points (k) that are evenly spaced along the path.
Input points:
[[x1,y1], ..., [xn,yn]] (randomly spaced)
Where x1,y1 is the first waypoint and xn,yn the last. The path is defined by connecting every point to the next with a straight line.
(Xn,Yn) -----> (Xn+1,Yn+1)
Expected output:
[[x1,y1], ..., [xk,yk]] (evenly spaced)
Image of an example path
Update: I've looked at Ramer-Douglas-Peucker algorithm. It will reduce the number of points but it won't allow to set a fixed number of points and they are not evenly spaced.
回答1:
Usually when you have a list of points to turn into a path, you want to make the path to have some smoothness to it. There are techniques to do that, but they make the second part of your problem more difficult to solve.
You mention in a comment that a straight line connecting each input point would be considered acceptable, which leads to an easy solution.
Calculate the distance between consecutive input points. Add up all those distances. Divide the total by the number of output points you desire; this is the output point spacing.
Now go through the list of input points and sum the distance traveled so far. If that distance goes beyond the next output distance you require, use linear interpolation between that point and the previous point to determine the output point.
Note: the output points will be equidistant when measured against the original input path, but they will not necessarily be equal distance from each other. Changing the number of points in this case changes the path.
回答2:
You will have to interpolate the path, as the with the initial discrete input you will not be able to solve the problem. That is you will need to "guess" how the path will go between the input points. This guess(called interpolation) may not be accurate, but your task is to get as close to the real path as possible. There are many ways in which you can do that for instance you can use splines or some polynomial interpolation.
Once you've done that you will have a continuous path - that is a path that can be described with f(x) where x goes from 0 to the length of the path and f(x) returns a point in the plane. With this function, the points you are interested in will be f((i * L) / M)
. Here L
is the length of the path, M
is the number of evenly spaced points you are interested in and i goes through the values 0,1,2,...M-1
.
来源:https://stackoverflow.com/questions/24907476/how-to-get-a-fixed-number-of-evenly-spaced-points-describing-a-path