I have a raster layer and a polygon layer. Polygon layer is inside of raster layer and it's extent is smaller than raster layer. Some pixels of raster layer inside the polygon have negative value. I want to change the negative values based on maximum pixel value that is inside the polygon in GDAL or PyQGIS. So In first step I must find the max value based on below code:

r_lyr = QgsRasterLayer('.../aa.tif', 'Raster')
v_lyr= QgsVectorLayer('../bb.shp','bb',"ogr") 
v_ext = v_lyr.extent()
#(xmin, xmax, ymin, ymax) = (v_ext.xMinimum(), v_ext.xMaximum(), v_ext.yMinimum(), v_ext.yMaximum())

provider = r_lyr.dataProvider()
r_ext = provider.extent()

rows = r_lyr.height()
cols = r_lyr.width()

block = provider.block(1, v_ext, cols, rows)
lst = []
for i in range(rows):
    for j in range(cols):
        #print (block.value(i,j)),
max_v = max(lst)

In second step it is important to get pixels inside the polygon and then change them to maximum value.

In @xunilk's answer to Changing pixel values of raster data from QGIS python plugin there is a way to change the pixel value but by this answer it is possible to do for full extent of raster layer.

How can I merge my code with @xunilk's code for doing it?

  • 1
    If you wish to also ask about GDAL then please do that in a separate question so that this one can remain focused on PyQGIS.
    – PolyGeo
    Oct 21, 2019 at 21:15


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.