Skip to content

Instantly share code, notes, and snippets.

@thejasonfisher
Forked from gsoykan/tensor_2_cv2.py
Created December 10, 2023 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejasonfisher/fe81a73fb86052a138aac3281d3913b2 to your computer and use it in GitHub Desktop.
Save thejasonfisher/fe81a73fb86052a138aac3281d3913b2 to your computer and use it in GitHub Desktop.
pt tensor to cv2 image
import cv2
import numpy as np
import torch
# Create a random torch tensor
tensor = torch.randn(3, 256, 256)
# Convert the tensor to a numpy array
numpy_image = tensor.numpy()
# Convert the numpy array to a cv2 image
cv2_image = np.transpose(numpy_image, (1, 2, 0))
cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB)
# Display the image using cv2
cv2.imshow("Image", cv2_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment