pythonpython-3.xgisgdalimage-registration

gdal resize and save to png using python


I know how to use gdal_translate from cmd line to resize and save the png:

gdal_translate -of PNG -outsize 10% 10% image.bsq image.png

But using python I only know how to save the png:

from osgeo import gdal

img_png  = 'image.png'
img_bsq  = 'image.bsq'
src_ds = gdal.Open(img_bsq)
out_format = "GTiff"
driver = gdal.GetDriverByName(out_format)
dst_ds = driver.CreateCopy(img_png, dst_ds, 0)
dst_ds = None
src_ds = None

May I ask how to resize and save the png using python?


Solution

  • You can use gdal_translate in python. Something like this should work.

    from osgeo import gdal
    
    options_list = [
        '-outsize 10% 10%',
        '-of PNG'
    ] 
    options_string = " ".join(options_list)
    
    gdal.Translate('image.png',
                   'image.bsq',
                   options=options_string)
    

    You could of course also write the options string yourself if you like, however i like to write it as a list and then convert it.

    If you are not comfortable with the python bindings, you can also use subprocess or os.system to call the command line versions.