My input raster consists of multiple layers, each with an image area surrounded by no data values. These layers don't overlap completely, and I am trying to output a file which consists of only the intersection of all bands (the zone which has no NoData values on any layer).
The following works for a few layers, but not for the 50+ that I have in my real files (at least 3000x3000 pixels):
library(raster)
fin = "D:\\temp\\all_modes.pix"
fout = "D:\\temp\\test.pix"
inbands = stack(fin, bands = c(3:20))
NAvalue(inbands) = 0
# Not great:
#out = all(is.na(inbands) == FALSE) * inbands
#writeRaster(out, filename=fout, format="PCIDSK", dtype="INT2U", overwrite=TRUE, NAflag=0)
# A little better:
#mymask = all(as.logical(inbands))
#mask(inbands, mymask, filename=fout, format="PCIDSK", dtype="INT2U", overwrite=TRUE, NAflag=0)
# Even better, don't need to keep everything (but still not efficient):
#trim(all(as.logical(inbands)) * inbands, filename=fout, format="PCIDSK", dtype="INT2U", overwrite=TRUE, NAflag=0)
# Even better, calculations get smaller as we progress (is it possible to do even better?)
for(i in 1:nlayers(inbands)){
band_i = subset(inbands, i)
inbands = trim(as.logical(band_i) * inbands)
}
writeRaster(inbands, filename=fout, format="PCIDSK", dtype="INT2U", overwrite=TRUE, NAflag=0)
Any ideas on how to do this more efficiently / get it working with a large number of layers?