2015-11-03 49 views
6

我有一個Python函數返回一個多維的numpy數組。我想從Lua調用這個Python函數,並儘可能快地將數據導入Lua火炬傳遞。我有一個解決方案,運行速度非常緩慢,正在尋找一種明顯更快的方式(10fps或更多)。我不確定這是否可能。如何將返回的Python-in-Lua numpy數組快速轉換爲Lua火炬張量?

我相信這對於其他人來說是有用的,因爲考慮到Facebook支持的Torch日益流行以及Lua缺乏的易於使用的Python圖像處理工具。

我使用lunatic-python的Bastibe分叉來調用Lua的Python函數。在前面的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")) 

回答

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() 
+0

謝謝:)還沒有遇到過這個呢。我正在尋找一種在Lua中運行Python的方法,但是由於我使用了大量的Lua代碼,只需要少量的Python。我給[鏈接](https://github.com/facebook/fblualib/blob/master/fblualib/python/README.md)一個嘗試,但我需要與qlua而不是luajit運行,以便我可以使用顯示視窗。 –