微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在我的情况下如何正确编写 collat​​e_fn ?

如何解决在我的情况下如何正确编写 collat​​e_fn ?

拜托,你能帮我找到解决我问题的方法吗?我想写 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

解决方法

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

pip install opencv-python

您需要使用的功能如下。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。