can't export hd5 file to a tif using terra

31 Views Asked by At

I'm using terra to import an hdf file from the MODIS instrument. I filter for the NDVI variable and I want to export as a tif. I'm getting errors when I do this.

You can download a raster yourself with this sample URL: https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/MOD13Q1.061/MOD13Q1.A2017049.h12v04.061.2021267000402/MOD13Q1.A2017049.h12v04.061.2021267000402.hdf

Here's the code:

path = "/Users/sample/MODIS"

omi <- list.files(path, pattern = "MOD",full.names = TRUE)

for (i in omi){
  print(i)
  fname = paste(substr(i,86,126),'.tif',sep="")
  r1 <- terra::rast(i) ## select the variable name
  r2 = r1$`"250m 16 days NDVI"`
  writeRaster(r2, fname)
}

Here's the error:

Error: [writeRaster] too few values for writing: 0 < 23040000
In addition: Warning messages:
1: GDreadfield() failed for block. (GDAL error 1) 
2: MOD13Q1.A2016353.h12v04.061.2021363152532.hdf":MODIS_Grid_16DAY_250m_500m_VI:"250m 16 days NDVI", band 1: IReadBlock failed at X offset 0, Y offset 0: GDreadfield() failed for block. (GDAL error 1) 

Where's the error here?

1

There are 1 best solutions below

2
Grzegorz Sapijaszko On

I would suspect a corrupted .hdf file on your end, below the example with linked above file:

r <- terra::rast("~/Downloads/MOD13Q1.A2017049.h12v04.061.2021267000402.hdf")

terra::writeRaster(r$`"250m 16 days NDVI"`, filename = "~/Downloads/111.tif", overwrite = TRUE)
terra::rast("~/Downloads/111.tif")
#> class       : SpatRaster 
#> dimensions  : 4800, 4800, 1  (nrow, ncol, nlyr)
#> resolution  : 231.6564, 231.6564  (x, y)
#> extent      : -6671703, -5559753, 4447802, 5559753  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs 
#> source      : 111.tif 
#> name        : "250m 16 days NDVI" 
#> min value   :           -20000000 
#> max value   :            99890000

Created on 2024-03-26 with reprex v2.1.0