文件夹ants/bees文件夹与learn_data.py隶属于同一个目录data_process
所以引用相对路径的方式即为:
class MyData(Dataset):
def __init__(self, root_dir, label_dir):
self.root_dir = root_dir #根目录,即hymenoptera_data/train
self.label_dir = label_dir #标签目录,即ants或bees
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)
ants_root_dir = "hymenoptera_data/train" #路径引用
ants_label_dir = "ants"
ants_dataset = MyData(ants_root_dir,ants_label_dir)
bees_root_dir = "hymenoptera_data/train"
bees_label_dir = "bees"
bees_dataset = MyData(bees_root_dir,bees_label_dir)
标签:img,python,self,label,相对路径,引用,path,root,dir From: https://www.cnblogs.com/scorpio-xin/p/17785356.html