10

How do I force the use of compression on the GTiff driver when called from osgeo.gdal in Python?

Example on the workflow, which currently reads LZW tiffs and dumps them to uncompressed tiffs.

from osgeo import gdal,gdalconst,osr
translateoptions = gdal.TranslateOptions(rgbExpand='RGB', format='GTiff')
outFile = gdal.Translate(gdaloutput, gdalinput, options=translateoptions)

Would be nice to do this without the use of subprocess.

Environment:

  • Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 11:27:44) [MSC v.1900 64 bit (AMD64)] on win32
  • gdal-2.2.2
  • libgdal-2.2.2

3 Answers 3

12

You have "creationOptions" for this:

translate_options = gdal.TranslateOptions(format = 'GTiff',
                                          creationOptions = ['TFW=YES', 'COMPRESS=LZW']
                                          )
9

I found the answer in this post.

The post says

GDAL supports three lossless compression algorithms for the GeoTiff format – Packbits, LZW and Deflate.
You can use the compression methods with GDALs creation options.

gdal_translate -of GTiff -co "COMPRESS=LZW" -co "PREDICTOR=2" -co "TILED=YES" uncompressed.tiff LZW-pred2-compressed.tiff

In addition, adding an options argument using drive.Create may be helpful.

driver.Create(utf8_path, xsize, ysize, bands, data_type, options=['COMPRESS=LZW'])

6

Thanks fenfen123. I ended up using the following approach via the GDAL python api:

# Write new tiffs with RGB palette
gdalinput = tile+'.tif'
gdaloutput = oFolder+'\\'+Path(tile).name+'.tif'    
translateoptions = gdal.TranslateOptions(gdal.ParseCommandLine("-of Gtiff -co COMPRESS=LZW"))
gdal.Translate(gdaloutput, gdalinput, options=translateoptions)
2
  • 2
    TranslateOptions (e.g. -ot -of -co) are listed on gdal.org/gdal_translate.html
    – Maosi Chen
    Feb 22, 2019 at 2:47
  • 2
    Your method was helpful to me. But for anyone else looking, you can use the gdal.TranslateOptions(format="GTiff", options=['COMPRESS=LZW']) way of doing it that I think is a little cleaner. See the gdal.TranslateOptions python function for an easy way to see the full list of options.
    – L0ngSh0t
    Jun 29, 2021 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.