Skip to content

Instantly share code, notes, and snippets.

@mhweber
Last active August 21, 2023 19:18
Show Gist options
  • Select an option

  • Save mhweber/1a07b0881c2ab88d062e3b32060e5486 to your computer and use it in GitHub Desktop.

Select an option

Save mhweber/1a07b0881c2ab88d062e3b32060e5486 to your computer and use it in GitHub Desktop.
Rasterize a shapefile using geopandas and fiona
import geopandas as gpd
import rasterio
import fiona
from rasterio import features
import os
from datetime import datetime as dt
def Rasterize(shapefile, inras, outras, meta, field):
with rasterio.open(inras) as src:
kwargs = src.meta.copy()
kwargs.update({
'driver': 'GTiff',
'compress': 'lzw'
})
windows = src.block_windows(1)
with rasterio.open(outras, 'w', **kwargs) as dst:
for idx, window in windows:
out_arr = src.read(1, window=window)
# this is where we create a generator of geom, value pairs to use in rasterizing
shapes = ((geom,value) for geom, value in zip(shapefile.geometry, shapefile[field]))
burned = features.rasterize(shapes=shapes, fill=0, out=out_arr, transform=src.transform)
dst.write_band(1, burned, window=window)
if __name__ == '__main__':
start = dt.now()
in_rst = 'template.tif'
convert_to_rast = gpd.read_file('my_shapefile.shp')
convert_to_rast = convert_to_rast.loc[convert_to_rast['My Field'] == 'My Value']
convert_to_rast['Junk'] = 1
if rst.crs != convert_to_rast.crs:
convert_to_rast = convert_to_rast.to_crs(rst.crs)
out_rast = 'out.tif'
rasterize(convert_to_rast, in_rst, out_rast, meta, field='Junk')
print dt.now() - start2
@byersiiasa
Copy link

a few issues:

  • rst not defined
  • function is Rasterize, bu L34 has rasterize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment