3

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!

siavashk
  • 436
  • 7
  • 24

2 Answers2

3

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).

Youka
  • 2,646
  • 21
  • 33
0

One potential solution is to use graphicsmagick.

local gm = require 'graphicsmagick'
local img = gm.Image()
local ok = pcall(img.fromString, img, body)
img = img:toTensor('float', 'RGB', 'DHW')

I found this example in https://github.com/clementfarabet/graphicsmagick/blob/master/test/corrupt.lua and I know that

local body, code = http.request(image_url)

will return body as a string. And, obviously if pcall returns false, the image was corrupt.

davini
  • 46
  • 2