Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active April 8, 2024 12:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/c2c31d3d3cb58e2f70ca920d9253140b to your computer and use it in GitHub Desktop.
Save CMCDragonkai/c2c31d3d3cb58e2f70ca920d9253140b to your computer and use it in GitHub Desktop.
Clone GDAL/OGR DataSource/DataSet to in-memory instance #gdal #ogr #python
from osgeo import gdal, ogr
def clone_data_to_mem(ds, name=''):
if (isinstance(ds, gdal.Dataset)):
return clone_raster_to_mem(ds, name)
elif (isinstance(ds, ogr.DataSource)):
return clone_vector_to_mem(ds, name)
else:
raise TypeError('Data source must be of GDAL dataset or OGR datasource')
def clone_vector_to_mem(vector_ds, name=''):
driver = ogr.GetDriverByName('Memory')
return driver.CopyDataSource(vector_ds, name)
def clone_raster_to_mem(raster_ds, name=''):
driver = gdal.GetDriverByName('MEM')
return driver.CopyDataSource(raster_ds, name)
@CMCDragonkai
Copy link
Author

Useful for cloning a disk backed data into an in-memory mutable data, so you can work on it in memory, before committing it to disk.

At some point you may need to create a target datasource, and then copy the memory data back into it.

@CMCDragonkai
Copy link
Author

In GDAL 2.x, there's no need to use OGR as well, as GDALDataset when used with OpenEx will support both raster and vector data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment