Monday, 4 February 2019

pyqgis - How to use QgsRasterInterface.histogram?



This is really a question of how to better understand QGIS API documentation (C++ or Python) but I'll use this example:


How do I use QgsRasterInterface.histogram? I was told in this thread I can use QgsRasterInterface.histogram to calculate a list of unique values and their counts in a raster layer.


My best attempt so far:


layer = iface.activeLayer()        #the active layer is a raster layer
provider = layer.dataProvider()

print(provider.hasHistogram(1, 127)) #returns false, no histogram yet

provider.histogram(1) #for band 1


and QGIS crashes. No errors or other information, just a crash. I see that QgsRasterInterface has a method .initHistogram. Maybe I need to initialize the histogram first?:


enter image description here


The first argument of .initHistogram is a QgsRasterHistogram. I am unsure how to make this QgsRasterHistogram object. The documentation for this class lists no methods. Though it does have some attributes which are inherited from QgsRasterInterface, and none of the attributes have an description. The QgsRasterHistogram has a short description which makes me think I am on the right path:


enter image description here


By doing a quick test I can see I have not constructed the QgsRasterHistogram properly.


histogram = QgsRasterHistogram()
print(histogram.extent) #prints empty extent

The documentation is mostly empty for QgsRasterHistogram and when I try to use it in the PyQGIS console, I am not prompted to add any arguments or anything.


Do I need to use .initHistogram to construct a histogram for this raster layer? Or is there another reason QGIS crashes when I use provider.histogram?





No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...