Search code examples
luajpegbinary-datatorchluasocket

Convert Binary Data to Torch Tensor in Lua


I have Lua code that downloads an image from a url using a luasocket:

local http = require('socket.http')
local image = require('image')

image_url = 'https://www.somedomain.com/someimage.jpg'
local body, code = http.request(image_url) -- body has jpg binary data
if not body then error(code) end -- check for errors

In order to read this image into a Torch tensor, I save it in a jpg file and read it using image.load:

-- open a file in binary mode to store the image
local f = assert(io.open('./temp.jpg', 'wb')) 
f:write(body)
f:close()

tensor = image.load('temp.jpg')

Is there a way to convert the binary jpg data to a torch tensor directly without doing a write-to-and-read-from the hard-drive? Something like:

tensor = CovertBinaryDataToTorchTensor(body)

Thank you!


Solution

  • See image.decompressJPG.

    You just have to pack your body string inside a ByteTensor first. This can be done by constructing this tensor with a storage which can set his contents with string(str).