0

I masked a geotiff raster with a shapefile as described below

import rasterio
from rasterio.plot import show
import geopandas as gpd

population = rasterio.open('myData.tif')
gdf = gpd.read_file('myFile.shp')
clipped_array, clipped_transform = 
rasterio.mask.mask(population, [mapping(ps.iloc[0].geometry)], crop=True)

f,ax=plt.subplots(figsize=(10,10))
gdf.boundary.plot(ax=ax, lw=3, color='red')
show(clipped_array, transform=clipped_transform, ax=ax)
ax.set_xlim([1.82, 2.74])
ax.set_ylim([48.51, 49.14])

enter image description here

Now I would like to save the new data as a .tif file with coordinates and information.

emax
  • 6,965
  • 19
  • 74
  • 141

1 Answers1

2

You can write to a new .tif using this. Since rasterio needs some meta for writing, it's common to use an input raster, such as in this case with adjusted attributes.

import rasterio
import os
import fiona
from rasterio import mask


with fiona.open('myFile.shp', "r") as shapefile:
    shapes = [feature["geometry"] for feature in shapefile]

with rasterio.open('myData.tif') as src:
    out_meta = src.meta
    out_image, out_transform = rasterio.mask.mask(src, shapes=shapes, crop=True)

    
    profile = src.profile
    profile["height"] = out_image.shape[1]
    profile["width"] = out_image.shape[2]
    profile["transform"] = out_transform

   
    out_meta.update({"driver": "GTiff",
                 "height": out_image.shape[1],
                 "width": out_image.shape[2],
                 "transform": out_transform})

with rasterio.open("masked.tif", "w", **out_meta) as dest:
    dest.write(out_image)
Matthew Borish
  • 3,016
  • 2
  • 13
  • 25