TransWikia.com

Extracting convex_hull polygon from CSVwith scipy.spatial ConvexHull and output it to a shapefile

Geographic Information Systems Asked by Francesco Zucca on June 7, 2021

I’m looking for a Python solution for extract a convex_hull polygon from quite big CSV (nearly 150 millions points) and return back the polygon to a shapefile.
After reading the CSV with pandas (pd.read_csv), I give a change to scipy.spatial Convex_Hull due to very quick response time. And effectively I get the convex_hull envelope correctly estimates.

But I’m now in the hurdles, because I’ve not a solution to export the result (a scipy.spatial.qhull.ConvexHull ). If I understand correctly, I need to extract from the hull structure the points or vertices, because no polygon is available.

Any hints?

One Answer

With geopandas and shapely you can do:

from scipy.spatial import ConvexHull as ch
import pandas as pd
from shapely.geometry import Polygon
import geopandas as gpd
xfield, yfield = 'xcoord', 'ycoord'
epsg = 3006
csvfile = r"C:GISdatatestdatamany_points.csv"

df = pd.read_csv(csvfile) 
arr = df[[xfield, yfield]].to_numpy() #Create numpy array from coordinates
hull = ch(arr) #Calculate convex hull

polylist = []
for idx in hull.vertices: #Indices of points forming the vertices of the convex hull.
    polylist.append(arr[idx]) #Append this index point to list
#polylist[:2]
#Out[61]: [array([ 757300.23175, 6432516.2335 ]), array([ 919182.325 , 7307516.6095])]

p = Polygon(polylist)
df = pd.DataFrame({'hull':[1]})
df['geometry'] = p
gdf = gpd.GeoDataFrame(df, crs='EPSG:{}'.format(epsg), geometry='geometry')
gdf.to_file( r"C:GISdatatestdatamany_points_convex_hull.shp")

enter image description here

Correct answer by BERA on June 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP