I need to rasterize a really simple shapefile a bit like this http://tinyurl.com/odfbanu. Which is just a shapefile containing counties in the US. I have seen this previous answer: GDAL RasterizeLayer does not Burn All Polygons to Raster? but I was wondering if there is a way to do it using Geopandas or fiona and maybe rasterio for the tiff writing part.
So my goal is to rasterize it and assign a value to every polygon sharing a common value, LSAD in the example.
So I wrote the beginning of the code inspired by shongololo in the thread: Dissolving polygons based on attributes with Python (shapely, fiona)?.
from geopandas import GeoDataFrame
name_in = 'cb_2013_us_county_20m.shp'
#Open the file with geopandas
counties = GeoDataFrame.from_file(name_in)
#Add a column to the Geodataframe containing the new value
for i in range (len(counties)):
LSAD = counties.at[i,'LSAD']
if LSAD == 00 :
counties['LSAD_NUM'] == 'A'
elif LSAD == 03 :
counties['LSAD_NUM'] == 'B'
elif LSAD == 04 :
counties['LSAD_NUM'] == 'C'
elif LSAD == 05 :
counties['LSAD_NUM'] == 'D'
elif LSAD == 06 :
counties['LSAD_NUM'] == 'E'
elif LSAD == 13 :
counties['LSAD_NUM'] == 'F'
elif LSAD == 15 :
counties['LSAD_NUM'] == 'G'
elif LSAD == 25 :
counties['LSAD_NUM'] == 'I'
else :
counties['LSAD_NUM'] == 'NA'
Really easy stuff, so now I am wondering how I can actually write those shapes to a tiff. I began working with Geopandas as I believed that was the best option but if you have a fiona suggestion I am up for it too.
I found a piece of code from rasterio which seems to be able to take a shapely geometry and burn it into a new raster http://tinyurl.com/op49uek
# I guess that my goal should be to load my list of geometries under geometry to be able to pass it to rasterio later on
geometry = {'type':'Polygon','coordinates':[[(2,2),(2,4.25),(4.25,4.25),(4.25,2),(2,2)]]}
with rasterio.drivers():
result = rasterize([geometry], out_shape=(rows, cols))
with rasterio.open(
"test.tif",
'w',
driver='GTiff',
width=cols,
height=rows,
count=1,
dtype=numpy.uint8,
nodata=0,
transform=IDENTITY,
crs={'init': "EPSG:4326"}) as out:
out.write_band(1, result.astype(numpy.uint8))