4

I'm trying to do a min-max stretch on a raster and save it using gdal_translate. The syntax requires to enter source min and max raster values as arguments for a -scale option:

-scale [src_min src_max [dst_min dst_max]]

My goal is to populate those src_min and src_max automatically to do conversions in a batch.

The docs even state that they are computed if ommited:

Rescale the input pixels values from the range src_min to src_max to the range dst_min to dst_max. If omitted the input range is automatically computed from the source data.

But in reality gdal_translate -scale 0 65535 src_16b.tif dst_16b.tif does not produce correct results. What may be wrong?

3
  • What result does it produce and what result would you like to get? The whole sentense in the documentation seems to be Rescale the input pixels values from the range src_min to src_max to the range dst_min to dst_max. If omitted the output range is 0 to 255. If omitted the input range is automatically computed from the source data. Thus your command should do the same than -scale 0 65535 0 255. Plain -scale should then convert from auto-min auto-max into range 0-255.
    – user30184
    Commented Aug 27, 2018 at 19:23
  • I have 10 bits of useful data and I'd like to stretch it along 16 bit. This is why I'm not satisfied with a plain -scale - it defaults output range to 8 bit so I'll loose information if I do it.
    – Basile
    Commented Aug 27, 2018 at 20:02
  • 1
    Gdal_translate does not support directly what you are after. You'll need some Python for reading min and max from the source and passing them to -scale.
    – user30184
    Commented Aug 27, 2018 at 20:21

1 Answer 1

2

You could solve it using a Bash script and Awk:

minmax=$(gdalinfo -mm file.tif|awk -F= '/Computed Min/ {print $2}')
min=$(echo $minmax|awk -F, '{print $1}')
max=$(echo $minmax|awk -F, '{print $2}')
gdal_translate -scale $min $max 0 65535 file.tif out.tif
1
  • The output of the 'gdalinfo -mm' command has changed. If failing with a max value of 'Max', the first line should be changed to: minmax=$(gdalinfo -mm file.tif|awk -FMin/Max= '/Computed Min/ {print $2}')
    – Sebastian
    Commented Mar 6, 2023 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.