1

I have this simple code that batch sieves all the raster in a given directory. I found outthat the resulting output files (241MB )are pretty much larger than the input(~31MB). In ArcGIS, there is a way to enable compression like LZW, how to do it it QGIS python? Is there a way to insert it in this code?

from qgis.core import * #importing the QGIS processing core
import os, subprocess, glob

input = "/data/brent/GAUP/sen2agri_two_years/"
output_dir = "/data/brent/GAUP/sen2agri_two_years/sieved//"
os.chdir(input)

for fname in glob.glob("S2*.TIF"):
    print fname
    name= list(os.path.splitext(fname))
    name[0] = name[0] + "_sieved"
    newName = "".join(name)
    print "processing " + newName
    subprocess.call(["gdal_sieve.py", "-st", "20", "-4", fname, "-of", "GTiff", output_dir+newName])
3
  • 1
    I am not sure if the gdal_sieve python script accepts raster layer creation options. If it does you should pass -co COMPRESS=LZW as documented in gdal.org/frmt_gtiff.html. Otherwise you can create a temporary output, perhaps info memory, and copy that into compressed tiff afterwards.
    – user30184
    Commented Feb 7, 2018 at 10:42
  • hello I tried editing the code at subprocess.cal portion: subprocess.call(["gdal_sieve.py", "-st", "300", "-4", fname, "-of", "GTiff", "-co", "COMPRESS=LZW", output_dir+newName]) But the code didn't work. Thanks. Any suggestion to improve my edits? Commented Feb 8, 2018 at 2:10
  • You could try to edit the gdal_sieve.py directly. Find where it initializes the output raster.
    – user30184
    Commented Feb 8, 2018 at 6:12

1 Answer 1

1

I add a few lines in my code using gdal_translate:

from qgis.core import * #importing the QGIS processing core
from qgis.utils import iface #importing the iface
import os, subprocess, glob

input = "/data/brent/GAUP/sen2agri_two_years/"
output_dir = "/data/brent/GAUP/sen2agri_two_years/sieved//"
os.chdir(input)

#Main Process
for fname in glob.glob("S2*.TIF"):
    name= list(os.path.splitext(fname))
    name[0] = name[0] + "_sieved"
    newName = "".join(name)
    print "processing " + newName
    subprocess.call(["gdal_sieve.py", "-st", "20", "-8", fname, "-of", "GTiff",  output_dir+newName])
    os.chdir("/data/brent/GAUP/sen2agri_two_years/sieved/")
    output_dir2 = "/data/brent/GAUP/sen2agri_two_years/sieved//"
    newName2 = newName.replace("_sieved", "_com")
    subprocess.call(["gdal_translate", "-of", "GTiff", newName, output_dir2+newName2, "-co", "compress=LZW"])
    os.chdir(input)

print "Finished Sieving!"

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.