IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
11thAPRIL2017

SNIPPET

Reading and writing JSON and HDF5 in Lua/Torch using luajson and torch-hdf5.

install.sh
# luajson
$ git clone https://github.com/harningt/luajson.git luajson-master
$ cd luajson-master
$ luarocks install rockspecs/luajson-1.3.4-1.rockspec
# torch-hdf5
$ sudo apt-get install libhdf5-serial-dev hdf5-tools
$ git clone https://github.com/deepmind/torch-hdf5 torch-hdf5-master
$ cd torch-hdf5-master
$ luarocks make hdf5-0-0.rockspec
utils.lua
--- Write a table as JSON to a file.
-- @param file file to write
-- @param t table to write
function utils.writeJSON(file, t)
  local f = assert(io.open(file, 'w'))
  f:write(json.encode(t))
  f:close()
end

--- Read a JSON file into a table.
-- @param file file to read
-- @return JSON string
function utils.readJSON(file)
  local f = assert(io.open(file, 'r'))
  local tJSON = f:read('*all')
  f:close()
  return json.decode(tJSON)
end

--- Writes a single torch tensor to HDF5.
-- @param file file to write to
-- @param tensor tensor to write
-- @param key optional key, i.e. tensor is accessible as "/key"
function utils.writeHDF5(file, tensor, key)
  local key = key or 'tensor'
  local h5 = hdf5.open(file, 'w')
  h5:write('/' .. key, tensor)
  h5:close()
end

--- Reads a single torch tensor from HDF5.
-- @param file file to read
-- @param key key to read from, i.e. read "/key"
-- @return tensor
function utils.readHDF5(file, key)
  local key = key or 'tensor'
  local h5 = hdf5.open(file, 'r')
  tensor = h5:read('/' .. key):all()
  h5:close()
  return tensor
end

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: