2

I currently write a code for automatic reading sentinel 2 data (JPEG2000 format), clipping it and save it a .tif. I use the language R and my system is Windows 10.

My problem is to install properly a gdal driver for JPEG2000. I tried to install the OpenJpeg library, but the installation is very poorly documented.

Can someone explain how to install the OpenJpeg library to use in R or has another suggestion how to read the JPEG2000 in R ?

2
  • If you only want to clip and convert the files, you could use gdal directly and avoid any rgdal troubles
    – Val
    Commented Jun 5, 2017 at 9:15
  • Should I use gdal in the OSGEO shell? (Sorry an absolute beginner)
    – Lau
    Commented Jun 5, 2017 at 10:38

2 Answers 2

3

Here are a couple of examples of using gdal from R but without rgdal (this is assuming Windows OS):

This is a really simple example, with just one image. You can use a vector of images (for instance as returned by list.files) and build multiple calls at once.

# your image is 'C:/Sentinelbands/B01.jp2'

Case 1: you have your gdal distribution available in your path:

cmd <- 'gdal_translate C:/Sentinelbands/B01.jp2 C:/Sentinelbands/B01.tif'

shell(cmd) #Linux use system()

Case 2: using the OSGEO distribution

# assume your OSGEO distribution is at C:/OSGeo4W64

cmd <- 'C:/OSGeo4W64/OSGeo4W.bat; gdal_translate C:/Sentinelbands/B01.jp2 C:/Sentinelbands/B01.tif'
shell(cmd)
2

You are correct in your comment, recommend you install GDAL via the OSGeo4W package manager. It comes with JP2OpenJPG, which should be able to handle Sentinel data (plus a couple of others).

Once its installed, a simple call would be like

system2('C:/OSgeo4w64/bin/gdal_translate.exe', args = c('--formats'))

(even simpler if the GDAL install is on your PATH properly!)

If the above works, you can call any GGAL/OGR tool in R with system2(), for instance something like

allthefiles <- list.files(dir, pattern = '\\.jp2$', full.names = TRUE)
sapply(allthefiles, function(x) {
    system2('C:/OSgeo4W64/bin/gdalwarp.exe', 
            args = c('-crop_to_cutline', '"path/to/cutlinefile.shp"', 
                     paste0('"', x, '"'),
                     paste0('"', tools::file_path_sans_ext(basename(x)), '.tif"')
})

It can just take a little bit of mucking around to make the system2() output match a valid shell command exactly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.