셰이프 파일의 기하학 차이

Aug 21 2020

하나의 shapefile의 일부로 외곽선 영역의 지오메트리가 있습니다 (단지 하나의 기능이며 이것과는 다른 다른 기능이 있습니다). 색상이 지정된 다른 다각형 영역의 경계는 다른 shapefile에 있습니다.

이미지의 색상이 지정되지 않은 영역 (모두 하나의 다각형 또는 여러 다각형)의 형상을 찾는 방법이 있습니까?

아래 코드로 시도했지만 전체 지역의 지오메트리를 제공했습니다.

from shapely.geometry import shape, mapping, Polygon
import matplotlib.pyplot as plt
import geopandas as gpd
import fiona

schema = {'geometry': 'Polygon','properties': {'test': 'float'}}

outline_shape = fiona.open(shapefile1)
region_shape = fiona.open(shapefile2)

for feature in outline_shape:
    if feature['properties']['Name'] == 'Required field':
        schema = {'geometry': 'Polygon', 'properties': {'test': 'int'}}
        with fiona.open('diff.shp', 'w', 'ESRI Shapefile', schema) as e:
            for geom in [shape(feature['geometry']).difference(shape(j['geometry'])) for j in region_shape]:
                if not geom.is_empty:
                    e.write({'geometry': mapping(geom), 'properties': {'test': 1}})

답변

1 bugmenot123 Aug 22 2020 at 23:45

이것은 완전히 테스트되지 않았지만 트릭을 수행해야합니다.

아이디어는 실제로 면적 차이를 계산할 수 있도록 윤곽선에서 다각형을 만드는 것입니다. 지역의 경우 단일 지오메트리를 만들었으므로 코드가 차이를 반복해서 다시 계산할 필요가 없으므로 더 빠를 것입니다.

또한 파일 처리를 with컨텍스트 와 함께 모범 사례로 변경했습니다 . 그리고 오해를 잡기 위해 몇 가지 주장을 추가했습니다.

import fiona
from shapely.geometry import shape, mapping, Polygon
from shapely.ops import unary_union


# load all regions and make a single geometry of them
with fiona.open(regions_file) as regions:
    regions_geometries = [shape(f["geometry"]) for f in regions]
    regions_geometry = unary_union(regions_geometries)

# load the wanted outline
# via https://gis.stackexchange.com/questions/91676/select-by-attributes-within-the-fiona-python-module
with fiona.open(outlines_file) as outlines:
    filtered = filter(lambda f: f["properties"]["Name"] == "Required field", outlines)
    assert len(filtered) == 1, "more than 1 match?"
    outline = filtered[0]

outline_geometry = shape(outline["geometry"])

# assuming you actually have an outLINE (as LineString)
outline_geometry = Polygon(outline_geometry)

# compute the difference
difference_geometry = outline_geometry.difference(regions_geometry)
assert not difference_geometry.is_empty, "no remaining difference geometry?"

# ready to write to output
schema = {"geometry": "Polygon", "properties": {"test": "int"}}

difference_feature = {
    "geometry": mapping(difference_geometry),
    "properties": {"test": 1},
}

with fiona.open("diff.shp", "w", "ESRI Shapefile", schema) as output:
    output.write(difference_feature)

출력에 대한 CRS가 누락되었을 수 있지만 그것은 당신에게 달려 있습니다 :)