Python-gdal write a GeoTiff with binary color and NaN

1.2k views Asked by At

I am generating a simple two-class (binary) geotiff from a numpy array with 3 values: 1, 2, and NaN. I wanted to display the geotiff with distinct colors so I used the color table. However, color table only supports the Byte or UInt16 datatype, which will convert the NaN to zeros.

Is there a way to write a binary geotiff including the NaN with colors? Thanks.

filename = 'test.tif'
ds = gdal.Open(filename, gdal.GA_ReadOnly)
outfile = 'classify.tif'
driver = gdal.GetDriverByName("GTiff")
outdata = driver.Create(outfile, cols, rows, 1, gdal.GDT_Byte)     
outdata.SetGeoTransform(ds.GetGeoTransform())
outdata.SetProjection(ds.GetProjection())
outband = outdata.GetRasterBand(1)
ct = gdal.ColorTable()
ct.SetColorEntry(1, (0,0,102,255))      
ct.SetColorEntry(2, (0,255,255,255))    
outband.SetColorTable(ct)
outband.WriteArray(result)
outband.FlushCache() 
outdata = None
outband = None
ds = None
1

There are 1 answers

0
Wilmar van Ommeren On

Byte only accepts 8-bit values so NaNs are not supported. One solution is to convert the NaNs to an 8-bit value (like 255) and add this line of code (before outband.WriteArray(result)):

outband.SetNoDataValue(255)

All 255-values in your created array will now be seen as nodata.