[GIS] Python-gdal write a GeoTiff with binary color and NaN

gdalgeotiff-tiffpython

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?

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

Best Answer

you can convert the NaNs to a real value (e.g. 255) and then set your Geotiffs NoData value to this real value.

dst_ds.GetRasterBand(1).SetNoDataValue(255)

More info on the conversion can be found here: Reclassify a raster value to -9999 and set it to the nodata value using python and or gdal