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

Time:07-12

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?

CodePudding user response:

The function torch::from_blob can view 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);
}
  • Related