如何快速将返回的Python-in-Lua numpy数组转换为Lua Torch Tensor?

时间:2015-11-03 23:05:18

标签: python arrays numpy lua torch

我有一个Python函数,它返回一个多维的numpy数组。我想从Lua调用这个Python函数,并尽快将数据导入Lua Torch Tensor。我有一个非常缓慢的解决方案,我正在寻找一种明显更快的方式(10fps或更高的顺序)。我不确定这是否可行。

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

我正在使用lunatic-python的Bastibe fork来从Lua调用Python函数。在此前question和此documentation的帮助下,我提出了一些有效的代码,但速度太慢了。我正在使用Lua 5.1和Python 2.7.6,如果需要可以更新它们。

Lua Code:" 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"))

1 个答案:

答案 0 :(得分:3)

试试lutorpy,它在python中有一个lua引擎,能够与火炬分享numpy内存,所以它非常快,这是你的情况的代码:

import numpy
import Image
import lutorpy as lua

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

# now you can use your image as torch Tensor
# for example: use SpatialConvolution from nn to process the image
require("nn")
n = nn.SpatialConvolution(1,16,12,12)
res = n._forward(a)
print(res._size())

# convert back to numpy array
output = res.asNumpyArray()