Комбинирайте близките многоъгълници

Имам двойка (затворени) полигони, всеки дефиниран като поредица от точки (върховете). Всеки от полигоните представлява парцел земя, разделен от малка река, така че потокът образува тясна пролука между двата полигона.

Търся алгоритъм за идентифициране и премахване на празнината, като съединя двата многоъгълника в един свързан многоъгълник.

Фигурата по-долу показва пример, където оригиналните полигони са зелено и червено, а полученият полигон е показан в жълто.

пример

Досега успях да направя следното:

  • За всеки ръб в многоъгълник-A намерете най-близкия връх в многоъгълник-B.
  • Намерете всички върхове на многоъгълник-B, които са на определено разстояние от многоъгълник-A.

Но не съм много сигурен какво трябва да направя сега.


person brianmearns    schedule 04.09.2013    source източник
comment
Трябва по-сложен пример. Например, представете си, че плъзгате жълтия блок срещу червения, така че да имате два крака срещу една повърхност. Това присъединява ли се? Или само ако е тясна връзка по целия път? Ако се съедини, остава ли ви цяло в средата или едно голямо съединено парче?   -  person user1676075    schedule 04.09.2013
comment
@user1676075: Предполагам, че трябва да има някаква спецификация на някои прагове. Например, дори на фигурата по-горе, жълтото е само един възможен резултат от присъединяването им. При по-строги прагове северното устие на реката може да е твърде широко и така съединението там ще бъде по-на юг, което води до вдлъбнатина в получения многоъгълник.   -  person brianmearns    schedule 04.09.2013
comment
Можете да шиете върховете   -  person Khaled.K    schedule 05.09.2013


Отговори (5)


Може да разгледате модификация на алгоритъм с изпъкнала обвивка. Алгоритъмът за изпъкнала обвивка взема набор от точки и чертае минималната изпъкнала форма, съдържаща тези точки. Вашият въпрос е почти въпрос на изпъкнала обвивка, с изключение на онези вдлъбнати области в горната част. Просто използването на алгоритъм за изпъкнала обвивка ще ви даде това, което е близо, но не е точно това, от което се нуждаете (обърнете внимание на кафявите области, които са различни)

Изпъкнал корпус

В зависимост от това, което се опитвате да направите, изпъкналата обвивка може да е „достатъчно добра“, но ако не, все пак може да сте в състояние да модифицирате алгоритъм, за да игнорирате частите, които не са изпъкнали, и просто да обедините двата многоъгълника.

По-конкретно този pdf показва как две изпъкнали обвивки могат да бъдат обединени, което много прилича на това, което се опитвате да направите.

person Retsam    schedule 04.09.2013
comment
Благодаря за идеята. Обмислях да използвам изпъкнала обвивка, но някои от формите, с които работя, са толкова силно вдлъбнати, че изпъкналата обвивка би била далеч. Но може би мога да използвам CH алгоритъм като отправна точка, както предлагате. - person brianmearns; 04.09.2013
comment
Да; по-конкретно, бих казал, че разгледайте алгоритъма за сливане или разделяне и владеене, тъй като той специално се занимава с комбинирането на съществуващи корпуси.] - person Retsam; 04.09.2013
comment
@sh1ftst0rm Ще получите жълтата област, ако вземете изпъкналата обвивка и замените ръбовете, свързващи върховете от същия многоъгълник с последователността от ръбове в оригинала. Не съм сигурен кои са всички ъглови случаи на този подход. - person David Eisenstat; 04.09.2013
comment
@DavidEisenstat: Това е наистина интересна идея, ще я разгледам. Благодаря! - person brianmearns; 04.09.2013
comment
@sh1ftst0rm По-точно, вземете безкрайното лице на равнинна праволинейна графика, образувана от двата полигона и техните две критични линии за поддръжка. - person David Eisenstat; 04.09.2013
comment
@DavidEisenstat: Вашата идея за замяна на CH ръбове, които свързват върхове от един и същ многоъгълник, работи много добре. Ако искате да публикувате това като отговор, ще се радвам да го гласувате. - person brianmearns; 05.09.2013
comment
Помислете също за алфа корпуси и свързани форми. (en.wikipedia.org/wiki/Alpha_shape) Дори и да не ви трябват, за тях е забавно да се мисли и може да са ви полезни в бъдеще. (Това е много стара публикация, но хей, в момента е високо в списъка с въпроси по изчислителна геометрия.) - person Rethunk; 30.04.2021

