[Libtorch]:how to transfer data from tensor to vector with libtorch

I transfer data from tensor to vector as follow:

vector box_vec;
torch::Tensor out1 = outputs->elements()[0].toTensor();
auto box_temp = out1.view({ 1 ,21708*4 }).to(torch::kCPU);
for (int i = 0; i < 21708 * 4; i++) { box_vec.push_back(box_temp[0][i].item().toFloat());

How to transfer data from tensor to vector with libtorch directly?

1 Like

box_temp.data<float>() will give you a float* which you can liberally use. You do have to deal with strides yourself. An alternative could be to use box_vec.reserve(...), create a tensor view on that with auto box_vec_view = torch::from_blob (but I don’t know if it should be at::from_blob or torch::) and box_vec_view.copy_(out1) the tensor there.

Note that from_blob does not take ownership of the memory, I use that because it’s impossible to create a std::vector with memory from elsewhere.

Best regards

Thomas

P.S.: The preferred way is to use the C++ category rather than a [Libtorch] prefix.

4 Likes

Great .Thanks a lot.