在 Lua 中将二进制数据转换为 Torch 张量
Convert Binary Data to Torch Tensor in Lua
我有 Lua 使用 luasocket 从 url 下载图像的代码:
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
为了将此图像读入 Torch 张量,我将其保存在 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 数据转换为 torch 张量,而无需从硬盘驱动器进行写入和读取?类似于:
tensor = CovertBinaryDataToTorchTensor(body)
谢谢!
您只需先将 body
字符串打包到 ByteTensor 中。这可以通过使用 storage which can set his contents with string(str).
构造此张量来完成
一个可能的解决方案是使用 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)
将returnbody
作为字符串。而且,很明显,如果 pcall
return 为假,则图像已损坏。
我有 Lua 使用 luasocket 从 url 下载图像的代码:
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
为了将此图像读入 Torch 张量,我将其保存在 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 数据转换为 torch 张量,而无需从硬盘驱动器进行写入和读取?类似于:
tensor = CovertBinaryDataToTorchTensor(body)
谢谢!
您只需先将 body
字符串打包到 ByteTensor 中。这可以通过使用 storage which can set his contents with string(str).
一个可能的解决方案是使用 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)
将returnbody
作为字符串。而且,很明显,如果 pcall
return 为假,则图像已损坏。