在 c++ 中调用 lua 函数(带有 require 'nn')

Call lua function (with require 'nn') in c++

本文关键字:require nn 带有 c++ 调用 lua 函数      更新时间:2023-10-16

我有一个Lua函数:

require 'nn'
require 'image'
require 'torch'
require './lib/data_augmentation'
function predict (x) do
  model = torch.load("trained.t7")
  img = image.load(x)
  img_tensor = torch.DoubleTensor(2, 3, 32, 32)
  img_tensor[1]:copy(img)
  x = data_augmentation(img_tensor[1])
  preprocessing(x,params)
  preds = torch.Tensor(4):zero()
  step = 64
  for j = 1, x:size(1), step do
     batch = torch.Tensor(step, x:size(2), x:size(3), x:size(4)):zero()
     n = step
     if j + n > x:size(1) then
        n = 1 + n - ((j + n) - x:size(1))
     end
     batch:narrow(1, 1, n):copy(x:narrow(1, j, n))
     z = model:forward(batch):float()
     for k = 1, n do
       preds = preds + z[k]
     end
  end
  preds:div(x:size(1))
  confidences, indices = torch.sort(preds,true)
  return indices[1]
end
end

我想用C++调用这个函数,但我得到了一个错误:

PANIC: unprotected error in call to Lua API (attempt to call a nil value)

因为需要"…"

我应该怎么做,这样C++就可以识别所有的包或其他Lua脚本(比如data_augmentation)?

我在mac上遇到了同样的问题,并用解决了它

source ~/.profile

然后运行lua脚本。

完整说明可在此处找到:torch.ch

# On Linux with bash
source ~/.bashrc
# On Linux with zsh
source ~/.zshrc
# On OSX or in Linux with none of the above.
source ~/.profile