Defining the CRS using rasterio when reading nongeoreferenced raster

coordinate systempythonrasterio

I am trying to manually set the CRS of my rasterio object after reading in a png/pgw file.

Of course, the pgw file contains the transformation for the raster but does not include any georeferencing/CRS information. So, I am trying to manually set it afterwards, it seems to work sometimes but not others… this is what I'm currently doing:

from rasterio.crs import CRS
import rasterio as rio

r = rio.open(file, 'r')
print(r.crs)
#prints nothing
crs = CRS.from_epsg(32611)
r._crs = crs

Now weirdly, sometimes it works..and sometimes even if I run this command without error, the r.crs will still be None.

I tried using:

r.crs = crs #read only attribute, cant do this
r._crs = crs #works sometimes but not others??
r._set_crs(crs) #read only attribute
setattr(r, '_crs', to_crs) #seems to work the same as r._crs

What is the proper way to manually define the CRS of an unknown raster?

Best Answer

You need r+ mode:

from rasterio.crs import CRS
import rasterio

with rasterio.open(file, 'r+') as rds:
    rds.crs = CRS.from_epsg(32611)
Related Question