New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Loading opencv image to pytorch tensor #14330
Comments
in opencv, the channel dimension is the last dimension. so you would do |
Thanks for that information. I had just figured it out. @ssnl Any comments? |
@jainshobhit If you want an 8UC the output is float so you need to convert in at::kByte and access with |
Thanks @bhack |
@ssnl Do you know how to transpose a tensor? I cannot find documentation related to it. |
I found it at https://pytorch.org/cppdocs/api/classat_1_1_tensor.html#exhale-class-classat-1-1-tensor. tensor_image = tensor_image.permute({0, 3, 1, 2}); |
A much cleaner way to transpose the axes is also provided in the ATen library. You can find an example for how to use it at https://github.com/jainshobhit/pytorch-cpp-examples/blob/master/libtorch_inference.cpp#L39. |
@jainshobhit I am curious, why is |
|
What about the vice-versa? I mean Pytorch tensor array to cv::Mat image? |
@xhuvom you could do sth like this based on this issue: 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 a blank image!
return cv::Mat(height, width, CV_8UC3);
} |
❓ Questions and Help
I am trying to load an image in OpenCV Mat variable and then converting it into tensor for passing it into my TorchScript model. I followed #12506 for loading the image however, I am not sure whether it is the correct way or not.
Here is my code
The output for the first 10 pixel values is
And the output on calling the slice function on the resulting tensor (
cout<<tensor_image.slice(2,0,1)<<endl;
) is (only mentioning the first few columns of the R color channel):This clearly shows that the values are not being copied correctly in the tensor.
I am not able to figure out what is the correct way to perform this step since I was not able to find adequate documentation.
@goldsborough
The text was updated successfully, but these errors were encountered: