Reading hdf files into R and converting them to geoTIFF rasters

后端 未结 4 620
傲寒
傲寒 2020-12-05 06:05

I\'m trying to read MODIS 17 data files into R, manipulate them (cropping etc.) and then save them as geoTIFF\'s. The data files come in .hdf format and there

4条回答
  •  不知归路
    2020-12-05 06:16

    This script has been very useful and I managed to convert a batch of 36 files using it. However, my problem is that the conversion does not seem correct. When I do it using ArcGIS 'Make NetCDF Raster Layer tool', I get different results + I am able to convert the numbers to C from Kelvin using simple formula: RasterValue * 0.02 - 273.15. With the results from R conversion I don't get the right results after conversion which leads me to believe ArcGIS conversion is good, and R conversion returns an error.

    library(gdalUtils)
    library(raster)
    
    setwd("D:/Data/Climate/MODIS")
    
    # Get a list of sds names
    sds <- get_subdatasets('MOD11C3.A2009001.006.2016006051904.hdf')
    # Isolate the name of the first sds
    name <- sds[1]
    filename <- 'Rasterinr.tif'
    
    gdal_translate(sds[1], dst_dataset = filename)
    # Load the Geotiff created into R
    r <- raster(filename)
    
    # Identify files to read:
    rlist=list.files(getwd(), pattern="hdf$", full.names=FALSE)
    
    
    # Substract last 5 digits from MODIS filename for use in a new .img filename
    substrRight <- function(x, n){
            substr(x, nchar(x)-n+1, nchar(x))
    }
    
    filenames0 <- substrRight(rlist,9)
    # Suffixes for MODIS files for identyfication:
    filenamessuffix <- substr(filenames0,1,5)
    
    listofnewnames <- c("2009.01.MODIS_","2009.02.MODIS_","2009.03.MODIS_","2009.04.MODIS_","2009.05.MODIS_",
                        "2009.06.MODIS_","2009.07.MODIS_","2009.08.MODIS_","2009.09.MODIS_","2009.10.MODIS_",
                        "2009.11.MODIS_","2009.12.MODIS_",
                        "2010.01.MODIS_","2010.02.MODIS_","2010.03.MODIS_","2010.04.MODIS_","2010.05.MODIS_",
                        "2010.06.MODIS_","2010.07.MODIS_","2010.08.MODIS_","2010.09.MODIS_","2010.10.MODIS_",
                        "2010.11.MODIS_","2010.12.MODIS_",
                        "2011.01.MODIS_","2011.02.MODIS_","2011.03.MODIS_","2011.04.MODIS_","2011.05.MODIS_",
                        "2011.06.MODIS_","2011.07.MODIS_","2011.08.MODIS_","2011.09.MODIS_","2011.10.MODIS_",
                        "2011.11.MODIS_","2011.12.MODIS_")
    
    # Final new names for converted files:
    newnames <- vector()
    for (i in 1:length(listofnewnames)) {
            newnames[i] <- paste0(listofnewnames[i],filenamessuffix[i],".img")
    }
    
    # Loop converting files to raster from NetCDF
    for (i in 1:length(rlist)) {
            sds <- get_subdatasets(rlist[i])
            gdal_translate(sds[1], dst_dataset = newnames[i])
    }
    

提交回复
热议问题