8

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?

four_loops
  • 235
  • 1
  • 2
  • 9

1 Answers1

9

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)
four_loops
  • 235
  • 1
  • 2
  • 9
  • For more details visit https://www.earthdatascience.org/courses/use-data-open-source-python/intro-raster-data-python/raster-data-processing/reproject-raster/ – PPR May 03 '20 at 10:14
  • 1
    this code contains multiple variables that are not defined anywhere – patkru May 15 '23 at 20:32