0

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
6
  • Could you set NaN into third palette entry (0,0,0,255) and mark that as NoData?
    – user30184
    Aug 28, 2017 at 18:52
  • Nope. Color Table only supports Byte or UInt16. However, NaN supports float datatype but not Byte or UInt16. So I had to write the file to Byte and it converts all the NaN elements into zeros.
    – J.Wang
    Aug 28, 2017 at 20:43
  • What does it matter if you know that all zeros mean NaN and you set metadata to show that as nodata?
    – user30184
    Aug 28, 2017 at 21:05
  • Good question. It is not a big issue but when I display it in GIS/RS software, I want those areas to be shown as NaN and I can easily get a percentage of each class.
    – J.Wang
    Aug 28, 2017 at 21:20
  • So your NaN does not mean missing data but it is a meaningful class? Sorry but I do not understand your use case yet.
    – user30184
    Aug 28, 2017 at 21:36

1 Answer 1

1

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

7
  • But I need to write it to a float type, right? The color table doesn't support float type. I wonder if there's another way to write the geotiff with color.
    – J.Wang
    Aug 28, 2017 at 23:26
  • can't you just use an integer, UInt16 ?
    – RutgerH
    Aug 29, 2017 at 2:18
  • Then I wouldn't be able to produce a colored geotiff?
    – J.Wang
    Aug 29, 2017 at 15:51
  • ct.SetColorEntry(255, (0,0,0,0))
    – RutgerH
    Aug 29, 2017 at 16:16
  • can you share your file, then I can give it a try
    – RutgerH
    Aug 29, 2017 at 16:20

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.