2

I am playing around with gdal and numpy to create a random grid in QGIS. The following code sniplet creates an grid an tries to load into QGIS. But the the result layer is invalid. If I run the script a second time, right after the first run, the layer is created and loaded without any problem...do I miss something in my code sniplet?

from osgeo import gdal
import numpy as np

fn = "d:/newgrid.tif"
rasterband = np.random.random((10,10))
driver = gdal.GetDriverByName("GTiff")
ds = driver.Create(fn, xsize=10, ysize=10, bands=1, eType=gdal.GDT_Float32)
ds.GetRasterBand(1).WriteArray(rasterband)
rlayer = iface.addRasterLayer(fn)

The error message on the first run is: Invalid Layer : GDAL provider Cannot open GDAL dataset d:/newgrid.tif: `d:/newgrid.tif' not recognized as a supported file format. Raster layer Provider is not valid (provider: gdal, URI: d:/newgrid.tif

3

1 Answer 1

1

Compared to https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html#create-raster-from-array FlushCache() is missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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