I want to sieve a classified image in py, and I try to use the gdal sieve function, but it will not work:
Syntax:
SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness=4, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> int
My code:
gdal.SieveFilter(1 "C:/X/testX.tif",None,1 "C:/X/testX_sieved.tif",100, 8)
What's the error here?
I do not believe there is a working python binding for the gdal sieve command. I am able to run it successfully by calling it from the command line by using this:
import os, sys, subprocess
sys.path.append(r'C:\Users\*****\AppData\Local\conda\conda\envs\****\Scripts')
gm = os.path.join('C:\\','Users','*****','AppData','Local','conda','conda','envs','****','Scripts','gdal_sieve.py')
sieve_command = ["python", gm,'-st','10','-8','-nomask','-of','GTiff','to_be_sieved.tif','sieved.tif']
subprocess.call(sieve_command,shell=True)
Of course, you'll need to change some paths in the first couple lines to point to the location where your gdal scripts are stored.
To apply the sieve in Python, you must provide raster bands for the first and third arguments. I suspect the error arises because the destination band (third argument) is not writable (i.e. you must open the destination image in read-write mode).
For example, to overwrite the original image:
from osgeo import gdal
Image = gdal.Open('SomeImageName.tif', 1) # open image in read-write mode
Band = Image.GetRasterBand(1)
gdal.SieveFilter(srcBand=Band, maskBand=None, dstBand=Band, threshold=100, connectedness=8, callback=gdal.TermProgress_nocb)
del Image, Band # close the datasets.
P.S. This works on Linux, gdal=3.1, python=3.9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With