Skip to content

Instantly share code, notes, and snippets.

@cjtu
Created June 26, 2025 00:08
Show Gist options
  • Save cjtu/01330eb126a94391c7641256033cb3cf to your computer and use it in GitHub Desktop.
Save cjtu/01330eb126a94391c7641256033cb3cf to your computer and use it in GitHub Desktop.
Unscale an image with GDAL

Unscaling a DEM with GDAL (gdal_translate plus a VRT)

Some image data like the Moon SLDEMs from https://pgda.gsfc.nasa.gov/products/67 have scale factors applied for image compression. The slope images are supplied as Int format and the label states to multiply by scale of 0.0015 and offest of 45 to convert to slope in degrees.

Often this metadata is machine readable and applied automatically but in this case QGIS doesn't see it.

To manually attach the scale/offset with gdal we can make a VRT (a simple "virtual" image that doesn't copy the original but points to it and adds this metadata):

gdal_translate -a_scale 0.0015 -a_offset 45 SLDEM2015_64_SL_90S_90N_000_360.JP2 tmp.vrt

Now reading tmp.vrt into GIS shows units in degrees (note you must keep the original image and the .vrt in the same folder but select the .vrt in GIS).

To make a new full copy of the image with the scale factor applied, we can use gdal_translate on the new .vrt. From gdal docs:

-a_offset : Set band offset value. No modification of pixel values is done. Note that the -unscale does not take into account -a_offset. You may for example specify -scale 0 1 <offset+scale> to apply a (offset, scale) tuple, for the equivalent of the 2 steps: gdal_translate input.tif tmp.vrt -a_scale scale -a_offset offset followed by gdal_translate tmp.vrt output.tif -unscale

So now we can make a new image, but note we'll have to give a new output type -ot to represent our floating point slopes rather than the original int format (again: docs.

-unscale: Apply the scale/offset metadata for the bands to convert linearly-scaled values to unscaled values. It is also often necessary to reset the output datatype with the -ot switch.

gdal_translate -unscale -ot Float32 tmp.vrt SLDEM2015_64_SL_90S_90N_000_360.tif
@cjtu
Copy link
Author

cjtu commented Jun 26, 2025

To test making a new image when the raster is very large, set target resolution (in georeferenced units) with -tr to make a downsampled image to start. So the last command to make a 1 degree/pixel (360x180) image would be:

gdal_translate -unscale -ot Float32 -tr 1 1 tmp.vrt test.tif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment