Pratiman, 01 August 2020
2 min read.A simple and elegant method to convert NetCDF to GeoTIFF using python.
import xarray as xr
import rioxarray as rio
#Open the NetCDF
#Download the sample from https://www.unidata.ucar.edu/software/netcdf/examples/sresa1b_ncar_ccsm3-example.nc
ncfile = xr.open_dataset('sresa1b_ncar_ccsm3-example.nc')
#Extract the variable
pr = ncfile['pr']
#(Optional) convert longitude from (0-360) to (-180 to 180) (if required)
pr.coords['lon'] = (pr.coords['lon'] + 180) % 360 - 180
pr = pr.sortby(pr.lon)
#Define lat/long
pr = pr.rio.set_spatial_dims('lon', 'lat')
#Check for the CRS
pr.rio.crs
#(Optional) If your CRS is not discovered, you should be able to add it like so:
pr.rio.set_crs("epsg:4326")
#Saving the file
pr.rio.to_raster(r"GeoTIFF.tif")
import xarray as xr
import rioxarray as rio
ncfile = xr.open_dataset('sresa1b_ncar_ccsm3-example.nc')
pr = ncfile['pr']
pr.coords['lon'] = (pr.coords['lon'] + 180) % 360 - 180
pr = pr.sortby(pr.lon)
pr = pr.rio.set_spatial_dims('lon', 'lat')
pr.rio.crs
pr.rio.set_crs("epsg:4326")
pr.rio.to_raster(r"GeoTIFF.tif")
Hope you like it!