LibTorch 读取img,归一化并返回tensor
- 函数需要返回深拷贝,from_bob传递的是引用,img超出作用域后会销毁,导致tensor传递出错
torch::Tensor preprocessImage(const std::string& img_path, int out_size) {
cv::Mat test_image_data = cv::imread(img_path);
cv::Mat rgb_image;
cv::cvtColor(test_image_data, rgb_image, cv::COLOR_BGR2RGB);
cv::Mat resized_image;
cv::resize(rgb_image, resized_image, cv::Size(out_size, out_size));
cv::Mat normalized_image;
resized_image.convertTo(normalized_image, CV_32F, 1.0 / 255.0);
cv::subtract(normalized_image, cv::Scalar(0.48145466, 0.4578275, 0.40821073), normalized_image);
cv::divide(normalized_image, cv::Scalar(0.26862954, 0.26130258, 0.27577711), normalized_image);
torch::Tensor img_tensor = torch::from_blob(normalized_image.data, { 1, out_size, out_size, 3 }, torch::kFloat);
img_tensor = img_tensor.permute({ 0, 3, 1, 2 });
return img_tensor.clone();