I want to crop a geo raster image with a geo shapefile using rasterio and geopandas. I struggle to properly create a mask so that the cropped areas actually display as transparent (and not black or any other color) when plotting with matplotlib.
How can I achieve this?
I am looking for a Python solution and I'd like to avoid creating an intermediate file on disk or use a GIS software. I looked through various SO posts and rasterio sample code to no avail. I tried manipulating numpy arrays, masked arrays and using a dataset MemFile, again with no success.
Sample code to illustrate the problem:
src = rasterio.open('test.tif')
shape = gpd.read_file("shape.shp")
fig, ax = plt.subplots(figsize=(6,6))
rasterio.plot.show(src, ax=ax)
shape.plot(color="red", ax=ax)
I would like to crop the raster so that pixels are only visible within the red star shape.
So I do this:
out_image, out_transform = rasterio.mask.mask(src, shape.geometry)
fig, ax = plt.subplots(figsize=(6,6))
rasterio.plot.show(out_image, transform=out_transform, ax=ax)
However, the cropped areas are black but not transparent. What do I do wrong?
rasterio.plot.show
is a wrapper of matplotlib imshow see Setting points with no data to white with Matplotlib imshow