如何在Pytorch中为图像及​​其遮罩创建自定义数据集?

时间:2018-11-29 01:55:47

标签: python dataset pytorch

我有两个tif图像的数据集文件夹,一个是名为BMMCdata的文件夹,另一个是称为BMMCmasks的BMMCdata图像的遮罩(图像名称是对应的)。我正在尝试制作一个自定义的数据集,还随机拆分数据以进行训练和测试。此刻我出现了错误

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

任何评论将不胜感激。

self.filenames.append(fn)
AttributeError: 'CustomDataset' object has no attribute 'filenames'

1 个答案:

答案 0 :(得分:0)

pytorch社区中@ptrblck给出的

答案。谢谢

 # get all the image and mask path and number of images
 folder_data = glob.glob("D:\\Neda\\Pytorch\\U-net\\BMMCdata\\data\\*.tif")
 folder_mask = glob.glob("D:\\Neda\\Pytorch\\U-net\\BMMCmasks\\masks\\*.tif")

 # split these path using a certain percentage
 len_data = len(folder_data)
 print(len_data)
 train_size = 0.6

 train_image_paths = folder_data[:int(len_data*train_size)]
 test_image_paths = folder_data[int(len_data*train_size):]

 train_mask_paths = folder_mask[:int(len_data*train_size)]
 test_mask_paths = folder_mask[int(len_data*train_size):]


 class CustomDataset(Dataset):
    def __init__(self, image_paths, target_paths, train=True):   # initial logic 
      happens like transform

         self.image_paths = image_paths
         self.target_paths = target_paths
         self.transforms = transforms.ToTensor()

    def __getitem__(self, index):

        image = Image.open(self.image_paths[index])
        mask = Image.open(self.target_paths[index])
        t_image = self.transforms(image)
     return t_image, mask

def __len__(self):  # return count of sample we have

    return len(self.image_paths)

train_dataset = CustomDataset(train_image_paths, train_mask_paths, train=True)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=4, shuffle=True, num_workers=1)

test_dataset = CustomDataset(test_image_paths, test_mask_paths, train=False)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=4, shuffle=False, num_workers=1)