gdalUtils icon indicating copy to clipboard operation
gdalUtils copied to clipboard

scale argument in gdal_translate() is wrongly built for multiband images

Open aloboa opened this issue 5 years ago • 2 comments

#Goal: use gdal_transfom() to stretch floating valuesfrom 2% - 98%
quantiles to the 1- 255 range (to leave 0 for nodata) and write as
Byte (uint8)
#Test image:
m <- matrix(rnorm(n=10^4,m=0,sd=2),nrow=100)
m[1:10,] <- NA
imatest <- raster(m)
cellStats(imatest,range)
imatest <- brick(imatest,imatest*2,imatest+10)
extent(imatest) <- c(0,100,0,100)
projection(imatest) <- CRS("+init=epsg:25831")
imatest

class       : RasterBrick
dimensions  : 100, 100, 10000, 3  (nrow, ncol, ncell, nlayers)
resolution  : 1, 1  (x, y)
extent      : 0, 100, 0, 100  (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:25831 +proj=utm +zone=31 +ellps=GRS80
+towgs84=0,0,0,0,0,0,0 +units=m +no_defs
data source : in memory
names       :    layer.1,    layer.2,    layer.3
min values  :  -7.623476, -15.246953,   2.376524
max values  :   7.618672,  15.237344,  17.618672

writeRaster(imatest,filename="imatest",format="GTiff",NAflag=0,overwrite=TRUE)

#Calculate parameters for scale in the form:
#inmin1 inmax1 outmin1 outmax1 inmin2 inmax2 outmin2 outmax2 inmin3
inmax3 outmin3 outmax3

qt <- quantile(imatest,probs=c(0.02,0.98),na.rm=TRUE)
 qt

               2%       98%
layer.1 -4.060864  4.061431
layer.2 -8.121729  8.122863
layer.3  5.939136 14.061431

scal <- 1
for(i in 1:nlayers(imatest)){
    scal <- c(scal,c(qt[i,],c(1,255)))
}
scal <- scal[-1]
scal

        2%        98%                               2%        98%
                         2%
 -4.060864   4.061431   1.000000 255.000000  -8.121729   8.122863
1.000000 255.000000   5.939136
       98%
 14.061431   1.000000 255.000000

gdal_translate(src_dataset="imatest.tif",
               dst_dataset="imateststretchgdal.tif",
               ot="Byte",scale=scal)
# Warning message:
#   In system(cmd, intern = TRUE) :
#   running command '"C:\Program Files\QGIS
3.4\bin\gdal_translate.exe" -scale -4.03716844947439 4.10004776627608
1 255 -8.07433689894878 8.20009553255217 1 255 5.96283155052561
14.1000477662761 1 255 -ot "Byte" -of "GTiff" "imatest.tif"
"imateststretchgdal.tif"' had status 1
#
#Note scale is wrong, it should repeat "-scale" for each band
#-scale -4.03716844947439 4.10004776627608 1 255 -scale
-8.07433689894878 8.20009553255217 1 255 -scale 5.96283155052561
14.1000477662761 1 255

aloboa avatar Nov 22 '19 07:11 aloboa