Reprojecting Rasters and Vectors with GDAL: gdalwarp, ogr2ogr and Python

This post shows how to check the coordinate reference system (CRS) of a raster or vector file and reproject it with GDAL, first with the gdalwarp and ogr2ogr command-line tools and then with the same operations from Python. The examples move a WGS 84 elevation raster and a road shapefile into UTM zone 33N (EPSG:32633), but any EPSG code works the same way.

Step 1: find out what you have

Never reproject a file before you know its current CRS. A file with a missing or wrong CRS will reproject without complaint and land in the wrong place.

Rasters: gdalinfo

gdalinfo dem_wgs84.tif

Look for the Coordinate System is: section, which prints the CRS as WKT. Near the end of the WKT there is usually an ID["EPSG",...] entry with the code. Also note the origin and pixel size: for a geographic CRS the pixel size is in degrees, for a projected one it is usually in metres. If there is no coordinate system section at all, the file has no CRS, and you need to assign one (with -s_srs, below) rather than guess.

Vectors: ogrinfo

ogrinfo -so -al roads.shp

-al reports all layers and -so (summary only) skips the per-feature dump, which you almost never want on a real dataset. The summary includes the geometry type, feature count, extent and the layer's SRS as WKT. For a shapefile the CRS comes from the .prj file; if that file is missing, the layer has no CRS.

When you want to look up a code rather than a file, gdalsrsinfo EPSG:32633 prints the definition of that CRS in several formats.

Step 2: reproject a raster with gdalwarp

gdalwarp -t_srs EPSG:32633 -r bilinear \
    -co COMPRESS=DEFLATE -co PREDICTOR=3 -co TILED=YES \
    -overwrite dem_wgs84.tif dem_utm33n.tif

What each option does:

  • -t_srs EPSG:32633 is the target CRS. It accepts anything GDAL can parse: EPSG codes, WKT, PROJ strings or a .prj file. The source CRS is read from the input.
  • -r bilinear chooses the resampling method. Every output pixel is computed from input pixels, and this decides how.
  • -co passes creation options to the output driver, here GeoTIFF. COMPRESS=DEFLATE compresses losslessly, PREDICTOR=3 improves compression for floating-point data (use PREDICTOR=2 for integer data), and TILED=YES writes internal tiles, which makes reading parts of a large file faster.
  • -overwrite deletes and recreates the output if it already exists. Without it, gdalwarp writes into the existing file, which is rarely what you want when re-running a command.

The output format is guessed from the extension; use -of to set it explicitly.

Choosing the resampling method

The default is near (nearest neighbour) for most drivers. That is right for categorical data such as land cover classes, because it never invents values that did not exist in the input. For categorical data that you are also downsampling, mode picks the most common class in each output pixel.

For continuous data such as elevation or temperature, bilinear or cubic gives smoother results. average is a good choice when the output pixels are much larger than the input pixels. The full list on the gdalwarp page also includes cubicspline, lanczos, min, max, med, q1, q3, rms and sum.

Other options worth knowing

gdalwarp -s_srs EPSG:4326 -t_srs EPSG:32633 -tr 30 30 -r bilinear \
    -dstnodata -9999 -multi -wo NUM_THREADS=ALL_CPUS \
    -co COMPRESS=DEFLATE -co TILED=YES \
    -overwrite dem_wgs84.tif dem_utm33n.tif
  • -s_srs overrides the source CRS, for files where it is missing or wrong.
  • -tr 30 30 sets the output pixel size in target units, here 30 metres. Without it, gdalwarp estimates a resolution close to the input's.
  • -dstnodata sets the nodata value for the areas outside the original footprint, which appear because a reprojected rectangle is no longer a rectangle.
  • -multi and -wo NUM_THREADS=ALL_CPUS spread the work over several threads.

Step 3: reproject a vector with ogr2ogr

ogr2ogr -f GPKG -t_srs EPSG:32633 -nln roads roads_utm33n.gpkg roads.shp

Note the argument order: the destination comes before the source. This trips up nearly everyone at least once.

  • -f GPKG writes a GeoPackage, a single SQLite-based file that avoids the shapefile limits on field names, file size and the scattered sidecar files.
  • -t_srs transforms every geometry to the target CRS and records that CRS in the output.
  • -nln roads names the new layer. Without it, the layer takes the source layer name.

