[pytorch使用] 1. dataset类

发布时间:2024年01月19日
from torch.utils.data import Dataset
from PIL import Image
import cv2
import os
import matplotlib.pyplot as plt

class MyDataset(Dataset):
    def __init__(self, root_dir, label_dir):
        self.root_dir = root_dir
        self.label_dir = label_dir
        self.path = os.path.join(self.root_dir, self.label_dir)
        self.img_path = os.listdir(self.path)

    def __getitem__(self,idx):
        img_name = self.img_path[idx]
        img_item_path = os.path.join(self.root_dir, self.label_dir, img_name)
        img = Image.open(img_item_path)
        label = self.label_dir
        return img, label
    
    def __len__(self):
        return len(self.img_path)
    


root_dir = "./dataset/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset = MyDataset(root_dir, ants_label_dir) 
bees_dataset = MyDataset(root_dir, bees_label_dir)


train_dataset = ants_dataset + bees_dataset
# print(ants_dataset)
# img, label = ants_dataset[0]
# img.show()
# print(label)
print(len(train_dataset))
print(len(ants_dataset))
print(len(bees_dataset))

img, label = train_dataset[124]
img.show()
文章来源:https://blog.csdn.net/yuri5151/article/details/135691222
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。