Twain
Twain

Reputation: 39

How to convert cv::Mat to torch::Tensor and feed it to libtorch model?

I read image with cv2.imread() and trying to feed it to torch model in c++. It has datatype cv::Mat. I think i need to convert it to tensor somehow and then use model.forward(), but i am confused how to do it. Is there some function similar to .Tensor() in python?

Upvotes: 1

Views: 1361

Answers (1)

ichramm
ichramm

Reputation: 6642

The function torch::from_blob can be used to create a tensor view over the image data, like this:

torch::Tensor to_tensor(cv::Mat img) {
    return torch::from_blob(img.data, { img.rows, img.cols, 3 }, torch::kUInt8);
}

Upvotes: 3

Related Questions