Muhammad Usman Liaqat
Muhammad Usman Liaqat

Reputation: 11

Issue Converting HDF5 into raster format

I am trying to convert my h5 daily files into a raster format. I converted into raster format. When I extracted my area of interest. I could not extract my area of interest from the raster image Kindly anyone guides me on how to solve this issue. The R code and hf5 file and after conversion raster image are present in link (attached). Thanks

library(rhdf5)
library(sp)
library(raster)
h5ls("reconstruction_indus_CY2001.h5")
h5readAttributes(file = "reconstruction_indus_CY2001.h5", name = "Grid")
h5f = H5Fopen("reconstruction_indus_CY2001.h5")
# h5f
# h5f&'Grid'

#system.time( swe <- h5f$Grid$swe )
system.time( melt <- h5f$Grid$melt )

locations <- data.frame(
  lon=c(74.86764,73.48753, 74.87066 , 73.37798 , 78.82102 ,75.85160 ,75.78263 , 78.46446 ), 
  lat = c(35.16700, 36.25674, 36.49362, 35.21188, 34.20916, 34.48459, 35.76965, 33.23380)
)

coordinates(locations) <- ~lon+lat
proj4string(locations) <-  CRS("+proj=longlat")

  swe180 <- melt[,,180]
  b <- swe180 == 65535
  # table(b)
  swe180[b] <- -1
  
  b <- swe180 > 200
  # table(b)
  swe180[b] <- 200
  
  b <- swe180 < 0
  # table(b)
  swe180[b] <- 20
  
  # image(swe180)
  
  # image(swe180)
  # str(swe180)
  
  # h5readAttributes(file = "reconstruction_Sierra_2016.h5", name = "Grid")$ReferencingMatrix
  
  RM <- h5readAttributes(file = "reconstruction_indus_CY2001.h5", name = "Grid")$ReferencingMatrix
  #GT <- GridTopology(c(RM[3,1], RM[3,2]+RM[1,2]*dim(swe)[1]), c(RM[2,1], -RM[1,2]), c(dim(swe)[2],dim(swe)[1]))
  GT <- GridTopology(c(RM[3,1], RM[3,2]+RM[1,2]*dim(melt)[1]), c(RM[2,1], -RM[1,2]), c(dim(melt)[2],dim(melt)[1]))
  # GT <- GridTopology(c(-1.088854e+07, 4718608.3619-463.3127*1978), c(463.3127, 463.3127), c(2171,1978))
  # GT
  SG = SpatialGrid(GT)
  # str(SG)
  # proj4string(SG) <- CRS("+proj=sinu")
  # str(SG)
  proj4string(SG) <- CRS("+proj=utm +zone=43 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")
  locations_aea <- spTransform(locations, CRS(proj4string(SG)))
  SGDF = SpatialGridDataFrame(SG, data.frame(melt = as.numeric(t(swe180))))
  gridded(SGDF)<- TRUE
  r = raster(SGDF)
  plot(SGDF, axes=T)
  writeRaster(r,"test_2001.tif",overwrite=TRUE)
  
## Open Raster Files and Extract Area of Interest

shp= readOGR("Hunza.shp")
e = extent(shp)
   r1  = raster("test_2001.tif")
  crs(r1) = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 "
  plot(r1)
  r1_mask = raster::mask(r1,shp)
  plot(r1_mask,axes = TRUE,ext = extent(shp))
  # Extracting Values as Data Frame
  r1_extract = raster::extract(r1,shp, df=TRUE,na.rm = TRUE)
  # Stroing as Raster
  writeRaster(r1_mask,paste0('/shared/MODIS/shastaH5SWEinR/2001_swe/Hunza/','hunza.tif'))
  c = cbind(r1_extract,y)
  c1=t(c)
  write.csv(c1,file = 'Hunza_SWE_2001.csv')

https://drive.google.com/drive/folders/18-hj2LEYWBN-uIDDTdqZ-x-WUxpCJu7H?usp=sharing

Upvotes: 1

Views: 1038

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47071

You can use the terra package (raster replacement) to shortcut this. terra can read hdf5 files directly.

The file has multiple sub-datasets, so it is easiest to read it as a SpatDataSet

library(terra)
f <- "reconstruction_indus_CY2001.h5"
s <- sds(f)
s
#class       : SpatDataSet 
#subdatasets : 3 
#dimensions  : 3651, 1641 (nrow, ncol)
#nlyr        : 1, 365, 365 
#resolution  : 0.2193784, 0.04930156  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#names       : maxswedates, melt, swe

And now get the variable of interest

r <- s$swe
r
#class       : SpatRaster 
#dimensions  : 3651, 1641, 365  (nrow, ncol, nlyr)
#resolution  : 0.2193784, 0.04930156  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#data source : swe 
#names       : swe_1, swe_2, swe_3, swe_4, swe_5, swe_6, ... 

A more direct way to get the same result is

r <- rast(f, "//Grid/swe")

And you can discover what is inside of a HDF5 file by running

sds_info(f)

Plot the first layer

plot(r, 1)

Extract area of interest, for example like this

v <- vect("Hunza.shp")
x <- crop(r, v)
y <- mask(x, v)

To save as a raster file you can add a filename to the functions above. Or you can do it later like this

y <- writeRaster(y, "hunza.tif")

To save the values to a csv file:

vy <- values(y)       
write.csv(vy, 'Hunza_SWE_2001.csv', row.names=FALSE)

Most function names in terra are the same as in raster. See ?terra for differences. If you want to continue in raster you can do

library(raster)
b <- brick(y)

Upvotes: 0

Related Questions