如何快速地将一个由Python-in-Lua的numpy数组转换为Lua Torch Tensor?

我有一个返回多维 numpy 数组的 Python 函数。我想从 Lua 中调用此 Python 函数,并尽快将数据获取到一个 Lua Torch 张量中。我有一个运行缓慢但可以工作的解决方案,并正在寻找一种显著更快的方法(10fps 或更高的顺序)。我不确定这是否可能。

我认为这对其他人会有用,考虑到 Facebook 支持的 Torch 的日益流行以及 Python 中可用的广泛易用的图像处理工具,这是 Lua 所缺少的。

我正在使用 Bastibe 的 lunatic-python 分支,以从 Lua 中调用 Python 函数。在此前一个问题和此文档的帮助下,我想出了一些代码,但是速度太慢了。我正在使用 Lua 5.1 和 Python 2.7.6,并且可以根据需要更新这些内容。

Lua 代码:"test_lua.lua"

require 'torch'

print(package.loadlib("libpython2.7.so", "*"))
require("lua-python")

getImage = python.import "test_python".getImage

pb = python.builtins()

function getImageTensor(pythonImageHandle,width,height)
    imageTensor = torch.Tensor(3,height,width)
    image_0 = python.asindx(pythonImageHandle(height,width))
    for i=0,height-1 do
        image_1 = python.asindx(image_0[i])
        for j=0,width-1 do
            image_2 = python.asindx(image_1[j])
            for k=0,2 do
                -- Tensor indices begin at 1
                -- User python inbuilt to-int function to return integer
                imageTensor[k+1][i+1][j+1] = pb.int(image_2[k])/255
            end
        end
    end
    return imageTensor
end

a = getImageTensor(getImage,600,400)

Python 代码:"test_python.py"

import numpy
import os,sys
import Image

def getImage(width, height):
    return numpy.asarray(Image.open("image.jpg"))
点赞
用户6262499
用户6262499

尝试 lutorpy,它在 Python 中有一个 Lua 引擎,并且能够与 Torch 共享 Numpy 内存,因此非常快速。这里是您需要的代码:

import numpy
import Image
import lutorpy as lua

getImage = numpy.asarray(Image.open("image.jpg"))
a = torch.fromNumpyArray(getImage)

# 现在你可以使用你的图像作为 Torch 张量
# 例如:使用 nn 中的 SpatialConvolution 处理图像
require("nn")
n = nn.SpatialConvolution(1,16,12,12)
res = n._forward(a)
print(res._size())

# 转换回 Numpy 数组
output = res.asNumpyArray()
2016-04-27 17:03:38