[1079] QGIS tools to python code
Steps:
- Open the
Processing Toolbox
in QGIS. - Search for the desired tool, such as the
Raster Calculator
. - Set the parameters for the selected tool according to your requirments.
- Click on
Advanced
, and convert the tool to Python code.
Examples: Raster Calculator -> Polygonize
The following script needs to be executed using QGIS's built-in Python interpreter.
import os, math
input_dir = r"..\Data_to_be_processed\Minimum Temperature\Projections\SSP3_7.0\Absolute"
output_dir_RC = os.path.join(input_dir, "RasterCalculator")
output_dir_Poly = os.path.join(input_dir, "Polygonize")
# create a new folder if this folder does not exist
if not os.path.exists(output_dir_RC):
os.makedirs(output_dir_RC)
if not os.path.exists(output_dir_Poly):
os.makedirs(output_dir_Poly)
def raster_calculator_func(input_fp, output_fp, operator, weight_number):
file_name = os.path.basename(input_fp).split('.')[0]
processing.run(
"qgis:rastercalculator",
{
'EXPRESSION':f' ( "{file_name}@1" - {weight_number / 2} ) {operator} {weight_number}', # replace the file name, operator and weight number
'LAYERS':[input_fp], # input file path
'CELLSIZE':0,
'EXTENT':None,
'CRS':QgsCoordinateReferenceSystem('EPSG:4283'),
'OUTPUT':output_fp})
def polygonize_func(input_fp, output_fp):
processing.run(
"gdal:polygonize",
{
'INPUT':input_fp,
'BAND':1,
'FIELD':'DN',
'EIGHT_CONNECTEDNESS':False,
'EXTRA':'',
'OUTPUT':output_fp})
for fn in os.listdir(input_dir):
if fn.endswith(".tif"):
input_fp = os.path.join(input_dir, fn)
output_fp_RC = os.path.join(output_dir_RC, fn)
raster_calculator_func(input_fp, output_fp_RC, '/', 3)
output_fp_Poly = os.path.join(output_dir_Poly, fn.replace("tif", "shp"))
polygonize_func(output_fp_RC, output_fp_Poly)
print("Complete the raster calculator of", fn)
print()