地理空间-Java实现航迹稀释
Java实现航迹点稀释算法(Douglas - Peucker算法)的示例代码,该算法可在保证航迹整体形状变化不大的情况下减少航迹点数量:
import java.util.ArrayList;
import java.util.List;
class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
public class TrackThinning {
public static List<Point> douglasPeucker(List<Point> points, double epsilon) {
if (points.size() < 3) {
return points;
}
int index = -1;
double dmax = 0;
int end = points.size();
for (int i = 1; i < end - 1; i++) {
double d = perpendicularDistance(points.get(i), points.get(0), points.get(end - 1));
if (d > dmax) {
index = i;
dmax = d;
}
}
List<Point> result = new ArrayList<>();
if (dmax > epsilon) {
List<Point> recursiveResult1 = douglasPeucker(points.subList(0, index + 1), epsilon);
List<Point> recursiveResult2 = douglasPeucker(points.subList(index, points.size()), epsilon);
result.addAll(recursiveResult1.subList(0, recursiveResult1.size() - 1));
result.addAll(recursiveResult2);
} else {
result.add(points.get(0));
result.add(points.get(points.size() - 1));
}
return result;
}
private static double perpendicularDistance(Point point, Point start, Point end) {
double dx = end.x - start.x;
double dy = end.y - start.y;
double numerator = Math.abs((dy * point.x - dx * point.y) + (end.x * start.y - end.y * start.x));
double denominator = Math.sqrt(dy * dy + dx * dx);
return numerator / denominator;
}
public static void main(String[] args) {
List<Point> points = new ArrayList<>();
points.add(new Point(0, 0));
points.add(new Point(1, 1));
points.add(new Point(2, 2));
points.add(new Point(3, 2));
points.add(new Point(4, 3));
points.add(new Point(5, 4));
double epsilon = 0.5;
List<Point> thinnedPoints = douglasPeucker(points, epsilon);
for (Point p : thinnedPoints) {
System.out.println("(" + p.x + ", " + p.y + ")");
}
}
}