[英]How to get back the image from Tensor in libtorch?
I am trying to get the image back from the tensor I created earlier and visualize it, However, the resulting image is distorted/garbage it seems.我正在尝试从我之前创建的张量中取回图像并将其可视化,但是,生成的图像似乎失真/垃圾。 This is how I convert a
CV_8UC3
into the corresponding at::Tensor
:这就是我将
CV_8UC3
转换为对应at::Tensor
的方式:
at::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte);
and this is how I convert it back to the image:这就是我将其转换回图像的方式:
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);
}
This is how the original image looks like:这是原始图像的样子:
and this is what I get after conversion:这就是我转换后得到的:
Now if I use at::kInt
instead of kByte
during the creation of the tensor:现在,如果我在创建张量期间使用
at::kInt
而不是kByte
:
at::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte);
I no longer get the distorted image, however, the network output will be off which means something has gone wrong in the input!我不再得到扭曲的图像,但是,网络 output 将关闭,这意味着输入出现问题!
What's the issue here and how should I be going about this?这里有什么问题,我应该怎么做?
When the tensor was created using a c10::kByte
for the cast we need to use uchar
and not char
or uint
, etc. so in order to get this fixed I only had to use uchar
instead of int
:当使用
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);
}
Side note: In case you created your Tensor with any other type, make sure to use Tensor::totype()
effectively and convert to the proper type before hand.旁注:如果您使用任何其他类型创建了张量,请确保有效地使用
Tensor::totype()
并事先转换为正确的类型。 That is before I feed this tensor to my network, eg I convert it to KFloat
and then carry on!那是在我将此张量提供给我的网络之前,例如,我将其转换为
KFloat
然后继续! its an obvious point that may very well be neglected and cost you hours of debugging!这是一个很明显的点,很可能会被忽略并花费您数小时的调试时间!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.