Rasterio Geotiff Coordinate Translation

Question:

I have some geotiff files but the coordinates are slightly off. I want to use rasterio’s API (or other python geo API like pygdal) to geometrically translate (shift) the image. For example, how do I move the image’s coordinates ‘north’ by a single pixel width.

When displayed with a tool like qgis the image should be exactly the same but shifted up a few pixels.

Asked By: Alex Ethier

||

Answers:

Modifying the georeference of a geotiff is a really simple task. I will show how to do it using the gdal python module. First, you should have a look at the GDAL data model with particular focus on the ‘affine geotransform‘.

I will assume that your raster is not skewed or rotated, so that your geotransform looks something like

gt = (X_topleft, X_resolution, 0, Y_topleft, 0, Y_resolution)

With this geotransform, the raster coordinate (0,0) has a top-left corner at (X_topleft, Y_topleft).

To shift the raster position, you need to change X_topleft and Y_topleft.

import gdal

# open dataset with update permission
ds = gdal.Open('myraster.tif', gdal.GA_Update)
# get the geotransform as a tuple of 6
gt = ds.GetGeoTransform()
# unpack geotransform into variables
x_tl, x_res, dx_dy, y_tl, dy_dx, y_res = gt

# compute shift of 1 pixel RIGHT in X direction
shift_x = 1 * x_res
# compute shift of 2 pixels UP in Y direction
# y_res likely negative, because Y decreases with increasing Y index
shift_y = -2 * y_res

# make new geotransform
gt_update = (x_tl + shift_x, x_res, dx_dy, y_tl + shift_y, dy_dx, y_res)
# assign new geotransform to raster
ds.SetGeoTransform(gt_update)
# ensure changes are committed
ds.FlushCache()
ds = None
Answered By: Logan Byers
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.