【问题标题】:Merging two polygons in Java在Java中合并两个多边形
【发布时间】:2012-07-02 08:47:45
【问题描述】:

有没有一种干净的 Java 方法可以将两个给定的重叠多边形的点合并为一个多边形?

【问题讨论】:

  • 如何合并?你尝试了什么?
  • 你的数据结构是什么样的?
  • 合并点,我尝试逐个遍历点,并检查相交。但在超过 1000 个点的多边形上运行是一项极其繁重的任务。
  • @BenPoulson - 我还是不明白。例如如果你有两个并排的正方形,中间有一些空间,你会如何合并它们?相反,如果它们共享一条边,那么您将如何合并它们?
  • 这个Q&A 检查合并多个三角形;我不知道它是如何扩展的。

标签: java polygons


【解决方案1】:

您想要的是Convex Hull Algorithm,它将采用一组点并返回包含原始点的最小点集。这可以在n.log n 时间完成。

【讨论】:

  • 经过仔细检查,凸包算法是执行此操作的正确方法。非常感谢。
【解决方案2】:

Area 类支持添加闭合多边形。

【讨论】:

  • 对此表示赞同。组合多边形意味着您必须具有边缘感知能力,而凸包算法通常只查看点。如果您查看Area.add() javadoc,凸包算法只会生成一个矩形。
【解决方案3】:

凸包不同于添加。添加意味着制作一个看起来像两个多边形重叠的多边形,不一定是凸的。

【讨论】:

    【解决方案4】:

    您可以为此使用JTS(Java 拓扑套件)。

    • 创建您的多边形对象
    • 使用 union 方法,该方法将返回一个包含两个多边形的所有点的集合

    简单代码示例:

    • 给定多边形 1(作为 WKT):POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))
    • 给定多边形 2(作为 WKT):POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))

      // create polygons
      Polygon p1 = new GeometryFactory().createPolygon(new Coordinate[]{new Coordinate(0, 0), new Coordinate(0,10), new Coordinate(10,10), new Coordinate(10,0), new Coordinate(0,0)});
      Polygon p2 = new GeometryFactory().createPolygon(new Coordinate[]{new Coordinate(5,5), new Coordinate(15,5), new Coordinate(15,15), new Coordinate(5,15), new Coordinate(5,5)});
      // calculate union
      Geometry union = p1.union(p2);
      // print as WKT
      System.out.println(union.toText());
      

    结果是一个新的多边形:

    POLYGON ((0 0, 0 10, 5 10, 5 15, 15 15, 15 5, 10 5, 10 0, 0 0))
    

    【讨论】:

    • 感谢您的回答!不幸的是,在使用这种方法组合多边形时,如果您以圆形方式放置多边形,JTS 真的不喜欢这样并且不会正确地覆盖/合并它们。不过,我不确定我是不是做错了什么。
    【解决方案5】:

    使用@Charles Keepax 提供的算法,您可以执行以下操作:

    public static Polygon mergePolygons(Polygon a, Polygon b) {
        // create arrays for border of each polygon
        Point[] a_pts = new Point[a.npoints];
        Point[] b_pts = new Point[b.npoints];
        // fill them in an array of Points instead of separate coords.
        Arrays.setAll(a_pts, i -> new Point(a.xpoints[i], a.ypoints[i]));
        Arrays.setAll(b_pts, i -> new Point(b.xpoints[i], b.ypoints[i]));
        // first merge 2 arrays into 1
        Point[] all_pts = (Point[]) mergeArrays(a_pts, b_pts);
        // apply Convex Hull on resulting array
        convexHull(all_pts, all_pts.length);
    
        // separate x and y coordinates back 
        int[] x_pts = new int[all_pts.length];
        int[] y_pts = new int[all_pts.length];
        Arrays.setAll(x_pts, i -> all_pts[i].x);
        Arrays.setAll(y_pts, i -> all_pts[i].y);
        // return polygon object using those coordinates
        return new Polygon(x_pts, y_pts, all_pts.length);
    }
    

    但是@Lars 的解决方案当然更实用,这就是你可以用幼稚的方式做到这一点的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 2021-06-18
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2014-05-13
      相关资源
      最近更新 更多