我试图从我之前创建的张量中恢复图像,并将其可视化,然而,结果图像似乎是扭曲的/垃圾。这就是我如何将CV_8UC3转换为相应的at::Tensor
at::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte);这就是我把它转换回图像的方法:
auto ToCvImage(at::Tensor tensor)
{
int width = tensor.sizes()[0];
int height = tensor.sizes()[1];
try
{
cv::Mat output_mat(cv::Size{ height, width }, CV_8UC3, tensor.data_ptr<int>());
return output_mat.clone();
}
catch (const c10::Error& e)
{
std::cout << "an error has occured : " << e.msg() << std::endl;
}
return cv::Mat(height, width, CV_8UC3);
}这是原始图像的外观:

这是我转换后得到的结果:

现在,如果我在创建张量时使用at::kInt而不是kByte:
at::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte);我再也看不到失真的图像了!但是,网络输出将关闭,这意味着输入中出现了问题!
这里的问题是什么,我应该怎么做?
发布于 2020-07-29 23:36:06
当使用c10::kByte为造型创建张量时,我们需要使用uchar,而不是char或uint等。因此,为了解决这个问题,我只需要使用uchar而不是int
auto ToCvImage(at::Tensor tensor)
{
int width = tensor.sizes()[0];
int height = tensor.sizes()[1];
try
{
cv::Mat output_mat(cv::Size{ height, width }, CV_8UC3, tensor.data_ptr<uchar>());
return output_mat.clone();
}
catch (const c10::Error& e)
{
std::cout << "an error has occured : " << e.msg() << std::endl;
}
return cv::Mat(height, width, CV_8UC3);
}附注:如果你用任何其他类型创建了张量,请确保有效地使用Tensor::totype(),并在手前转换为正确的类型。那是在我把这个张量输入到我的网络之前,例如我把它转换成KFloat,然后继续!这是一个显而易见的点,很可能会被忽略,并花费你几个小时的调试时间!
https://stackoverflow.com/questions/63152275
复制相似问题