得到两个形状文件的差异

时间:2018-07-05 11:40:38

标签: python shapefile fiona shapely.geometry

我有两个形状文件,其中包含多边形。我正在尝试从中找出差异。 尝试通过以下代码来做到这一点,但不能按我期望的方式工作。 以下是两个形状文件,蓝色是缓冲区形状文件,我需要删除与蓝色缓冲区相交的缓冲区区域。需要获得与 Qgis 差异 函数

相同的几何差异

enter image description here

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

green = fiona.open(
    "/home/gulve/manual_geo_ingestion/probe-data/images/r/shape_out/dissolved.shp")
blue = fiona.open(
    "/home/gulve/manual_geo_ingestion/probe-data/images/g/shape/shape.shp")

print([not shape(i['geometry']).difference(shape(j['geometry'])).is_empty for i, j in zip(list(blue), list(green))])

schema = {'geometry': 'Polygon',
          'properties': {}}
crs = {'init': u'epsg:3857'}

with fiona.open(
        '/home/gulve/manual_geo_ingestion/probe-data/images/r/shape_out/diff.shp', 'w',
        driver='ESRI Shapefile', crs=crs, schema=schema
) as write_shape:
    for geom in [shape(i['geometry']).difference(shape(j['geometry'])) for i, j in zip(list(blue), list(green))]:
        if not geom.empty:
            write_shape.write({'geometry': mapping((shape(geom))), 'properties': {}})

预期输出: enter image description here

2 个答案:

答案 0 :(得分:2)

导入shapefiles into PostgreSQL后,只需执行以下查询即可:

CREATE TABLE not_intersects AS 
SELECT * FROM shape 
WHERE id NOT IN (SELECT DISTINCT shape.id
         FROM buffer,shape 
         WHERE ST_Intersects(buffer.geom,shape.geom)); 

此查询将创建第三个表(在此处称为not_intersects),该表包含两个表(形状文件)之间不相交的多边形。

enter image description here

结果以黄色表示。

答案 1 :(得分:0)

我能够用匀称的功能解决这个问题

这是我的代码。

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

buffered_shape = fiona.open(
    "dissolved.shp", 'r', encoding='UTF-8')
color_shape = fiona.open(
    "shape.shp", 'r', encoding='UTF-8')

print([not shape(i['geometry']).difference(shape(j['geometry'])).is_empty for i, j in
       zip(list(color_shape), list(buffered_shape))])

outmulti = []
for pol in color_shape:
    green = shape(pol['geometry'])
    for pol2 in buffered_shape:
        red = shape(pol2['geometry'])
        if red.intersects(green):
            # If they intersect, create a new polygon that is
            # essentially pol minus the intersection
            intersect = green.intersection(red)
            nonoverlap = green.symmetric_difference(intersect)
            outmulti.append(nonoverlap)
        else:
            outmulti.append(green)

finalpol = unary_union(outmulti)

schema = {'geometry': 'MultiPolygon',
          'properties': {}}
crs = {'init': u'epsg:4326'}

with fiona.open(
        'shape_out/diff.shp', 'w',
        driver='ESRI Shapefile', crs=crs, schema=schema
) as write_shape:
    for geom in finalpol:
        # if not geom.empty:
        write_shape.write({'geometry': mapping(Polygon(shape(geom))), 'properties': {}})