Search code examples
pythongisspatialgeopandasrasterio

How to change the crs of a raster with rasterio?


I am trying to change the CRS of a raster tif file. When I assign new CRS using the following code:

with rio.open(solar_path, mode='r+') as raster:
    raster.crs = rio.crs.CRS({'init': 'epsg:27700'})
    show((raster, 1))
    print(raster.crs)

The print function returns 'EPSG:27700', however after plotting the image the CRS clearly hasn't change?


Solution

  • Unlike Geopandas, rasterio requires manual re-projection when changing the crs.

    def reproject_raster(in_path, out_path):
    
        """
        """
        # reproject raster to project crs
        with rio.open(in_path) as src:
            src_crs = src.crs
            transform, width, height = calculate_default_transform(src_crs, crs, src.width, src.height, *src.bounds)
            kwargs = src.meta.copy()
    
            kwargs.update({
                'crs': crs,
                'transform': transform,
                'width': width,
                'height': height})
    
            with rio.open(out_path, 'w', **kwargs) as dst:
                for i in range(1, src.count + 1):
                    reproject(
                        source=rio.band(src, i),
                        destination=rio.band(dst, i),
                        src_transform=src.transform,
                        src_crs=src.crs,
                        dst_transform=transform,
                        dst_crs=crs,
                        resampling=Resampling.nearest)
        return(out_path)