【发布时间】:2021-09-04 10:07:08
【问题描述】:
请您帮我找到解决问题的方法。我想写 collate_fn 使我的图片大小相等,但我不知道如何正确实现。
Colab:link
代码:
import pandas as pd
import numpy as np
from PIL import Image
from torchvision import transforms
from torch.utils.data.dataset import Dataset # For custom datasets
class CustomDataset(Dataset):
def __init__(self, csv_path):
self.to_tensor = transforms.ToTensor()
self.data_info = csv_path
# First column contains the image paths
self.image_arr = np.asarray(self.data_info.iloc[:, 0])
# Second column is the labels
self.label_arr = np.asarray(self.data_info.iloc[:, 1])
# Calculate len
self.data_len = len(self.data_info.index)
def __getitem__(self, index):
# Get image name from the pandas df
single_image_name = self.image_arr[index]
# Open image
IMAGE_SIZE = [224,224]
response = requests.get(single_image_name)
img_as_img = Image.open(BytesIO(response.content)).resize(IMAGE_SIZE)
# Transform image to tensor
img_as_tensor = self.to_tensor(img_as_img)
# Get label(class) of the image based on the cropped pandas column
single_image_label = self.label_arr[index]
return (img_as_tensor, single_image_label)
def __len__(self):
return self.data_len
【问题讨论】:
-
我建议使用
torchvision库 (pytorch.org/vision/stable/…) 在__getitem__方法(或预先作为预处理)中调整图像大小,这样您就不需要编写自己的 @ 987654326@(堆叠张量的默认值将起作用)。虽然看起来您已经在尝试将__getitem__中的图像大小调整为 224x224 - 那么您遇到了什么样的错误?
标签: python neural-network pytorch dataloader pytorch-dataloader