GDAL – Can Gdal.Translate() Return an Object Instead of Writing a File?

gdalgdal-translatepython

I have some Python GDAL code I am using to convert a GeoTIFF file to PNG. The code uses the gdal.Translate() function which generates a new file each time I run it. However, I was wondering if there is a way to get the Python gdal.Translate() function to return a python object instead of writing a file? Ideally I would like to write to a numpy array or something, but any kind of internal object would be fine.

Here is some sample code I am using:

from osgeo import gdal

scale = '-scale min_val max_val'
options_list = [
    '-ot Byte',
    '-of JPEG',
    scale
] 
options_string = " ".join(options_list)

gdal.Translate('test.jpg',
               'test.tif',
               options=options_string)

I looked over the documentation and source code to figure out how gdal.Translate() worked, but could not get past the TranslateInternal() function. I could not find a link through the source code past that.

Best Answer

gdal.Translate does return an object, it returns a gdal.Dataset object.

from osgeo import gdal
in_ds = gdal.OpenEx('path/to/input.tif')
print(in_ds)

<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x00000000037BE930> >

out_ds = gdal.Translate('path/to/output.tif', in_ds)
print(out_ds )

<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x00000000037BE990> >

It has to write the translated output somewhere...

If you don't want to write to disk, write to memory (don't bother with the MEM driver), use the "VSIMEM" virtual filesystem to write a GeoTIFF to memory:

out_ds = gdal.Translate('/vsimem/in_memory_output.tif', in_ds)

You can then read it into a numpy array if you want.

out_arr = out_ds.ReadAsArray()
Related Question