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


    若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)

  • 相关阅读:
    大模型全情投入,低代码也越来越清晰
    【cartographer ros】十: 延时和误差分析
    C语言数据结构 —— 复杂度
    物联网设备上云难?华为云IoT帮你一键完成模型定义,快速在线调试设备
    图书推荐||Word文稿之美
    4.云原生-KubeSphere中安装GitLab(三)
    Java不支持协程?那是你不知道Quasar!
    面试官让说出8种创建线程的方式,我只说了4种,然后挂了。。。
    使用物联网进行智能能源管理的10大优势
    8-11二路插入排序
  • 原文地址:https://blog.csdn.net/weixin_63163242/article/details/132946684