How to transform images to tensors

Hi, I am a newbie to PyTorch, I am doing the image classification, please help me. how to transfer the image to tensors,
Here my code :

import cv2
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import os
import torch
import torchvision
import torchvision.transforms as transforms
file_path='dataset'
train=pd.read_csv(os.path.join(file_path,'train.csv'))
test=pd.read_csv(os.path.join(file_path,'test.csv'))
temp=[]
for img_name in train.Image:
    img_path=os.path.join(file_path,'Train Images',img_name)
    img=cv2.imread(img_path)
    img=cv2.resize(img,(64,64))
    temp.append(img)
train_x=np.asarray(temp)

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainloader = torch.utils.data.DataLoader(train_x, batch_size=4,
                                          shuffle=True, num_workers=2)

I tried this ,
but it is showing some module error.

Those transforms are only for PIL Images, so you have two options:

  • Using opencv to load the images and then convert to pil image using:
from PIL import Image
img = cv2.imread('img_path')
pil_img = Image.fromarray(img).convert('RGB')  #img as opencv
  • Load the image directly with PIL (better than 1)
from PIL import Image
pil_img = Image.open(img_path).convert('RGB') # convert('L') if it's a gray scale image

You can resize the pil image directly or also using transforms. Also you shouldn’t load all the images into a list, because Dataloader load on the fly, but you have to set your own Dataset or using something like https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder

3 Likes