# Libtorch tensor to image with OpenCV

**URL:** <https://discuss.pytorch.org/t/libtorch-tensor-to-image-with-opencv/159058>\
**Category:** Uncategorized\
**Created:** [August 12, 2022, 8:03pm UTC](https://discuss.pytorch.org/t/libtorch-tensor-to-image-with-opencv/159058 "2022-08-12T20:03:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Isabela\_Marinho](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/isabela_marinho/32/51475_2.png) [@Isabela\_Marinho](https://discuss.pytorch.org/u/Isabela_Marinho)\
**Post date:** [August 12, 2022, 8:03pm UTC](https://discuss.pytorch.org/t/libtorch-tensor-to-image-with-opencv/159058/1 "2022-08-12T20:03:26Z")

</div>

Hello!  
I’m trying to plot an image using OpenCV, from a torch::tensor with rgb values (dim=100x100x3), but the output image is all black. The rgb tensor has float values between 0 and 1.

I’m using the following code:

```auto
auto img = cv::Mat(100, 100, CV_32FC3, rgb.data_ptr<float>());
cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
cv::imwrite("../new_img.jpg", img);

```

Am I missing something?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 12, 2022, 8:24pm UTC](https://discuss.pytorch.org/t/libtorch-tensor-to-image-with-opencv/159058/2 "2022-08-12T20:24:17Z")

</div>

`imwrite` expects int8 or int16 images as explained in the [docs](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imwrite#imwrite):

> The function `imwrite` saves the image to the specified file. The image format is chosen based on the `filename` extension (see [`imread()`](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html) for the list of extensions). Only 8-bit (or 16-bit unsigned (`CV_16U`) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use [`Mat::convertTo()`](https://docs.opencv.org/2.4/modules/core/doc/basic_structures.html) , and [`cvtColor()`](https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html) to convert it before saving. Or, use the universal [`FileStorage`](https://docs.opencv.org/2.4/modules/core/doc/xml_yaml_persistence.html#FileStorage) I/O functions to save the image to XML or YAML format.
