Skip to content

Instantly share code, notes, and snippets.

@alpha-beta-soup
Last active March 14, 2024 19:10
Show Gist options
  • Save alpha-beta-soup/a628239f48dd64209440657fb65b8fab to your computer and use it in GitHub Desktop.
Save alpha-beta-soup/a628239f48dd64209440657fb65b8fab to your computer and use it in GitHub Desktop.
Example of running standalone QGIS 3 processing algorithms in Ubuntu Linux (typical installation)
#!/usr/bin/env python3
import os
import sys
import warnings
from functools import wraps
def ignore_warnings(f):
@wraps(f)
def inner(*args, **kwargs):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("ignore")
response = f(*args, **kwargs)
return response
return inner
def import_qgis_processing():
sys.path.append('/usr/lib/qgis')
sys.path.append('/usr/share/qgis/python/plugins')
from qgis.core import QgsApplication, QgsProcessingFeedback, QgsRasterLayer
app = QgsApplication([], False)
feedback = QgsProcessingFeedback()
return (app, feedback, QgsRasterLayer)
app, feedback, QgsRasterLayer = import_qgis_processing()
app.initQgis()
@ignore_warnings # Ignored because we want the output of this script to be a single value, and "import processing" is noisy
def initialise_processing(app):
from qgis.analysis import QgsNativeAlgorithms
import processing
from processing.core.Processing import Processing
Processing.initialize()
app.processingRegistry().addProvider(QgsNativeAlgorithms())
return (app, processing,)
def check_input_validity(QgsRasterLayer):
raster = QgsRasterLayer(sys.argv[1], 'raster', 'gdal')
if not raster.isValid():
raise Exception('Invalid raster')
def raster_stats():
params = {
'INPUT': sys.argv[1],
'BAND': 1
}
return processing.run(
"qgis:rasterlayerstatistics",
params, feedback=feedback
)
def get_raster_stat(stat='SUM'):
return raster_stats().get(stat)
app, processing = initialise_processing(app)
check_input_validity(QgsRasterLayer)
print(get_raster_stat(stat=sys.argv[2]))
app.exitQgis()
@alpha-beta-soup
Copy link
Author

You would run this as: python3 ./rasterstats.py /path/to/some/raster/file.tif SUM, and it would output the sum of all values of the input raster to stdout. MAX, MIN etc. all work too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment