Libtorch c++ equivalent of 'torch.transforms.Compose' function? Please Help

I would like to convert image (array) to tensor for Deep learning model inference.

How do I convert to libtorch based C++ from the below code?

img_transforms = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) ?

I found the below example in online

Tensor CVMatToTensor(cv::Mat mat)
std::cout << “converting cvmat to tensor\n”;
cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB);
cv::Mat matFloat;
mat.convertTo(matFloat, CV_32F, 1.0 / 255);
auto size = matFloat.size();
auto nChannels = matFloat.channels();
auto tensor = torch::from_blob(, { 1, size.height, size.width, nChannels });
return tensor.permute({ 0, 3, 1, 2 });

but not sure how to implement the 'transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) to C++ using libtorch (or whatevert methods).

Thank You.

Something like this should work:

std::vector<double> norm_mean = {0.485, 0.456, 0.406};
std::vector<double> norm_std = {0.229, 0.224, 0.225};
input_tensor = torch::data::transforms::Normalize<>(norm_mean, norm_std)(input_tensor);

defined here or you could directly normalize the tensor via input.sub(mean).div(stddev); as seen in the operator() definition.

Thank you very much for the help.
I have one more question, I’m new to C++ and how to convert the below code for post-processing the output (Tensor type) of the deep learning model to C++?

output_ = output.cpu().detach().numpy()

Thank you.

You won’t be able to use numpy in libtorch as it’s a Python library so you would need to process the PyTorch tensor instead. I don’t know which operations are applies to output_ but would assume you could use the PyTorch equivalent.

1 Like