Само за пълнота исках да споделя моето решение като реализация на Python. Това се основава на приетия отговор от Retsam и идеята, представена от David Eisenstat в коментарите към този отговор, която е да се заменят ръбовете на изпъкналата обвивка, които се свързват с върховете на същия оригинален многоъгълник, с междинните върхове от този многоъгълник .

def joinPolygons(polya, polyb):
    """
    Generate and return a single connected polygon which includes the two given
    polygons. The connection between the two polygons is based on the convex hull
    of the composite polygon. All polygons are sequences of two-tuples giving the
    vertices of the polygon as (x, y), in order. That means vertices that are adjacent
    in the sequence are adjacent in the polygon (connected by an edge). The first and
    last vertices in the sequence are also connected by any edge (implicitly closed, do
    not duplicate the first point at the end of the sequence to close it).

    Only simple polygons are supported (no self-intersection).
    """

    #Just to make it easier to identify and access by index.
    polygons = [polya, polyb]

    #Create a single list of points to create the convex hull for (each
    # point is a vertex of one of the polygons).
    #Additionally, each point includes some additional "cargo", indicating which
    # polygon it's from, and it's index into that polygon
    # This assumes the implementation of convexHull simply ignores everything
    # beyond the first two elements of each vertex.
    composite = []
    for i in range(len(polygons)):
        points = polygons[i]
        composite += [(points[j][0], points[j][1], j, i) for j in xrange(len(points))]

    #Get the convex hull of the two polygons together.
    ch = convexHull(composite)

    #Now we're going to walk along the convex hull and find edges that connect two vertices
    # from the same source polygon. We then replace that edge with all the intervening edges
    # from that source polygon.

    #Start with the first vertex in the CH.
    x, y, last_vnum, last_pnum = ch[0]

    #Here is where we will collect the vertices for our resulting polygon, starting with the
    # first vertex on the CH (all the vertices on the CH will end up in the result, plus some
    # additional vertices from the original polygons).
    results = [(x, y)]

    #The vertices of the convex hull will always walk in a particular direction around each
    # polygon (i.e., forwards in the sequence of vertices, or backwards). We will use this
    # to keep track of which way they go.
    directions = [None for poly in polygons]

    #Iterate over all the remaining points in the CH, and then back to the first point to
    # close it.
    for x, y, vnum, pnum in list(ch[1:]) + [ch[0]]:

        #If this vertex came from the same original polygon as the last one, we need to
        # replace the edge between them with all the intervening edges from that polygon.
        if pnum == last_pnum:

            #Number of vertices in the polygon
            vcount = len(polygons[pnum])

            #If an edge of the convex hull connects the first and last vertex of the polygon,
            # then the CH edge must also be an edge of the polygon, because the two vertices are
            # adjacent in the original polygon. Therefore, if the convex
            # hull goes from the first vertex to the last in a single edge, then it's walking
            # backwards around the polygon. Likewise, if it goes from the last to the first in 
            # a single edge, it's walking forwards.
            if directions[pnum] is None:
                if last_vnum < vnum:
                    if last_vnum == 0 and vnum == vcount - 1:
                        direction = -1
                    else:
                        direction = 1
                else:
                    if last_vnum == vcount - 1 and vnum == 0:
                        direction = 1
                    else:
                        direction = -1
                directions[pnum] = direction
            else:
                direction = directions[pnum]

            #Now walk from the previous vertex to the current one on the source
            # polygon, and add all the intevening vertices (as well as the current one
            # from the CH) onto the result.
            v = last_vnum
            while v != vnum:
                v += direction
                if v >= vcount:
                    v = 0
                elif v == -1:
                    v = vcount - 1
                results.append(polygons[pnum][v])

        #This vertex on the CH is from a different polygon originally than the previous
        # vertex, so we just leave them connected.
        else:
            results.append((x, y))

        #Remember this vertex for next time.
        last_vnum = vnum
        last_pnum = pnum

    return results



