1Masking a raster using a shapefile 2================================== 3Using ``rasterio`` with ``fiona``, it is simple to open a shapefile, read geometries, and mask out regions of a raster that are outside the polygons defined in the shapefile. 4 5.. code-block:: python 6 7 import fiona 8 import rasterio 9 import rasterio.mask 10 11 with fiona.open("tests/data/box.shp", "r") as shapefile: 12 shapes = [feature["geometry"] for feature in shapefile] 13 14This shapefile contains a single polygon, a box near the center of the raster, so in this case, our list of features is one element long. 15 16.. code-block:: python 17 18 with rasterio.open("tests/data/RGB.byte.tif") as src: 19 out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True) 20 out_meta = src.meta 21 22Using ``plot`` and ``imshow`` from ``matplotlib``, we can see the region defined by the shapefile in red overlaid on the original raster. 23 24.. image:: ../img/box_rgb.png 25 26Applying the features in the shapefile as a mask on the raster sets all pixels outside of the features to be zero. Since ``crop=True`` in this example, the extent of the raster is also set to be the extent of the features in the shapefile. We can then use the updated spatial transform and raster height and width to write the masked raster to a new file. 27 28.. code-block:: python 29 30 out_meta.update({"driver": "GTiff", 31 "height": out_image.shape[1], 32 "width": out_image.shape[2], 33 "transform": out_transform}) 34 35 with rasterio.open("RGB.byte.masked.tif", "w", **out_meta) as dest: 36 dest.write(out_image) 37 38.. image:: ../img/box_masked_rgb.png 39