4

I'd like to change the value of a pixel in a QGIS raster layer. But the following Python code cannot do it.

r_layer = iface.activeLayer()
provider = r_layer.dataProvider()
from osgeo import gdal 
raster = gdal.Open(str(provider.dataSourceUri()))
np_array = raster.ReadAsArray()

np_array[1,2] = 5 

raster.GetRasterBand(1).WriteArray(np_array, 0, 0)
raster.GetRasterBand(1).FlushCache()
1
  • Are you sure it's not changed? I have code that does pretty much that using GDAL in C# and ArcObjects (lots more lines that you have) and have noted that the value doesn't appear changed until the pyramids are rebuilt and the layer removed and added again to refresh the cache. I open using OpenShared but I think that that would matter little. May 29, 2017 at 6:00

1 Answer 1

5

I finally found the solution to my problem. The array can be written after I added the option gdal.GA_Update to Open(...)

r_layer = iface.activeLayer()
provider = r_layer.dataProvider()
from osgeo import gdal 
raster = gdal.Open(str(provider.dataSourceUri()), gdal.GA_Update)
band = raster.GetRasterBand(1)

np_array = band.ReadAsArray()
np_array[0,0] =255
band.WriteArray(np_array)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.