2016-02-26 76 views
3

我有一个从URL使用luasocket下载图像Lua代码:转换二进制数据火炬张量在Lua

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 

为了把这个图像读到火炬张量,我把它保存在一个JPG文件并使用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') 

有没有办法将二进制JPG数据火炬张量直接转换而不做写来和读取,从硬盘驱动器?例如:

tensor = CovertBinaryDataToTorchTensor(body) 

谢谢!

回答

0

一个可能的解决方案是使用graphicsmagick。

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

我发现这个例子中https://github.com/clementfarabet/graphicsmagick/blob/master/test/corrupt.lua我知道

local body, code = http.request(image_url) 

将返回body为字符串。而且,显然如果pcall返回false,则图像已损坏。