How to open Landsat bit value quality flags rasters in R?

80 views Asked by At

Landsat QA rasters are stored in 8bit .tiff files. The flags are encoded by the bit position. But I can not extract them using terra.

I am trying to retrieve the bit position with this code:

library(terra)

toBinary <- function(i){
  valuesbin = paste0(as.integer(rev(intToBits(i)[1:8])), collapse = "")
  valuesbin = unlist(strsplit(valuesbin, split = ""))
  as.numeric(valuesbin)
  
}


qa = rast('./qarast.tiff')
qa = app(qa,toBinary)

but it crash with:

Error: [app] the number of values returned by 'fun' is not appropriate

How can I use this quality flags in R? Is there any specific library less error prone?

Cheers

1

There are 1 answers

2
Robert Hijmans On

toBinary is not vectorized

toBinary <- function(i){
  valuesbin = paste0(as.integer(rev(intToBits(i)[1:8])), collapse = "")
  valuesbin = unlist(strsplit(valuesbin, split = ""))
  as.numeric(valuesbin) 
}

toBinary(1:2)
#[1] 0 0 0 0 0 0 0 1

This is a vectorized function

toB <- function(x) {
    t(sapply(x, toBinary))
}
toB(1:2)
#    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,]    0    0    0    0    0    0    0    1
#[2,]    0    0    0    0    0    0    1    0

And use it:

r <- rast(ncol=5, nrow=5, vals=c(NA, 1:24))
a <- app(r, toB)
#class       : SpatRaster 
#dimensions  : 5, 5, 8  (nrow, ncol, nlyr)
#resolution  : 72, 36  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 
#source(s)   : memory
#names       : lyr.1, lyr.2, lyr.3, lyr.4, lyr.5, lyr.6, ... 
#min values  :     0,     0,     0,     0,     0,     0, ... 
#max values  :     0,     0,     0,     1,     1,     1, ...