I am reading in a raster using rasterio, and then upsampling the raster as per the example in the documentation:
def upsample_raster(raster):
return raster.read(
out_shape=(raster.height * 2, raster.width * 2, raster.count),
resampling=resampling.bilinear,
)
This seems to work fine, except that this method returns the data in a numpy array.
My current application workflow includes operations such as masking which takes as input rasterio's DatasetReader
class.
Thus, I am searching for a way to resample a raster and get the result as a DatasetReader
or, without dumping the data to disk and re-opening the file, convert a numpy array into a valid DatasetReader
.
Best Answer
You need to recreate a
DatasetReader
manually and you can use aMemoryFile
to avoid writing to disk.You can re-use the metadata from the input raster in the
DatasetReader
, but you'll need to modify theheight
andwidth
properties and thetransform
. From documentation:In the example below note that:
contextmanager
so theDatasetReader
andMemoryFile
objects get cleaned up automatically. This is why I useyield
notreturn
in the functionraster.read
as arrays are(band, row, col)
order not(row, col, band)
like you used in your snippet.Output