Skip to content

Instantly share code, notes, and snippets.

@sachadee
Last active May 7, 2022 06:56
Show Gist options
  • Save sachadee/35c6d35cad60157e662f8335fef27ce2 to your computer and use it in GitHub Desktop.
Save sachadee/35c6d35cad60157e662f8335fef27ce2 to your computer and use it in GitHub Desktop.
Create a Pytorch Tensor of an image
import torch
import numpy as np
import cv2
import torchvision.transforms as transforms
from PIL import Image
# Read the image with openCV
# image = cv2.imread('sachadee.jpg')
# Convert BGR image to RGB image
#image = cv2.cvtColor(image, cv2.COLOR_BGR2R
#or with PIL
image = Image.open('sachadee.jpg')
GB)
# Define a transform to convert
# the image to torch tensor
transform = transforms.Compose([
transforms.ToTensor()
])
# Convert the image to Torch tensor
tensor = transform(image)
# print the converted image tensor
print(tensor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment