[GIS] Min-max stretch using gdal_translate in a batch

gdalgdal-translatehistogram

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?

Best Answer

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
Related Question