I'm opening and reading the one band TIFF file as an array with the below code:
ds = gdal.Open('mosaic.tif')
array = ds.ReadAsArray()
Then I'm doing some operations on the array including normalizing the pixel values between 0 and 1. Then I'm writing the array (crop_sufficiency) to TIFF with the below code:
arr_type = gdal.GDT_Float64
driver = gdal.GetDriverByName("GTiff")
out_ds = driver.Create('sufficiency_map.tif', crop_sufficiency.shape[1], crop_sufficiency.shape[0], 1, arr_type)
out_ds.SetProjection(ds.GetProjection())
out_ds.SetGeoTransform(ds.GetGeoTransform())
band = out_ds.GetRasterBand(1)
band.WriteArray(crop_sufficiency)
band.FlushCache()
band.ComputeStatistics(False)
I load the tiff into QGIS but all the pixel values are 0, which I know not to be the case because I'm looking at the max and mean values of the numpy array which are not 0. The dtype is correct. I'm not sure where I'm going wrong.
1 Answer 1
I fixed it, just posting the answer here in case anyone comes across a similar thing in the future, since I was following a first result tech blog post example I assume someone might.
The below code works.
arr_type = gdal.GDT_Float64
driver = gdal.GetDriverByName("GTiff")
out_ds = driver.Create('sufficiency_map12.tif', crop_sufficiency.shape[1], crop_sufficiency.shape[0], 1, arr_type)
out_ds.GetRasterBand(1).WriteArray(crop_sufficiency)
out_ds.SetProjection(ds.GetProjection())
out_ds.SetGeoTransform(ds.GetGeoTransform())
out_ds.GetRasterBand(1).WriteArray(crop_sufficiency)
out_ds = None
-
Better yet, use a context manager, like
with driver.Create(...) as out_ds:
dbaston– dbaston2025年01月23日 00:33:15 +00:00Commented Jan 23 at 0:33 -