I am trying to clip a Tiff raster with a shapefile. I follow the examples provided in rioxarray (here)
The link to raster file (here) and shp file (here)
import xarray as xr
import rioxarray
import geopandas as gpd
from shapely.geometry import box, mapping
#read the shp file
geodf = gpd.read_file('shp_file.shp')
# Assign the crs
prj = [l.strip() for l in open('shp_file.prj','r')][0]
geodf.crs = prj
# Select one of the polygons
tmp = geodf[geodf['OBJECTID']==1]
da = xr.open_rasterio('raster_file.tif')
file_clipped = da.rio.clip(tmp.geometry.apply(mapping),tmp.crs)
file_clipped.rio.to_raster('file_clipped.tif')
However the resulted raster file (file_clipped.tif) has a different pixel size than the original one. The pixel size for the original raster is (463.3127165m, 463.3127165m) and for the clipped is (830.1019504m, 506.502885m). I am not sure what I do wrong. Is there any way to fix the raster pixel size when clipping?
EDIT1: Updated the codes and also uploaded the shp and raster files.
EDIT2: clipping the TIFF file with the rasterio.mask (in cases where polygons are separated, refer to the answers).
def tif_clip(tif_file, shp_file):
from rasterio.mask import mask
def getFeatures(gdf):
"""Function to parse features from GeoDataFrame in such a manner that rasterio wants them"""
import json
return [json.loads(gdf.to_json())["features"][0]["geometry"]]
coords = getFeatures(shp_file)
out_img, out_transform = mask(tif_file, shapes=coords, crop=True)
out_meta = tif_file.meta.copy()
#epsg_code = int(data.crs.data["init"][5:])
out_meta.update(
{
"driver": "GTiff",
"height": out_img.shape[1],
"width": out_img.shape[2],
"transform": out_transform,
#"crs": pycrs.parse.from_epsg_code(epsg_code).to_proj4(),
"crs": tif_file.crs,
}
)
out_file = 'clip_raster.tif'
with rasterio.open(out_file, "w", **out_meta) as dest:
dest.write(out_img)
tif_file = rasterio.open('raster_file.tif')
geodf = gpd.read_file('shp_file.shp')
tmp = geodf[geodf['OBJECTID']==1]
tif_clip(tif_file,tmp)
This approach keeps the pixel size unchanged and also crop the extend to the extend of the shapefile. However, it still would be nice to be able to do the same thing with rioxarray for NetCDF files.