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

6
我有一个返回多维numpy数组的Python函数。我想从Lua调用这个Python函数,并尽快将数据获取到Lua Torch Tensor中。我有一个解决方案,但速度非常慢,我正在寻找一种更快的方法(10fps或更高)。我不确定是否可能做到这一点。
我相信这对其他人会有用,考虑到Facebook支持的Torch越来越受欢迎,而Python具有丰富易用的图像处理工具,而Lua则缺乏。
为了从Lua调用Python函数,我使用了lunatic-python的Bastibe分支。在参考了questiondocumentation之后,我编写了一些代码,但速度太慢了。我使用的是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"))
1个回答

3
尝试使用 lutorpy,它拥有一个在Python中的Lua引擎,并能够与torch共享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()

谢谢 :) 我还没有遇到过这个。我正在寻找一种在Lua中运行Python的方法,因为我正在处理大量的Lua代码,只需要少量的Python。我也尝试了[链接](https://github.com/facebook/fblualib/blob/master/fblualib/python/README.md),但我需要使用qlua而不是luajit来运行,以便我可以使用显示窗口。 - Adam Tow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接