title: How do I use rasterio/python to mask a raster using a shapefile, to set the raster pixels inside the polygons to zero?
body: <p>I am trying to create a land mask to apply to satellite imagery, that will set the pixels in a raster intersecting with a land mass to 0.</p>
  
  <p>After experimenting with gdal, skimage, pyplot etc. I've found the method given in the rasterio cookbook to be quick and easy. However, it is setting the pixels <em>outside</em> the polygons to 0, whereas I am trying to do the inverse of this.</p>
  
  <p>Keep to using rasterio if possible - you don't have to calculate pixel locations of geospatial coordinates or deal with clipping features that are beyond the extents of the raster turning negative. It's also FAST which is important for the file size of the raw imagery I'm working with.</p>
  
  <p>From here: <a href="https://mapbox.s3.amazonaws.com/playground/perrygeo/rasterio-docs/cookbook.html#masking-raster-with-a-polygon-feature" rel="noreferrer">https://mapbox.s3.amazonaws.com/playground/perrygeo/rasterio-docs/cookbook.html#masking-raster-with-a-polygon-feature</a></p>
  
  <p>My code is as follows:</p>
  
  <pre><code>import fiona
  import rasterio
  from rasterio.tools.mask import mask
  
  with fiona.open("/Users/Cate/UK_Mainland.shp", "r") as shapefile:
      geoms = [feature["geometry"] for feature in shapefile]
  
  with rasterio.open("jan_clip.tif") as src:
      out_image, out_transform = mask(src, geoms, crop=True)
      out_meta = src.meta.copy()
  
  out_meta.update({"driver": "GTiff",
                   "height": out_image.shape[1],
                   "width": out_image.shape[2],
                   "transform": out_transform})
  
  with rasterio.open("masked2.tif", "w", **out_meta) as dest:
      dest.write(out_image)
  </code></pre>
  
  <p>How do I mask the areas that intersect with the polygons rather than those that don't?</p>