def convexHull(points, leftMostVert=None):
    """
    Returns a new polygon which is the convex hull of the given polygon.

    :param: leftMostVert    The index into points of the left most vertex in the polygon.
                            If you don't know what it is, pass None and we will figure it
                            out ourselves.
    """
    point_count = len(points)

    #This is implemented using the simple Jarvis march "gift wrapping" algorithm.
    # Generically, to find the next point on the convex hull, we find the point
    # which has the smallest clockwise-angle from the previous edge, around the
    # last point. We start with the left-most point and a virtual vertical edge
    # leading to it.

    #If the left-most vertex wasn't specified, find it ourselves.
    if leftMostVert is None:
        minx = points[0][0]
        leftMostVert = 0
        for i in xrange(1, point_count):
            x = points[i][0]
            if x < minx:
                minx = x
                leftMostVert = i

    #This is where we will build up the vertices we want to include in the hull.
    # They are stored as indices into the sequence `points`.
    sel_verts = [leftMostVert]

    #This is information we need about the "last point" and "last edge" in order to find
    # the next point. We start with the left-most point and a pretend vertical edge.

    #The index into `points` of the last point.
    sidx = leftMostVert

    #The actual coordinates (x,y) of the last point.
    spt = points[sidx]

    #The vector of the previous edge.
    # Vectors are joined tail to tail to measure angle, so it
    # starts at the last point and points towards the previous point.
    last_vect = (0, -1, 0)
    last_mag = 1.0

    #Constant
    twopi = 2.0*math.pi

    #A range object to iterate over the vertex numbers.
    vert_nums = range(point_count)

    #A list of indices of points which have been determined to be colinear with
    # another point and a selected vertex on the CH, and which are not endpoints
    # of the line segment. These points are necessarily not vertices of the convex
    # hull: at best they are internal to one of its edges.
    colinear = []

    #Keep going till we come back around to the first (left-most) point.
    while True:
        #Try all other end points, find the one with the smallest CW angle.
        min_angle = None
        for i in vert_nums:

            #Skip the following points:
            # -The last vertex (sidx)
            # -The second to last vertex (sel_verts[-2]), that would just backtrack along
            #  the edge we just created.
            # -Any points which are determined to be colinear and internal (indices in `colinear`).
            if i == sidx or (len(sel_verts) > 1 and i == sel_verts[-2]) or i in colinear:
                continue

            #The point to test (x,y)
            pt = points[i]

            #vector from current point to test point.
            vect = (pt[0] - spt[0], pt[1] - spt[1], 0)
            mag = math.sqrt(vect[0]*vect[0] + vect[1]*vect[1])

            #Now find clockwise angle between the two vectors. Start by
            # finding the smallest angle between them, using the dot product.
            # Then use cross product and right-hand rule to determine if that
            # angle is clockwise or counter-clockwise, and adjust accordingly.

            #dot product of the two vectors.
            dp = last_vect[0]*vect[0] + last_vect[1]*vect[1]
            cos_theta = dp / (last_mag * mag)

            #Ensure fp erros don't become domain errors.
            if cos_theta > 1.0:
                cos_theta = 1.0
            elif cos_theta < -1.0:
                cos_theta = -1.0

            #Smaller of the two angles between them.
            theta = math.acos(cos_theta)

            #Take cross product of last vector by test vector.
            # Except we know that Z components in both input vectors are 0,
            # So the X and Y components of the resulting vector will be 0. Plus,
            # we only care aboue the Z component of the result.
            cpz = last_vect[0]*vect[1] - last_vect[1]*vect[0]

            #Assume initially that angle between the vectors is clock-wise.
            cwangle = theta
            #If the cross product points up out of the plane (positive Z),
            # then the angle is actually counter-clockwise.
            if cpz > 0:
                cwangle = twopi - theta

            #If this point has a smaller angle than the others we've considered,
            # choose it as the new candidate.
            if min_angle is None or cwangle < min_angle:
                min_angle = cwangle
                next_vert = i
                next_mvect = vect
                next_mag = mag
                next_pt = pt

            #If the angles are the same, then they are colinear with the last vertex. We want
            # to pick the one which is furthest from the vertex, and put all other colinear points
            # into the list so we can skip them in the future (this isn't just an optimization, it
            # appears to be necessary, otherwise we will pick one of the other colinear points as
            # the next vertex, which is incorrect).
            #Note: This is fine even if this turns out to be the next edge of the CH (i.e., we find
            # a point with a smaller angle): any point with is internal-colinear will not be a vertex
            # of the CH.
            elif cwangle == min_angle:
                if mag > next_mag:
                    #This one is further from the last vertex, so keep it as the candidate, and put the
                    # other colinear point in the list.
                    colinear.append(next_vert)
                    min_angle = cwangle
                    next_vert = i
                    next_mvect = vect
                    next_mag = mag
                    next_pt = pt
                else:
                    #This one is closer to the last vertex than the current candidate, so just keep that
                    # as the candidate, and put this in the list.
                    colinear.append(i)

        #We've found the next vertex on the CH.
        # If it's the first vertex again, then we're done.
        if next_vert == leftMostVert:
            break
        else:
            #Otherwise, add it to the list of vertices, and mark it as the
            # last vertex.
            sel_verts.append(next_vert)
            sidx = next_vert
            spt = next_pt
            last_vect = (-next_mvect[0], -next_mvect[1])
            last_mag = next_mag

    #Now we have a list of vertices into points, but we really want a list of points, so
    # create that and return it.
    return tuple(points[i] for i in sel_verts)
