3

I have a points shapefile and I want to compute the convex hull of the points using shapely, and output the result as a shapefile using Fiona.

Does anyone know how I can do that?

This is what I have tried:

from shapely.geometry import MultiPoint
from fiona.crs import from_epsg
shape = fiona.open('.cache/town_points/ny_points.shp')
with fiona.open('.cache/mew.shp', 'w', 'ESRI Shapefile', shape.schema.copy(), shape.crs) as output:
    for feat in shape:
        ch_area = MultiPoint(shape).convex_hull
        output.write(feat)
0
7

To transform the shapefile geometries to shapely geometries (you can't build a MultiPoligon with a single point as in your solution)

enter image description here

from shapely.geometry import Point, shape
import fiona

for feat in fiona.open("mypoints.shp"):
    print(shape(feat['geometry']))

POINT (270855.306991149 4458932.596754404)
POINT (270764.3725329859 4458995.357990075)
POINT (270854.1957680934 4458994.84736782)
POINT (270866.2151319417 4458994.87391199)
POINT (270866.2151319417 4458994.87391199)
POINT (270870.1540668578 4458992.662788996)
POINT (270872.9667142337 4458963.298747919)
POINT (270794.8588358188 4458943.977238521)
POINT (270762.3619021429 4458965.487104538)
POINT (270764.3725329859 4458995.357990075)

To construct a shapely MultiPoint geometry with all the points of the shapefile

from shapely.geometry import MultiPoint
import fiona

mpt = MultiPoint([shape(point['geometry']) for point in fiona.open("mypoints.shp")])
mpt.convex_hull.wkt

'POLYGON ((270855.306991149 4458932.596754404, 270794.8588358188 4458943.977238521, 270762.3619021429 4458965.487104538, 270764.3725329859 4458995.357990075, 270866.2151319417 4458994.87391199, 270870.1540668578 4458992.662788996, 270872.9667142337 4458963.298747919, 270855.306991149 4458932.596754404))

enter image description here

NEW save the resulting shapefile

The resulting geometry is a Polygon therefore

from shapely.geometry import mapping
geom = mpt.convex_hull # the shapely geometry
schema = { 'geometry': 'Polygon', 'properties': { 'name': 'str' } }
with fiona.open('mew.shp', 'w', 'ESRI Shapefile', schema) as output:
    output.write({'properties': {'name': '0'}, 'geometry': mapping(geom)})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.