Dataset 读取数据
from torch.utils.data import Dataset
from PIL import Image
import osclass Mydata(Dataset):def __init__(self,root_dir,label_dir):self.root_dir = root_dir #根目录 dataset/trainself.label_dir = label_dir #标签的后面链接目录 ants_imageself.path = os.path.join(self.root_dir,self.label_dir) #根目录与标签目录链接起来 dataset/train + ants_imageself.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) #该图片的路径 dataset/train/ants_image/5650366_e22b7e1065.jpgimg = Image.open(img_item_path) #打开该图片label = self.label_dir #此图片属于哪一个标签 ants_imagereturn img,labeldef __len__(self):return len(self.img_path) #图片长度root_dir = "dataset/train"
ants_label_dir ="ants_image"
bees_label_dir ="bees_image"ants_dataset = Mydata(root_dir,ants_label_dir)
bees_dataset = Mydata(root_dir,bees_label_dir)train_dataset = ants_dataset + bees_datasetimg,label = train_dataset[110]
img.show()
print(label)
数据集文件夹对应位置,图片是随便找的