How to convert torch::conv2d return value(tensor) to cv::mat

I run the following program:

read a picture of 3 channel input torch::nn::conv2d(3,3,3).pad(1).stride(1),then I got the results:

cv::Mat img = cv::imread("babyx2.png", 1);
torch::Tensor img_tensor = torch::from_blob(, { img.rows, img.cols, 3 }, torch::kByte);
img_tensor = img_tensor.permute({ 2, 0, 1 }); 
img_tensor = img_tensor.unsqueeze(0);
img_tensor =;
torch::Tensor result = C1(img_tensor);       //C1: torch::nn::Conv2d(torch::nn::Conv2dOptions(3, 3, 5).padding(1))
.....then get the result use following method
auto ToCvImage(at::Tensor tensor)
	int width = tensor.sizes()[0];
	int height = tensor.sizes()[1];
	//auto sizes = tensor.sizes();
		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);

what happen???I don’t think the result picture is right,how to do…help

I input picture following:
then torch::nn::Conv2D(3,3,5).padding.stride
why the return value of torch::nn::Conv2D like that??? How to show it in the right way??

You are permuting the tensor from channels-last to channels-first format here:

img_tensor = img_tensor.permute({ 2, 0, 1 }); 

and I don’t see the permutation back to channels-last, which is the expected memory layout in OpenCV.
If you pass a channels-first image to OpenCV, the result would be interleaved, which fits your first posted image.

Thank you. It worked well