2

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?

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
svein
  • 21
  • 1
  • 2
  • What does Python say when you try to execute it? – Gnudiff Feb 26 '19 at 14:32
  • And your code doesn't seem to match the function signature at all. The order of arguments is wrong, plus it apparently requires a couple Band objects as arguments, and you are providing some filenames instead. – Gnudiff Feb 26 '19 at 14:34
  • The signature is showing the type of each parameter, followed by the parameter name. For a "Band" you need myds.GetRasterBand(mybandnum), for example, a GDAL band object. – Benjamin Mar 14 '19 at 01:12

3 Answers3

1

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.

jbrownmi88
  • 11
  • 2
1

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.

0

I know this thread is old but since there is no accepted answer, here's a working version using gdal>=3.5

from osgeo_utils.gdal_sieve import gdal_sieve

gdal_sieve(
    src_filename="C:/X/testX.tif",
    dst_filename="C:/X/testX_sieved.tif",
    threshold=100,
    connectedness=8
)