95

Given two polygons:

POLYGON((1 0, 1 8, 6 4, 1 0))
POLYGON((4 1, 3 5, 4 9, 9 5, 4 1),(4 5, 5 7, 6 7, 4 4, 4 5))

How can I calculate the union (combined polygon)?

enter image description here

Dave's example uses SQL server to produce the union, but I need to accomplish the same in code. I'm looking for a mathematical formula or code example in any language that exposes the actual math. I am attempting to produce maps that combine countries dynamically into regions. I asked a related question here: Grouping geographical shapes

Rob
  • 26,989
  • 16
  • 82
  • 98
grenade
  • 31,451
  • 23
  • 97
  • 126

10 Answers10

79

This is a very good question. I implemented the same algorithm on c# some time ago. The Algorithm constructs a common contour of two polygons (i.e. Constructs a union without holes). Here it is.


Goal

Step 1. Create graph that describes the polygons.

Input: first polygon (n points), second polygon (m points). Output: graph. Vertex - polygon point of intersection point.

We should find intersections. Iterate through all polygon sides in both polygons [O(n*m)] and find any intersections.

  • If an intersection is not found, simply add vertices and connect them to the edge.

  • If any intersections are found, sort them by length to their start point, add all vertexes (start, end and intersections) and connect them (already in sorted order) to the edge. Graph

Step 2. Check constructed graph

If we did not find any intersection points when graph was built, we have one of the following conditions:

  1. Polygon1 contains polygon2 - return polygon1
  2. Polygon2 contains polygon1 - return polygon2
  3. Polygon1 and polygon2 do not intersect. Return polygon1 AND polygon2.

Step 3. Find left-bottom vertex.

Find the minimum x and y coordinates (minx, miny). Then find the minimum distance between (minx, miny) and the polygon's points. This point will be the left-bottom point.

Left-bottom point

Step 4. Construct common contour.

We start to traverse the graph from the left-bottom point and continue until we get back into it. At the beginning we mark all edges as unvisited. On every iteration you should select the next point and mark it as visited.

To choose the next point, choose an edge with a maximum internal angle in counter-clockwise direction.

I calculate two vectors: vector1 for current edge and vector2 for each next unvisited edge (as presented in the picture).

For vectors I calculate:

  1. Scalar product (dot product). It returns a value related to an angle between vectors.
  2. Vector product (cross product). It returns a new vector. If z-coordinate of this vector is positive, scalar product gives me right angle in counter-clockwise direction. Else (z-coordinate is negative), I calculate get angle between vectors as 360 - angle from scalar product.

As a result I get an edge (and a correspond next vertex) with the maximum angle.

I add to result list each passed vertex. Result list is the union polygon. Vectors

Remarks

  1. This algorithm allows us to merge multiple of polygons - to apply iteratively with polygon's pairs.
  2. If you have a path that consists of many bezier curves and lines, you should flatten this path first.
Peter O.
  • 32,158
  • 14
  • 82
  • 96
