How to change the crs of a raster with rasterio?
Asked Answered
C

2

9

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?

Caen answered 18/2, 2020 at 20:27 Comment(0)
C
10

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)
Caen answered 31/3, 2020 at 14:4 Comment(2)
For more details visit earthdatascience.org/courses/use-data-open-source-python/…Zulemazullo
this code contains multiple variables that are not defined anywhereDarnell
I
1

The plotting function would not change the CRS of your data. You can try

from rasterio.crs import CRS
import rioxarray as rxr

raster = rxr.open_rasterio(solar_path, masked=True).squeeze()
raster_new = raster.rio.reproject(CRS.from_string('EPSG:4326'))

print(raster_new.rio.crs)     # CRS.from_epsg(4326)
Io answered 28/10, 2023 at 6:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.