3

I am attempting to export data of varying scales into GeoTIFF images...a new method for me. The problem I'm running into is when using the GDT_Byte pixel type, data values < 0 and > 256 are not represented (they are black or white), and when I use GDT_Float32 or other pixel types, I get white, or transparent images. How can I represent a wider range of values?

This example creates an image with values of zero of less being black, and greater then 256 being white. Alternate pixel types result in transparent images.

from osgeo import gdal, osr, ogr
import numpy as np
#create a bogus grid
mag_grid = np.arange(-500, 500, .1).reshape((100, 100))
lats = np.arange(-10,90,1.)
lons = np.arange(-10,90,1.)

xres = lons[1] - lons[0]
yres = lats[1] - lats[0]
ysize = len(lats)
xsize = len(lons)
ulx = lons[0] - (xres / 2.)
uly = lats[-1] - (yres / 2.)


driver = gdal.GetDriverByName('GTiff')
ds = driver.Create('output.tif',
               xsize, ysize, 1, gdal.GDT_Byte, )
##################################
#pixel type of gdal.GDT_Float32 results in transparent image
##################################

# this assumes the projection is Geographic lat/lon WGS 84
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
ds.SetProjection(srs.ExportToWkt())
gt = [ulx, xres, 0, uly, 0, yres ]
ds.SetGeoTransform(gt)
outband=ds.GetRasterBand(1)
outband.SetStatistics(np.min(mag_grid), np.max(mag_grid), np.average(mag_grid), np.std(mag_grid))
outband.WriteArray(mag_grid)
ds = None
5

Use gdal.GDT_Float32 not GDT_Byte. The Byte datatype is unsigned 8 bit integer. That means it can only hold values from 0-255. If you try to include values <0 or >255 they will overflow, i.e -1 will be converted to 255, -2 to 254 and 256 to 0 and 257 to 1 etc...

Your code works fine with Float32 datatype, see image below.

enter image description here

You may be seeing "values of zero of less being black, and greater then 256 being white" due to the overflow and transparent images if the software you used to view the image didn't understand how to display it. See the same image as displayed by Windows PhotoViewer below.

enter image description here

Use a GIS (or image software that can apply a basic display stretch) to view a GeoTIFF, not a simple image viewer and make sure you use an appropriate datatype for the data you want to store.

  • This is correct. Besides, for simple image viewing programs, you may want to add a color table to the Geotiff. Embedding this kind of information helps those programs to display your image. Take a look at this gis.stackexchange.com/a/181882/66527 (sorry for the auto reference) – Akhorus Feb 23 '16 at 13:26

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.