person brianmearns    schedule 06.09.2013

Може да опитате морфологични операции. По-конкретно, можете да опитате дилатация, последвана от ерозия (известна също като морфологично "затваряне"). Разширението с n пиксела - където n е по-голямо от ширината на реката - ще комбинира формите. След това последваща ерозия би отменила голяма част от щетите, нанесени на останалата част от фигурата. Не би било перфектно (то ще идеално съчетава двете форми, но за сметка на известно омекотяване на останалата част от формата), но може би с резултата от цялата операция бихте могли да разберете намерете начин да го коригирате.

Обикновено тези морфологични операции се извършват върху растерни изображения, а не върху полигони. Но изпълнението на простите операции в ъглите на многоъгълниците може да работи.

person JoshG79    schedule 04.09.2013
comment
Това е интересна идея, но мисля, че ще бъде твърде загуба за моите цели. Но винаги се радвам да науча нещо ново. - person brianmearns; 05.09.2013

С Boost.Geometry можете да извикате buffer с положително разстояние boost::geometry::strategy::buffer::distance_symmetric<double>{r}, достатъчно голямо, за да преодолеете празнината между зелени и червени полигони, последвано от извикване на buffer с boost::geometry::strategy::buffer::distance_symmetric<double>{-r}. Ако второто извикване произведе артефакти, добавете много малко число към r, напр. boost::geometry::strategy::buffer::distance_symmetric<double>{-r+0.001}

person Paul Jurczak    schedule 09.01.2020
comment
Как да намерим стойността на r в това, ако трябва да автоматизираме този процес? - person Jerin Mathew; 18.06.2021

Това е груб, мащабируем подход.

  1. Квантузирайте вашето пространство до решетка с клетки с размер Z-by-Z и наименувайте всяка клетка нейните индекси (i,j).
  2. За всеки полигон P, за всеки връх V, идентифицирайте (P,V) с клетката (i,j), която го съдържа.
  3. За всяка клетка (i,j) разгледайте набора от двойки многоъгълници-върхове (P_k,V_k), k = 1...K, които са идентифицирани с нея. Обединете върховете V_a и V_b на полигоните P_a и P_b, ако и само ако P_a и P_b не са един и същ многоъгълник и V_a и V_b са най-близките сред тези двойки. Повтаряйте сливането на върхове, докато няма повече за сливане. Обединените върхове получават средната стойност на позициите на изходните върхове.
person Timothy Shields    schedule 04.09.2013