【问题标题】:How to write collate_fn correctly in my case?在我的情况下如何正确编写 collat​​e_fn?
【发布时间】:2021-09-04 10:07:08
【问题描述】:

请您帮我找到解决问题的方法。我想写 collat​​e_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


【解决方案1】:

为了将图像调整为相同大小,您可以使用 opencv 库。 要安装库,请运行以下命令。

pip install opencv-python

你需要用到的函数如下。

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

您可以在以下link找到该库的详细文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多