A GeoPackage can hold several layers. To add a second one to the same file, open it in update mode:

ogr2ogr -update -f GPKG -t_srs EPSG:32633 -nln rivers roads_utm33n.gpkg rivers.shp

Do not confuse -t_srs with -a_srs. -a_srs only assigns a CRS label without touching the coordinates. It is the right tool when the coordinates are already correct but the CRS is missing, and the wrong tool for everything else. As with gdalwarp, -s_srs overrides the source CRS when used together with -t_srs.

Step 4: the same in Python

The osgeo package exposes the command-line utilities as functions, with keyword arguments that mirror the flags. These come from the GDAL Python bindings, which must match the installed GDAL version; conda-forge or your system package manager is usually the least painful way to get a matching pair.

from osgeo import gdal

gdal.UseExceptions()

# Raster: equivalent of the first gdalwarp command
ds = gdal.Warp(
    "dem_utm33n.tif",
    "dem_wgs84.tif",
    dstSRS="EPSG:32633",
    resampleAlg="bilinear",
    creationOptions=["COMPRESS=DEFLATE", "PREDICTOR=3", "TILED=YES"],
)
ds = None  # close the dataset so everything is flushed to disk

# Vector: equivalent of the first ogr2ogr command
ds = gdal.VectorTranslate(
    "roads_utm33n.gpkg",
    "roads.shp",
    format="GPKG",
    dstSRS="EPSG:32633",
    reproject=True,
    layerName="roads",
)
ds = None

gdal.UseExceptions() should be the first thing you call. Without it, many GDAL functions report failure by printing an error and returning None, and your script continues until something unrelated breaks. With it, a failed operation raises a RuntimeError carrying GDAL's message. Recent versions of the bindings warn if you call neither UseExceptions() nor DontUseExceptions().

Setting the returned dataset to None is how you close it in the Python bindings. Until then, part of the output may still be in memory.

For a folder of rasters, a loop is enough:

from pathlib import Path

from osgeo import gdal

gdal.UseExceptions()

src_dir = Path("input")
dst_dir = Path("output_utm33n")
dst_dir.mkdir(exist_ok=True)

for src in sorted(src_dir.glob("*.tif")):
    dst = dst_dir / src.name
    ds = gdal.Warp(str(dst), str(src), dstSRS="EPSG:32633",
                   resampleAlg="bilinear",
                   creationOptions=["COMPRESS=DEFLATE", "TILED=YES"])
    ds = None
    print(f"{src.name} -> {dst}")

A note on axis order

Since GDAL 3.0, a spatial reference honours the axis order defined by the authority. For EPSG:4326 that order is latitude, longitude, not the longitude, latitude (x, y) that most GIS data and code assume.

gdalwarp and ogr2ogr deal with this for you when they read and write files. It bites when you transform coordinates yourself with osr. To keep the traditional x = longitude, y = latitude order, set the axis mapping strategy:

from osgeo import osr

osr.UseExceptions()

src = osr.SpatialReference()
src.ImportFromEPSG(4326)
src.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)

dst = osr.SpatialReference()
dst.ImportFromEPSG(32633)
dst.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)

ct = osr.CoordinateTransformation(src, dst)
x, y, _ = ct.TransformPoint(15.0, 52.0)  # longitude, latitude in; easting, northing out

Without the two SetAxisMappingStrategy() calls, the same TransformPoint(15.0, 52.0) treats 15 as the latitude and quietly returns a point somewhere else. If transformed points land in the wrong country, or in the ocean, check this first.

Summary

  • Inspect first: gdalinfo for rasters, ogrinfo -so -al for vectors.
  • gdalwarp -t_srs EPSG:xxxx -r <method> reprojects rasters. Use near or mode for categories, bilinear or cubic for continuous values, and -co COMPRESS=DEFLATE to keep files small.
  • ogr2ogr -f GPKG -t_srs EPSG:xxxx out.gpkg in.shp reprojects vectors. Destination first; -a_srs only labels, it does not transform.
  • In Python, call gdal.UseExceptions(), then use gdal.Warp() and gdal.VectorTranslate() with keyword arguments, and set datasets to None to close them.
  • When transforming coordinates with osr, use OAMS_TRADITIONAL_GIS_ORDER to get longitude, latitude order.

Comments

Popular posts from this blog

My Cloud Notes

My CSharp Notes