• 深度学习(一)读取数据 图片数据


    若label作为文件夹名字,图片存放在里面:

    1. from torch.utils.data import Dataset
    2. import os
    3. import cv2 as cv
    4. class MyData(Dataset):
    5. def __init__(self,root_dir,label_dir):
    6. self.root_dir = root_dir #读取训练集的路径
    7. self.label_dir = label_dir #读取label的名字
    8. self.path = os.path.join(self.root_dir,self.label_dir) #这是图片的路径
    9. self.img_path = os.listdir(self.path) #把一条条路径变成列表
    10. def __getitem__(self, idx):
    11. img_name = self.img_path[idx]
    12. img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)
    13. img = cv.imread(img_item_path)
    14. label = self.label_dir
    15. return img,label
    16. def __len__(self):
    17. return len(self.img_path)
    18. root_dir = "dataset/train1"
    19. ants_label_dir = "ants"
    20. bees_label_dir = "bees"
    21. ants_dataset = MyData(root_dir,ants_label_dir)
    22. bees_dataset = MyData(root_dir,bees_label_dir)
    23. train_dataset = ants_dataset + bees_dataset;

    若label和图片分别在不同文件夹:

    1. from torch.utils.data import Dataset
    2. import os
    3. import cv2 as cv
    4. class MyData(Dataset):
    5. def __init__(self,root_dir,img_dir,label_dir):
    6. self.root_dir = root_dir #读取训练集的路径
    7. self.label_dir = label_dir #读取label的名字
    8. self.img_dir = img_dir
    9. self.img_path = os.path.join(self.root_dir,self.img_dir) #这是图片的路径
    10. self.label_path = os.path.join(self.root_dir, self.label_dir) # 这是标签的路径
    11. self.img_path_list = os.listdir(self.img_path) #把一条条路径变成列表
    12. self.label_path_list = os.listdir(self.label_path) # 把一条条路径变成列表
    13. def __getitem__(self, idx):
    14. img_name = self.img_path_list[idx]
    15. img_item_path = os.path.join(self.img_path,img_name)
    16. img = cv.imread(img_item_path)
    17. label_name = self.label_path_list[idx]
    18. label_item_path = os.path.join(self.label_path, label_name)
    19. label = open(label_item_path,encoding = 'utf-8')
    20. content = label.read()
    21. return img,content
    22. def __len__(self):
    23. return len(self.img_path_list)
    24. root_dir = "dataset2/train"
    25. label_dir = "ants_label"
    26. img_dir = "ants_image"
    27. ants_dataset = MyData(root_dir,img_dir,label_dir)

  • 相关阅读:
    第十二天最大重复子字符串
    需求解析思路
    阿里云r8i内存型服务器ECS实例介绍_CPU性能_网络存储测评
    重庆东微电子推出高性能抗射频干扰MEMS硅麦放大器芯片
    003-Java程序流程控制
    leetcode-aboutString
    总体设计(软件项目)
    Java查询多条数据放入word模板 多个word文件处理成zip压缩包并在前端下载.zip文件
    表单追加数据 - 工作经历
    简单但现代的服务器仪表板Dashdot
  • 原文地址:https://blog.csdn.net/weixin_63163242/article/details/132946684