[GIS] GDAL Warp to in-memory raster

gdalgdalwarprastervrt

So, I have a few rasters I need to use for processing, but the task requires them to be in a different SRS than they currently are. GDAL Warp would be the go-to solution, however, it saves the transformed raster in a new file, and for project reasons I cannot have it save a transformed file anywhere, it has to be done in memory. I thought of two ways to do it, but encountered problems in both.

Alternative #1: use the MEM driver.

This would be ideal, but GDALDriver::CreateCopy() however does not
have a reprojection parameter, and I'm unable to create an empty
memory raster (and pass that to Warp) because GDALDriver::Create()
expects input of the number of rows and cols, and I have no idea how
many there'll be in the transformed raster before I transform it.

or

Alternative #2: build a VRT.

I can very easily get the desired data from a transformed vrt, and
that would actually be my preferred solution if I was able to save it
anywhere. But I can't. But then I thought, a vrt is just an xml, might
there be a way to just generate the vrt in memory, instead of saving
it to disk beforehand?

I'm not really tieing this problem to one alternative or the other, just showing what I tried thus far. A working solution for either would be fine, as would be an entirely different solution I haven't thought of.

Best Answer

The best solution for you would be the VSIMEM filesystem which lets you save outputs of gdal utilities into a filesystem stored in memory.

gdal.Warp('/vsimem/reprojected.tif', ds, srcSRS=in_proj, dstSRS=out_proj)

You could also make a vrt:

gdal.Warp('/vsimem/reprojected.vrt', ds, srcSRS=in_proj, dstSRS=out_proj)

Once stored in the vsimem filesystem, the file may be retrieved:

ds = gdal.Open('/vsimem/reprojected.tif')

Files in the vsimem filesystem may also be called as inputs to gdal utilities instead of a local path, which makes it a useful tool when stringing together multiple utility calls while keeping intermediary data in memory.

Use gdal.Unlink('/vsimem/reprojected.tif') to remove from memory.

Related Question