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
-
Could you set NaN into third palette entry (0,0,0,255) and mark that as NoData?user30184– user301842017年08月28日 18:52:57 +00:00Commented 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– J.Wang2017年08月28日 20:43:58 +00:00Commented 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– user301842017年08月28日 21:05:38 +00:00Commented 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– J.Wang2017年08月28日 21:20:58 +00:00Commented 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– user301842017年08月28日 21:36:40 +00:00Commented Aug 28, 2017 at 21:36
1 Answer 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
-
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– J.Wang2017年08月28日 23:26:42 +00:00Commented Aug 28, 2017 at 23:26
-
can't you just use an integer, UInt16 ?RutgerH– RutgerH2017年08月29日 02:18:30 +00:00Commented Aug 29, 2017 at 2:18
-
Then I wouldn't be able to produce a colored geotiff?J.Wang– J.Wang2017年08月29日 15:51:56 +00:00Commented Aug 29, 2017 at 15:51
-
ct.SetColorEntry(255, (0,0,0,0))RutgerH– RutgerH2017年08月29日 16:16:20 +00:00Commented Aug 29, 2017 at 16:16
-
can you share your file, then I can give it a tryRutgerH– RutgerH2017年08月29日 16:20:15 +00:00Commented Aug 29, 2017 at 16:20