xtmq
  • 3,380
  • 22
  • 26
  • 2
    I think it should be mentioned that for comparing the scalar products, the vectors should be normalized before computing their scalar product (i.e., divide the vector coordinates by it's lengths). Anyhow, thanks for this answer. – eyalzba Mar 06 '17 at 10:27
  • Does this algorithm have a name or is your own creation? – Andrés Oviedo Jan 07 '18 at 05:45
  • I read it somewhere, but now I do not remember where and when =) – xtmq Jan 08 '18 at 07:12
  • NOTE: See [polygon union without holes](https://stackoverflow.com/q/6844462/199364), which shows a different diagram: two polygons overlap, BUT there is a "hole" that neither of them cover. As per @xtmq's comment there, this algorithm "fills" that hole (even though it is *not* part of either input polygon). If you instead wish to "retain" those holes as holes, then (a) calculate the holes, and (b) return the "set of holes" [On some graphics systems/modes, these holes can be included in the output polygon set, and will result in holes when drawn.] ... – ToolmakerSteve Jan 08 '18 at 23:20
  • 3
    ... To do "(a) calculate the holes", look for points that are never visited by "Step 4. Construct common contour". Use one of these points to "start" the hole. Do a similar "contour" algorithm, excluding any points already used by the main output polygon. The resulting polygon is a "hole". Repeat until ALL points have been included in some polygon or hole. – ToolmakerSteve Jan 08 '18 at 23:23
  • ... Unfortunately, there is a "borderline" case, where an interior "hole" just "touches" the outside, so there is a point that is both part of the outside, *and* part of the hole. If the hole can't complete itself, re-use a point (that was used elsewhere), then try to continue with unused points. Extremely rarely, you might have to repeat for multiple such points - but keep "favoring" unused points where possible. If you get stuck w/o using some points, discard the remaining points (maybe message to user or log) - don't get stuck in infinite loop. Probably discard that incomplete hole. – ToolmakerSteve Jan 08 '18 at 23:30
  • ... I forgot to mention that in this variation (keeping holes), you must test each point of one polygon to see if is inside the other polygon. If so, throw point away. That is, only form holes out of points that are not inside any other polygon, plus intersection points ("favoring" intersection points that were not on the outside edge that you calculate). I stored *which* points connect to each point - which gets tricky as add "intersection points". Formed edges of holes by linking together already connected points, possibly switching to the "other polygon"s point list at intersections. – ToolmakerSteve Jan 10 '18 at 02:04
  • This looks like the [Weiler-Atherton](https://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm) clipping algorithm unless I am mistaken? – noblemaster Oct 15 '21 at 08:19
15

This is a challenging but well-understood topic, that often goes under the name "regularized Boolean operations on polygons." You might look at this MathOverflow answer, which includes the figure below (from Alan Murta's clipping library), with the pink union the OP's combine:


      BooleanOps
Community
  • 1
  • 1
Joseph O'Rourke
  • 4,346
  • 16
  • 25
6

You need to determine which points lie inside. After removing these points, you can insert one set of "outside" points into the other. Your insertion points (e.g. where you have the arrow in the picture on the right) are where you had to remove points from the input sets.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
3

Good question! I've never attempted this before, but I'll take a crack at it now.

First: You need to know where these two shapes overlap. To do this, you could look at every edge in Polygon A and see where it intersects and edge in Polygon B. In this example, there should be two points of intersection.

Then: Make the union shape. You can take all of the vertices in A and B, and also the points of intersection, and then exclude the vertices that contained by the final shape. To find these points, it looks like you could just find any vertex of A that is inside B, and any vertext of B that is inside A.

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
3

Try gpc.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • That looks promising. I've emailed the authors as their download links are all returning 403's. – grenade Apr 20 '10 at 07:59
  • 1
    The link to the source code works for me: ftp://ftp.cs.man.ac.uk/pub/toby/gpc/gpc232-release.zip – lhf Apr 20 '10 at 11:21
3

I have faced the same problem and I solved the problem by using the following way

Cython wrapper for the C++ translation of the Angus Johnson's Clipper library (ver. 6.4.2) https://github.com/fonttools/pyclipper

pc = pyclipper.Pyclipper()
def get_poly_union(polygons):
    pc.AddPaths(polygons, pyclipper.PT_SUBJECT, True)
    solution = pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO)
    return solution[0]

print_image = image.copy()
solution = get_poly_union(polygons_array) 
#polygons_array=[polygon,polygon,polygon, ...,polygon] and polygon=[point,point,point...,point]

cv2.drawContours(print_image, [np.asarray(solution)], -1, (0, 255, 0), 2)

plt.imshow(print_image)
Rabindra Nath Nandi
  • 1,433
  • 1
  • 15
  • 28
2

A solution I've seen using BSP trees is described here.

Basically, it describes intersection in terms of a union of the edges of polygon A that are inside polygon B (including partial edges, and calculated using a BSP tree). Then, you can define A / B as ~(~A /\ ~B), where ~ denotes reversing the winding of the polygon, / denotes union and /\ denotes intersection.

Kelly Thomas
  • 440
  • 7
  • 17
nornagon
  • 15,393
  • 18
  • 71
  • 85
2

This is very old question but Union_ function from Boost worked for me.

See this snippet below:

#include <iostream>
#include <vector>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include <boost/foreach.hpp>


int main()
{
    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

    polygon green, blue;

    boost::geometry::read_wkt(
        "POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))", green);

    boost::geometry::read_wkt(
        "POLYGON((5 5, 5 15, 15 15, 15 5, 5 5))", blue);

    std::vector<polygon> output;
    boost::geometry::union_(green, blue, output);

    int i = 0;
    std::cout << "green || blue:" << std::endl;
    BOOST_FOREACH(polygon const& p, output)
    {
        std::cout << i++ << ": " << boost::geometry::area(p) << std::endl;

        for (int i = 0; i < p.outer().size(); i++)
        {
            std::cout << p.outer().at(i).x() << " " << p.outer().at(i).y() << std::endl;
        }
    }



    return 0;
}
Yonatan
  • 51
  • 7
  • 1
    Remember to "correct" your polygons if ncessary. See https://stackoverflow.com/questions/22258784/boostgeometryunion-no-result – anumi Oct 30 '19 at 16:54
1

I needed to solve this same problem today and found the solution with this lib: https://en.wikipedia.org/wiki/General_Polygon_Clipper.

It have a lot of language implementations the list here including Java, Obj-C, C#, Lua, python and more.

jevon
  • 3,197
  • 3
  • 32
  • 40
ademar111190
  • 14,215
  • 14
  • 85
  • 114
1

When grouping countries, I'd hope there be no overlap -- you could take a fairly naive algorithm that looks for shared vertices - a simple view would be to iterate through the points on one polygon, see if it's on any of your other polygons, and shares the same next or previous point to see if there is a match. Then just remove the shared vertex to create your union

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
  • 2
    "When grouping countries, I'd hope there be no overlap"... not all countries agree on their own or their neighbours borders, though it would be nice if they did. – FrustratedWithFormsDesigner Apr 19 '10 at 13:40
  • 2
    @FrustratedWithFormsDesigner indeed, but most cartographers will either assign the disputed region to their political ally or as a separate entity in its own right -- that's also why I describe my algorithm as naive... – Rowland Shaw Apr 19 '10 at 14:17