Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gdal sieve filter in python

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?

like image 412
svein Avatar asked Apr 26 '26 00:04

svein


2 Answers

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.

like image 150
jbrownmi88 Avatar answered Apr 28 '26 12:04

jbrownmi88


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.