python4oceanographers

Turning ripples into waves

Plotting geotiff with cartopy

This post is a quick example on how to read geotiff images with GDAL and plot them with Cartopy.

The image, and most of the code, is from Kelsey Jordahl original notebook. The main difference is that I compressed the geotiff with:

gdal_translate -co "TILED=YES" -co "COMPRESS=JPEG" manhattan.tif manhattan2.tif

First: read the geotiff image with GDAL.

In [2]:
from osgeo import gdal, osr

gdal.UseExceptions()


fname = './data/manhattan2.tif'

ds = gdal.Open(fname)
data = ds.ReadAsArray()
gt = ds.GetGeoTransform()
proj = ds.GetProjection()

inproj = osr.SpatialReference()
inproj.ImportFromWkt(proj)

print(inproj)
PROJCS["NAD83 / UTM zone 18N",
    GEOGCS["NAD83",
        DATUM["North_American_Datum_1983",
            SPHEROID["GRS 1980",6378137,298.2572221010002,
                AUTHORITY["EPSG","7019"]],
            AUTHORITY["EPSG","6269"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4269"]],
    PROJECTION["Transverse_Mercator"],
    PARAMETER["latitude_of_origin",0],
    PARAMETER["central_meridian",-75],
    PARAMETER["scale_factor",0.9996],
    PARAMETER["false_easting",500000],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]],
    AUTHORITY["EPSG","26918"]]

Second: convert the WKT projection information to a cartopy projection.

In [3]:
import cartopy.crs as ccrs


projcs = inproj.GetAuthorityCode('PROJCS')
projection = ccrs.epsg(projcs)
print(projection)
_EPSGProjection(26918)

Third (and last): the figure.

In [4]:
import matplotlib.pyplot as plt

subplot_kw = dict(projection=projection)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw=subplot_kw)

extent = (gt[0], gt[0] + ds.RasterXSize * gt[1],
          gt[3] + ds.RasterYSize * gt[5], gt[3])

img = ax.imshow(data[:3, :, :].transpose((1, 2, 0)), extent=extent,
                origin='upper')