I'm trying to use GDAL/python API to open a raster, do some math, then write the two resulting arrays as rastes. One is to be an 8-bit raster and the other 16-bit signed. However, only the 8-bit raster is coming out correctly. The 16-bit raster comes back as a raster of 0's. Here is the relevant code:
import numpy as np
import gdal
gdal.UseExceptions() # enable exceptions to report errors
drvtif = gdal.GetDriverByName("GTiff")
# open raster, read as array, do some math, return two arrays: arr1 and arr2
# arr1 and arr2 are both float32, though not necessary
print np.unique(arr1)
# prints [-15000, -10000, ..., 10000]
print np.unique(arr2)
# prints [1, 2, ..., 11]
# now write arr1 and arr2 as .tif:
outNDVI = '/path/to/outputs/output1.tif':
ndvidrv = drvtif.Create(outNDVI, ncols, nrows, 1, 3) # 3 = 16 bit signed
ndvidrv.SetGeoTransform(hc_gt)
ndvidrv.SetProjection(proj2)
ndvidrv.GetRasterBand(1).SetNoDataValue(-15000)
ndvidrv.GetRasterBand(1).WriteArray(arr1)
del ndvidrv
outQA = '/path/to/outputs/output2.tif'
qadrv = drvtif.Create(outQA, ncols, nrows, 1, 1) # 1= 8 bit
qadrv.SetGeoTransform(hc_gt)
qadrv.SetProjection(proj2)
## qadrv.GetRasterBand(1).SetNoDataValue(-15000)
qadrv.GetRasterBand(1).WriteArray(arr2)
del qadrv
outQA turns out as expected, with the correct range of values and correct projection, but outNDVI is just a raster of 0's (in the correct projection). The values should range from -10000 to 10000 (with NoData= -15000).
Any thoughts?
Deleting ndvidrv seemed to do the trick and I've updated above to reflect that.
1 Answer 1
I think you might need to flush the band out and then close ("delete") the datasource try adding:
ndvidrv.GetRasterBand(1).FlushCache() ## flush to finish writing
del ndvidrv
-
2@user20408
del ndvidrv
is sufficient. The wiki notes that not all drivers support flushing and that it doesn't guarantee that the data are written to disk, so the preferred method is to deallocate (i.e.del ndvidrv
orndvidrv = None
)user2856– user28562016年03月11日 08:59:58 +00:00Commented Mar 11, 2016 at 8:59 -
1Yes, it is enough
del ndvidrv
orndvidrv = None
afterndvidrv.GetRasterBand(1).WriteArray(arr1)
.xunilk– xunilk2016年03月11日 10:19:56 +00:00Commented Mar 11, 2016 at 10:19 -
Thanks Josh, Luke, @xunilk... del ndvidrv worked and I've updated the question. Thank you alluser20408– user204082016年03月11日 16:06:52 +00:00Commented Mar 11, 2016 at 16:06
qadrv
)