7

I have a function that reads a multi-band image in as a raster brick object, iterates through the bands doing various calculations, and then writes the raster out as a new .tif. All of this works fine, but the file size of the new image file is roughly four times greater (I assume because the original image has 4 bands). I'm wondering if there's a parameter in the writeRaster() function that I'm unaware of, or if there's some other way I can ensure that the output image is basically the same file size as the input.

Original file size is 134 MB; output ranges from 471 to 530 MB or so, depending on format.

Simplified code:

library(rgdal)
library(raster)

path = "/Volumes/ENVI Standard Files/"
img = "qb_tile.img"

imageCorrection = function(path, img){
  raster = brick(paste0(path, img))   
  raster = reclassify(raster, cbind(0, NA))  

  for(i in 1:nlayers(raster)){   
    raster[[i]] = raster[[i]] - minValue(raster[[i]]) 
  }
  writeRaster(raster, paste0(path,img,"_process.tif"), format = "GTiff", overwrite=TRUE)
}
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
Danple
  • 111
  • 2
  • 6
  • So the inputs and outputs have exactly the same number of pixels and bands? So its either that your .img file is using better compression than your .tiff, or the .img file is storing at a lower precision (like 8-bit ints) and your .tiff is storing 4-byte floats.... Or both. What does sp::GDALinfo have to say about your files? – Spacedman Feb 04 '17 at 16:00
  • Yes that seems to be the issue. GDALinfo indicates that the output is written as FLT4S while the input comes in as INT2U. I've tried changing the datatype of the output, but anything other than FLT4S creates a blank image (data = 0-1). – Danple Feb 04 '17 at 17:29
  • https://stat.ethz.ch/pipermail/r-sig-geo/2015-January/022246.html – Danple Feb 04 '17 at 21:54

1 Answers1

11

You can set the default datatype for writing rasters with the rasterOptions() as follows:

rasterOptions(datatype="INT2U")

Or directly in the writeRaster call:

writeRaster(yourRas, "path/to/raster/", dataType="INT2U", options="COMPRESS=LZW")

Also notice the options argument where you can specify compression.

Usually when I export integer rasters from R, I make sure that I really have integers and not floats, since this can result in an empty raster. Try the following before exporting:

ras <- as.integer(ras)

Please note: Also check for negative values in your raster. Try INT2S if you have values below zero.

maRtin
  • 6,336
  • 11
  • 43
  • 66
  • 4
    I'd like to add that all options and properties of the output raster formats can be found [here](http://gdal.org/formats_list.html) – loki Oct 19 '17 at 09:45
  • https://search.r-project.org/CRAN/refmans/raster/html/writeRaster.html Here are more rasterOptions() to add to the options argument. I found really useful to just default it to no-compression like this: options="COMPRESS=NONE" – Santiago Sotelo Oct 08 '22 at 20:45