c++load pytorchのデータ変換


tensor、numpy、vector変換
python:
**numpy -> tensor**:  `torch.from_numpy(ndarray)`

    **tensor -> numpy**:  `tensor.numpy()`

c++中:
**array -> tensor**:  `torch::tensor(at::ArrayRef({3.1, 3.2, 3.3, ...}));`     

    **cv::Mat -> tensor**:  `torch::tensor(at::ArrayRef(img.data, img.rows * img.cols * 3)).view({img.rows, img.cols, 3}); `  
**tensor->vector**:  ` vector xxx(tensor.data(), tensor.data()+tensor.numel())`;        vector

    **tensor -> cv::Mat**:  `Mat m(tensor.size(0), tensor.size(1), CV_8UC1, (void*) tensor.data());`

cv::Matとtensorの他の変換方法:
// from_blob      ,  image.data view。   .clone   。
at::Tensor tensor_image = torch::from_blob(image.data, {1, 3, image.rows, image.cols}, at::kByte); //at::kByte image dypte  ;   at::kFloat 。
//       dtype
tensor_image = tensor_image.to(at::kFloat);

tensor_image.data(); //    float*   。

// an example
at::Tensor compute(at::Tensor x, at::Tensor w) {
  cv::Mat input(x.size(0), x.size(1), CV_32FC1, x.data());
  cv::Mat warp(3, 3, CV_32FC1, w.data());

  cv::Mat output;
  cv::warpPerspective(input, output, warp, {64, 64});

  return torch::from_blob(output.ptr(), {64, 64}).clone();
}

c++model forward戻り値
戻りタイプはtorch::jit::IValueです
torch::jit::IValue result = module->forward(inputs);

戻り値が1つしかない場合はtensorを直接回転できます.
auto outputs = module->forward(inputs).toTensor();

複数の戻り値がある場合は、tupleを先に回転する必要があります.
auto outputs = module->forward(inputs).toTuple();
torch::Tensor out1 = outputs->elements()[0].toTensor();
torch::Tensor out2 = outputs->elements()[1].toTensor();

gpuの使用
モデルとinputsをgpuに配置します.
std::shared_ptr<:jit::script::module> module = torch::jit::load(argv[2]);
//put to cuda
module->to(at::kCUDA);

//     tensor  gpu,   vector<:jit::ivalue>
std::vector<:jit::ivalue> inputs;
image_tensor.to(at::kCUDA)
inputs.push_back(image_tensor)

GPU id:to(torch::Device(torch::kCUDA, id))を指定できます
同時通知ページ