terra writeRaster modifies raster values when writing a jpeg2000 file

61 Views Asked by At

I'm trying to save a terra raster in jpeg2000 format. The only jpeg2000 driver I know of for writeRaster is JP2OpenJPEG (are there others?). But it seems to modify the raster values:

r <- rast(system.file("ex/logo.tif", package="terra"))   
rjp2 <- writeRaster(r,"r.jp2",filetype="JP2OpenJPEG")

all(values(r)==values(rjp2))
# [1] FALSE

plot(r)
plot(rjp2)

The colors have been modified (255 values disappeared, NA values appeared, colors shifted). I've tried adding several options, but the values are always changed when saving:

rjp3 <- writeRaster(r,"r.jp3",filetype="JP2OpenJPEG",
                    gdal=c("QUALITY"="100","REVERSIBLE"="YES",
                    "YCC"="NO","YCBCR420"="NO"))
all(values(r)==values(rjp3))
# [1] FALSE

Are there any options I need to set to save a JPEG2000 file without changing colors? Or is this a bug? A missing feature?

2

There are 2 best solutions below

1
Robert Hijmans On

You can do

rjp <- writeRaster(r, "r2.jp2", filetype="JP2OpenJPEG", overwrite=TRUE,
                  NAflag=NA,  
                  gdal=c("QUALITY=100","REVERSIBLE=YES"))

That is, you need to specify that you do not want a NA flag; and you need to correctly format the gdal options to avoid the data quality loss normally associated with JPEG.

1
Jean-Luc Dupouey On

I'm experiencing difficulties saving some rasters in jp2. Here's an example, with volcano data:

vo <- rast(volcano)
vojp2 <- writeRaster(vo,filename="vo.jp2", 
                     wopt=list(filetype="JP2OpenJPEG",
                               gdal=c("QUALITY=100","REVERSIBLE=YES")))

# Error: [writeRaster] mem copy create failed for JP2OpenJPEG
# In addition: Warning message:
# JP2OpenJPEG driver only supports creating Byte, GDT_Int16, GDT_UInt16,
# GDT_Int32, GDT_UInt32 (GDAL error 6)