Search code examples
rmatrixbinaryraster

Converting band interleaved by pixel binary files into raster grids


I have a BIP binary file https://drive.google.com/open?id=0BwkLXkUMkLd4SnBmUHNmMW5CcDg with the following information:

ncol <- 193 
nrow <- 94  
xmin <- -180
xmax<-  180
ymin <- -88.542000
ymax <- 88.542000

The file has 365 bands, I want to be able to convert them into raster grids (raster stack). I can read the files in R, but I don't know how to deal with the bands. Here is what I have done so far:

cnt <- ncol*nrow*365
data <- readBin(file,what= "double", n=cnt, size=4,endian=.Platform$endian)
data.m <- matrix(data, ncol=193, nrow=94) # I don't know how to add the bands
data.r <- raster(data.m, xmn=xmin, xmx=xmax, ymn=ymin, ymx=ymax)
plot(data.r)

Solution

  • Use raster::brick as it is a function to create multi-band rasters based on files with multiple bands including BIL and BIP. If it by chance does not recognize your georef data, you can input it as arguments when reading the file: ncols=193, xmn=-180, xmx=180, ymn=-88.542000, ymx=88.542000, nl=365.

    Here is an example implementation based on the file you provided. Since it was not recognized as a BIP file, you first have to read it and convert it into an 3D array. Then you can simply use it with the brick command to create the raster stack. Now, the tricky thing is that the dimensions of the data file where in an order incompatible with the brick command, so you have to transpose the dimensions using the aperm function. After that, it is straight forward to convert the entire array into a georeferenced stack.

    wd="D:/temp/"
    setwd(wd)
    library(raster)
    ncol <- 193 
    nrow <- 94  
    nbands <- 365
    cnt <- ncol*nrow*nbands
    data <- readBin("Tavg.dat",what= "double", n=cnt, size=4,endian=.Platform$endian)
    data2=array(data,c(nbands, ncol, nrow))
    data2 <- aperm(data2, c(3,2,1)) #for transposing
    raster_brick=brick(data2, xmn=-180, xmx=180, ymn=-88.542000, ymx=88.542000)
    plot(raster_brick[[1]])
    

    Here is the first band image: enter image description here