파이썬에서 여러 다각형의 교차로를 효율적으로 얻기


12

여러 다각형의 교차점을 얻고 싶습니다. 파이썬 shapely패키지를 사용하면 intersection함수를 사용하여 두 다각형의 교차점을 찾을 수 있습니다 . 여러 다각형의 교집합을 얻는 비슷한 효율적인 기능이 있습니까?

다음은 내가 의미하는 바를 이해하는 코드 스 니펫입니다.

from shapely.geometry import Point

coord1 = ( 0,0 )
point1 = Point(coord1)
circle1 = point1.buffer(1)

coord2 = ( 1,1 )
point2 = Point(coord2)
circle2 = point2.buffer(1)

coord3 = ( 1,0 )
point3 = Point(coord3)
circle3 = point3.buffer(1) 

두 서클의 교차점은에서 찾을 수 있습니다 circle1.intersection(circle2). 로 세 서클의 교차점을 모두 찾을 수 있습니다 circle1.intersection(circle2).intersection(circle3). 그러나이 방법은 점점 더 많은 코드가 필요하기 때문에 많은 수의 다각형에 적용 할 수 없습니다. 임의의 수의 다각형을 가져 와서 그 교차점을 반환하는 함수를 원합니다.


im 생각은 좌표를 사전에 저장하고 itertools 가져 오기 조합에서 사용하면서 반복합니다. 곧 게시하겠습니다
— ziggy

"그들의 교차점"은 무엇을 의미합니까? 하나 이상의 다른 다각형과 교차 하는 모든 영역 또는 모든 입력이 교차 하는 영역을 의미 합니까?
— jpmc26

나는 적어도 하나가 아닌 모든 다각형의 교차점을 의미합니다.
— splinter

위의 내용을 명확히해야합니다 (아마도 출력 예). 나는 대부분의 답변 이 원하는대로 작동 하지 않는다는 것을 확신 합니다. (그리고 몇몇 답변자들이 오해 한 사실은 그 질문이 명확
— 해져야

1
@ jpmc26 방금 rtree가 사용되는 답변에 업데이트를 추가했습니다. 이 접근 방식은 이제 더 효율적이고 확장 가능합니다. 도움이 되었기를 바랍니다!
— Antonio Falciano

답변:


7

하나의 가능한 접근법은 다각형 쌍, 그 교차점 및 마지막으로 계단식 유니온을 통해 모든 교차점의 조합을 고려하는 것입니다 ( 여기서 제안 됨 ).

from shapely.geometry import Point
from shapely.ops import cascaded_union
from itertools import combinations

circles = [
    Point(0,0).buffer(1),
    Point(1,0).buffer(1),
    Point(1,1).buffer(1),
]

intersection = cascaded_union(
    [a.intersection(b) for a, b in combinations(circles, 2)]
)
print intersection

보다 효율적인 접근법은 많은 기하학을 처리하기 위해 Rtree 와 같은 공간 인덱스를 사용해야합니다 (세 개의 원이 아닌 경우).

from shapely.geometry import Point
from shapely.ops import cascaded_union
from rtree import index

circles = [
    Point(0,0).buffer(1),
    Point(1,0).buffer(1),
    Point(1,1).buffer(1),
]
intersections = []
idx = index.Index()

for pos, circle in enumerate(circles):
    idx.insert(pos, circle.bounds)

for circle in circles:
    merged_circles = cascaded_union([circles[pos] for pos in idx.intersection(circle.bounds) if circles[pos] != circle])
    intersections.append(circle.intersection(merged_circles))

intersection = cascaded_union(intersections)
print intersection

나는 이것이 OP가 원하는 것을하지 않는다고 생각합니다. OP는 두 세트의 모든 다각형이 포함 된 영역 만 찾는 반면 최소 2 개의 다각형이 포함 하는 영역을 반환합니다 . 주석에서 설명을 참조하십시오.
— jpmc26

3

반복 또는 재귀를 사용하지 않는 이유는 무엇입니까? 같은 :

from shapely.geometry import Point

def intersection(circle1, circle2):
    return circle1.intersection(circle2)

coord1 = ( 0,0 )
point1 = Point(coord1)
circle1 = point1.buffer(1)

coord2 = ( 1,1 )
point2 = Point(coord2)    
circle2 = point2.buffer(1)


coord3 = ( 1,0 )
point3 = Point(coord3)
circle3 = point3.buffer(1)
circles = [circle1, circle2, circle3]
intersectionResult = None

for j, circle  in enumerate(circles[:-1]):

    #first loop is 0 & 1
    if j == 0:
        circleA = circle
        circleB = circles[j+1]
     #use the result if the intersection
    else:
        circleA = intersectionResult
        circleB = circles[j+1]
    intersectionResult = intersection(circleA, circleB)

result= intersectionResult

2

이 코드에 샷을 제공하십시오. 그것의 개념은 매우 간단하고 나는 당신이 찾고있는 것을 얻습니다.

from shapely.geometry import Point
from itertools import combinations
dic ={}
dic['coord1']=Point(0,0).buffer(1)
dic['coord2']=Point(1,1).buffer(1)
dic['coord3']=Point(1,0).buffer(1)
inter = {k[0]+v[0]:k[1].intersection(v[1]) for k,v in combinations(dic.items(),2)}
print inter

그리고 출력을 shapefile로 저장하려면 fiona를 사용하십시오.

from shapely.geometry import Point,mapping
import fiona
from itertools import combinations
schema = {'geometry': 'Polygon', 'properties': {'Place': 'str'}}
dic ={}
dic['coord1']=Point(0,0).buffer(1)
dic['coord2']=Point(1,1).buffer(1)
dic['coord3']=Point(1,0).buffer(1)
inter = {k[0]+v[0]:k[1].intersection(v[1]) for k,v in combinations(dic.items(),2)}
print inter
with fiona.open(r'C:\path\abid', "w", "ESRI Shapefile", schema) as output:
    for x,y in inter.items():
        output.write({'properties':{'Place':x},'geometry':mapping(y)})

이 출력-

여기에 이미지 설명을 입력하십시오


3
나는 이것이 OP가 원하는 것을하지 않는다고 생각합니다. OP는 두 세트의 모든 다각형이 포함 된 영역 만 찾는 반면 최소 2 개의 다각형이 포함 하는 영역을 반환합니다 . 주석에서 설명을 참조하십시오. 또한, 및 당신의 변수 이름에 대한 빈약 한 선택이다 함축는. 이러한 변수는 각각 키-값 쌍이 아닌의 다른 요소를 나타 냅니다. 같은 뭔가 덜 오해의 소지가 될 것이다. kvdictdic.items()a, b
— jpmc26

1
오 그래 알았어 난 그가 무슨 뜻인지 이해하지 못했다
— ziggy

및 지점을 잘 내 K, V 선택에 대한 찍은 - 난 그냥 자동으로 K를 사용, V dictionary..didnt 통해 반복 그것에게 많은 생각 제공
— ziggy에서
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.