Search code examples
plotmayavimayavi.mlab

how to plot geotiff data in python by imshow


I have a geotiff raster data sets with elevation data init. No data in raster image is defined by -9999. When I try to make a plot with this code below:

import gdal
import numpy as np
from mayavi import mlab

ds = gdal.Open('data.tif')
dem = ds.ReadAsArray()
gt = ds.GetGeoTransform()
ds = None

mlab.imshow(dem)
mlab.colorbar()
mlab.show()

The problem is when I make a plot, it also plot nodata value. My question is how do I exclude -9999 value (or select value range to plot) from raster image.

The link to data is:

https://drive.google.com/file/d/0B2rkXkOkG7ExR1VsVW5HQXBhSDQ/view?usp=sharing


Solution

  • In case you still needed a clean solution to this question, I believe what you are looking for is a masked array from numpy.ma like:

    import gdal
    import numpy as np
    from mayavi import mlab
    
    ds = gdal.Open('data.tif')
    dem = ds.ReadAsArray()
    
    msk = dem==-9999 # boolean array with True at elements to be masked
    dem = np.ma.array(data=dem, mask=msk, fill_value=np.nan)
    
    gt = ds.GetGeoTransform()
    ds = None
    
    mlab.imshow(dem)
    mlab.colorbar()
    mlab.show()