How to combine transform and custom Dataset?

I defined a custom Dataset as shown below:

class VideoQuality_torchResize(Dataset):
    def __init__(self,imagelist):
        with open(imagelist) as f:
            self.lines = f.readlines()
    
    def __len__(self):
        return len(self.lines)
    
    def __getitem__(self,index):
        if '\t' in self.lines[index]:
            imgPath,label = self.lines[index].split('\t')
        else:
            imgPath,label = self.lines[index].split(' ')

        label = int(label.split('\n')[0])
        img = cv2.imread(imgPath)[...,::-1] 
        return img,label,imgPath

and I define a transform as shown below:

trainVal_transform = transforms.Compose([
    transforms.Resize((224, 224)), 
    transforms.ToTensor(),  
    transforms.Normalize(mean, std)  
])

and I try to combine them as shown below:

train_dataset = VideoQuality_torchResize(trainlist,transform = trainVal_transform)

I change my image as a txt file list, in VideoQuality_torchResize, and the program tell me that:

Traceback (most recent call last):
  File "videoquality_train_torchresize.py", line 41, in <module>
    train_dataset = VideoQuality_torchResize(trainlist,transform = trainVal_transform)
TypeError: __init__() got an unexpected keyword argument 'transform'

I know that VideoQuality_torchResize class haven’t transorm params,So can you tell me how to slove this problem?


class VideoQuality_torchResize(Dataset):

    def __init__(self,imagelist,transform=None):

        with open(imagelist) as f:

            self.lines = f.readlines()

            self.transform = transform

          

    def __len__(self):

        return len(self.lines)

    

    def __getitem__(self,index):

        if '\t' in self.lines[index]:

            imgPath,label = self.lines[index].split('\t')

        else:

            imgPath,label = self.lines[index].split(' ')

        label = int(label.split('\n')[0])

        img = cv2.imread(imgPath)[...,::-1]

        if self.transform is not None:

            img = self.transform(img)

        return img,label,imgPath

You can add you transform in the customdataset class like this
Then when you are creating your dataset its simply

train_dataset = VideoQuality_torchResize(trainlist,transform = trainVal_transform)
Hope this solves your problem

put an error:

/python3.6/site-packages/torchvision/transforms/functional.py", line 239, in resize
    raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
TypeError: img should be PIL Image. Got <class 'numpy.ndarray'>

I must use the opencv to read img, because Pillow and opencv is not equal when using read img or resize. please help me.

You can also create your custom pre-processing pipeline using only openCV. You can also load images as PIL Image perform pre process using torchvision and convert the image back to openCV image if you want. Refer to the documentation of the libraries to set your parameters correctly.