Warm tip: This article is reproduced from stackoverflow.com, please click
python raster gdal

Stacking of Raster Image and Compressing it in python

发布于 2020-03-29 12:46:45

I am trying to stacking my raster .tif file I have 12 .tif files but I also want to compress the output stacked file in python.

Here is my current working code for stacking file but after stacking the size of the file is very large

from osgeo import gdal
outvrt='/vsimen/Stacked.tif'
outtif='E:/Users/Compressed_files/Stacked.tif'
tifs=glob.glob('E:/Users/Compressed_files/*.tif')
outds=gdal.BuildVRT(outvrt,tifs,seperate=True)
outds=gdal.Translate(outtif,outds)
Questioner
Its_me
Viewed
40
Val 2020-02-05 02:13

You can pass a TranslateOptions object to your gdalTranslate call, where you can add the relevant creationOptions for compression.

So as dummy code:

from osgeo import gdal

topts = gdal.TranslateOptions(creationOptions=['COMPRESS=LZW', 'PREDICTOR=2'])
outds=gdal.Translate(outtif,outds, options=topts)

Of course, the options can also be a string or array of strings - it's not mandatory to use the TranslateOptions.

Also, the compression setting used in the dummy code is just an example. To maximize your gain, you should select options that work with your data.

Here's a excerpt from the documentation on available options for GeoTiffs:

COMPRESS=JPEG/LZW/PACKBITS/DEFLATE/CCITTRLE/CCITTFAX3/CCITTFAX4/LZMA/ZSTD/LERC/LERC_DEFLATE/LERC_ZSTD/WEBP/NONE]: Set the compression to use. JPEG should generally only be used with Byte data (8 bit per channel). But starting with GDAL 1.7.0 and provided that GDAL is built with internal libtiff and libjpeg, it is possible to read and write TIFF files with 12bit JPEG compressed TIFF files (seen as UInt16 bands with NBITS=12). See the “8 and 12 bit JPEG in TIFF” wiki page for more details. The CCITT compression should only be used with 1bit (NBITS=1) data. LZW, DEFLATE and ZSTD compressions can be used with the PREDICTOR creation option. ZSTD is available since GDAL 2.3 when using internal libtiff and if GDAL built against libzstd >=1.0, or if built against external libtiff with zstd support. LERC/LERC_DEFLATE/LERC_ZSTD are available since GDAL 2.4 when using internal libtiff (and for LERC_ZSTD, see above mentioned conditions). None is the default.

NUM_THREADS=number_of_threads/ALL_CPUS: (From GDAL 2.1) Enable multi-threaded compression by specifying the number of worker threads. Worth for slow compressions such as DEFLATE or LZMA. Will be ignored for JPEG. Default is compression in the main thread.

PREDICTOR=[1/2/3]: Set the predictor for LZW, DEFLATE and ZSTD compression. The default is 1 (no predictor), 2 is horizontal differencing and 3 is floating point prediction.