问题描述
拜托,你能帮我找到解决我问题的方法吗?我想写 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
解决方法
为了将图像调整为相同大小,您可以使用 opencv 库。 为了安装库,运行以下命令。
pip install opencv-python
您需要使用的功能如下。
cv2.resize(src,dsize[,dst[,fx[,fy[,interpolation]]]])
您可以在以下 link 中找到库的详细文档。