【问题标题】:How to quickly convert a returned Python-in-Lua numpy array into a Lua Torch Tensor?如何快速将返回的 Python-in-Lua numpy 数组转换为 Lua Torch 张量?
【发布时间】:2016-02-04 07:02:30
【问题描述】:

我有一个 Python 函数,它返回一个多维 numpy 数组。我想从 Lua 调用这个 Python 函数,并尽快将数据输入 Lua Torch 张量。我有一个工作非常缓慢的解决方案,并且正在寻找一种速度明显更快的方法(10fps 或更多)。我不确定这是否可能。

考虑到 Facebook 支持的 Torch 越来越受欢迎,以及 Lua 缺乏的 Python 中提供的广泛易用的图像处理工具,我相信这对其他人有用。

我正在使用 lunatic-python 的 Bastibe fork 来从 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"))

【问题讨论】:

    标签: python arrays numpy lua torch


    【解决方案1】:

    试试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。我也尝试了link,但是我需要使用 qlua 而不是 luajit 运行,以便我可以使用显示窗口。
    猜你喜欢
    • 2016-09-05
    • 2014-10-04
    • 2016-06-09
    • 2015-09-27
    • 2020-03-16
    • 2021-02-02
    • 2016-10-06
    • 2016-09-27
    • 2021-01-08
    相关资源
    最近更新 更多