2

I want to calculate the zonal statastics from multi band raster for a polygon layer. When I am using this snippet of code:

vectorlayer=qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()
zonalstats = qgis.analysis.QgsZonalStatistics(vectorlayer,rasterfile,"Zonal_")
zonalstats.calculateStatistics(None)

it is updating the field names but the values are NULL in the attribute table. So if I want to get the values to be updated, how can I do that?

Joseph
  • 75,746
  • 7
  • 171
  • 282
user99
  • 979
  • 2
  • 15
  • 36

2 Answers2

1

Not sure why you're getting NULL values but the following code worked for me (note that I call the QGIS Zonal Statistics tool from the Processing plugin and I want to load the result):

vectorlayer = qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()
processing.runandload('qgis:zonalstatistics', rasterfile, 3, vectorlayer, "Zonal_", True, None)

The following is the help description for the parameters required which you can edit in your code:

>>>processing.alghelp("qgis:zonalstatistics")
    ALGORITHM: Zonal Statistics
        INPUT_RASTER <ParameterRaster>
        RASTER_BAND <ParameterNumber>
        INPUT_VECTOR <ParameterVector>
        COLUMN_PREFIX <ParameterString>
        GLOBAL_EXTENT <ParameterBoolean>
        OUTPUT_LAYER <OutputVector>

Hope this helps!

Joseph
  • 75,746
  • 7
  • 171
  • 282
  • will the Zonal statastics work for multi band raster? – user99 Jul 24 '15 at 11:03
  • @user99 - I believe so yes since you can specify the number of Raster bands required (I used 3 in the code). – Joseph Jul 24 '15 at 11:07
  • is there any other way to calculate the raster statastics instead of Zonal? – user99 Jul 24 '15 at 11:16
  • @user99 - There's the Raster layer statistics tool which gives you the basic statistics: max, min, sum, mean, and std dev. Are there any specific statistics you are looking for? – Joseph Jul 24 '15 at 11:25
0

Here's my solution which I derived from running through the Zonal Statistics plugin wizard and viewing the generated Python command with Advanced -> Copy as Python Command. Then simply adding a loop to support the multiband requirement.

for i in range(1,num_raster_bands):
    processing.run("native:zonalstatisticsfb", { 
        'INPUT':'my_shp_file',
        'INPUT_RASTER':'my_raster_file',
        'RASTER_BAND':i,
        'COLUMN_PREFIX':'_',
        'STATISTICS':[0,1,2],
        'OUTPUT':f'output_filepath_{i}.csv'
})
hayfreed
  • 111
  • 4