Search code examples
rasterrasterio

Rasterio base object in Python?


I would like to create some simple raster test data using rasterio that I can later process. I don't want to write to/read from any files from disk, but instead would like to work from variables/in memory objects. I also don't need to give this raster a projection from the time being.

For asc type rasters for example it could be as simple as this:

ncols 4
nrows 4
xllcorner 20
yllcorner 8.5
cellsize 0.5
nodata_value -9999
0.1 0.2 0.3 0.4
0.2 0.3 0.4 0.5
0.3 0.4 0.5 0.6
0.4 0.5 0.6 0.7

Does rasterio support any objects which I can fill out with the above data without worrying about writing to or reading from raster files?


Solution

  • I think rasterio.io.MemoryFile might work for your application (memory file docs). For your example, it might look something like:

    from rasterio.io import MemoryFile
    from affine import Affine
    
    with MemoryFile() as memfile:
        transform = Affine(0.5, 0, 20, 0, 0.5, 8.5)
        data = np.arange(16).reshape(1, 4, 4) / 10
        meta = {"count": 1, "width": 4, "height": 4, "transform": transform, "nodata": -9999, "dtype": "float64"}
        with memfile.open(driver='GTiff', **meta) as dataset:
            dataset.write(data)