TransWikia.com

Set number of columns and rows with PyQGIS

Geographic Information Systems Asked by ilFonta on August 24, 2021

I know how to resample a raster using pyQGIS 3.0 and the gdal warptranslate function by imposing the pixel dimension of the output file, see below.

rasterLayer = QgsRasterLayer('/path/inputfile.tif', 'raster')
    
parameters = {
    'INPUT': rasterLayer,
    'SOURCE_SRS': "EPSG:32632",
    'TARGET_SRS': "EPSG:32632",
    'RESAMPLING': 1,
    'NODATA': 0,
    'TARGET_RESOLUTION': 30,
    'OPTIONS': "",
    'DATA_TYPE': 6,
    'TARGET_EXTENT': rasterLayer,
    'TARGET_EXTENT_CRS': "EPSG:32632",
    'MULTITREADING': True,
    'EXTRA': "",
    'OUTPUT': "/path/fileout.tif"}

processing.run('gdal:warpreproject', parameters)

Is there a way to resample a raster by imposing instead the number of columns and rows (pixel dimension can varies)?

One Answer

You can calculate target resolution from the layer extent and number of columns/rows.

rows = 1000    # set as you need
cols = 2000    # set as you need

rasterLayer = QgsRasterLayer('/path/inputfile.tif', 'raster')
ext = rasterLayer.extent()
x_res = (ext.xMaximum() - ext.xMinimum()) / rows
y_res = (ext.yMaximum() - ext.yMinimum()) / cols
res = min(x_res, y_res) # or max or mean?

Then add resolution to processing parameters. As far as I know you cannot set different resolutions in x and y directions from processing (while in the command line version of gdalwarp it is possible).

Answered by Zoltan on August 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP