ГИС: объединение мультиполигонов в Python - PullRequest
0 голосов
/ 10 сентября 2018

У меня есть файл геоджона округов на Британских островах, и я пытаюсь заменить отдельные округа Лондона одним объединенным округом, а затем сохранить результат как геоджон.(Округа Лондона могут быть идентифицированы, потому что их атрибут TYPE_2 установлен на London Borough.)

Я думал, что смогу выполнить эту задачу со следующим:

from shapely.geometry import Polygon, MultiPolygon, asShape
from shapely.ops import unary_union
import json, geojson

j = json.load(open('british-isles.geojson'))

# find the london counties
indices = [idx for idx, i in enumerate(j['features']) if \
    i['properties']['TYPE_2'] == 'London Borough']

# transform each london county into a shapely polygon
polygons = [asShape(j['features'][i]['geometry']) for i in indices]

# get the metadata for the first county
properties = j['features'][indices[0]]['properties']
properties['NAME_2'] = 'London'

# get the union of the polygons
joined = unary_union(polygons)

# delete the merged counties
d = j
for i in indices:
  del d['features'][i]

# add the new polygon to the features
feature = geojson.Feature(geometry=joined, properties=properties)
d['features'].append(feature)

# save the geojson
with open('geojson-british-isles-merged-london.geojson', 'w') as out:
  json.dump(d, out)

Однако этонеправильно объединяет лондонские округа - вместо этого получается фрагментированная серия полигонов, где раньше были лондонские округа.

Знают ли другие, как я могу выполнить эту задачу в Python?Любые предложения будут очень полезны!

1 Ответ

0 голосов
/ 11 сентября 2018

Ну, было две проблемы с вышеуказанным. Первый был просто недосмотром: при удалении из d['features'] мне нужно было удалять элементы массива в обратном порядке (удаление индекса 0, затем 1 отличается от удаления 1, затем 0).

Более существенно, что вышеупомянутый геойсон был уже с потерями. Значения координат имели ограниченные десятичные разряды, чтобы сократить размер файла JSON. Но это делает объединение геометрий только приблизительным и приводит к небольшим промежуткам между объединенными многоугольниками:

enter image description here

Итак, мой рабочий процесс заключался в том, чтобы получить файл topojson с высоким разрешением , преобразовать его в geojson, объединить геометрию с помощью приведенного ниже кода, затем ограничить десятичную точность (при необходимости) .

from shapely.geometry import Polygon, MultiPolygon, asShape
from shapely.ops import unary_union, cascaded_union
from geojson import Feature
import json

j = json.load(open('GBR_adm2.json'))

# find the london counties
indices = [idx for idx, i in enumerate(j['features']) if \
    'London Borough' in i['properties']['TYPE_2']]

# transform each london county into a shapely polygon
polygons = [asShape(j['features'][i]['geometry']) for i in indices]

# get the metadata for the first county
properties = j['features'][indices[0]]['properties']
properties['NAME_2'] = 'London'

# get the union of the polygons
joined = unary_union(polygons)

# delete the merged counties
d = j
for i in reversed(sorted(indices)):
  del d['features'][i]

# add the new polygon to the features
feature = Feature(geometry=joined, properties=properties)
d['features'].append(feature)

# save the geojson
with open('british-isles-merged-london.geojson', 'w') as out:
  json.dump(d, out)

Результат: enter image description here

...