自用:小土堆练习 实现将单个训练数据集文件拆分为:image文件和label文件(pytorch学习+蚂蚁蜜蜂数据集)

蚂蚁蜜蜂/练手数据集:链接: https://pan.baidu.com/s/1jZoTmoFzaTLWh4lKBHVbEA 密码: 5suq
蚂蚁蜜蜂/练手拆分过后的数据集,参考大佬的做法:将单个训练数据集文件拆分为:image文件和label文件(pytorch学习+蚂蚁蜜蜂数据集)_怎么把bio标注数据集的文字和标签分成两个文件-CSDN博客

具体代码实现:

from torch.utils.data import Dataset
import os
from PIL import Image

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

def __getitem__(self, idx):
img_path=os.path.join(self.root_dir,self.image_dir,self.img_list[idx])
label_path=os.path.join(self.root_dir,self.label_dir,self.label_list[idx])
image=Image.open(img_path)
with open(label_path,"r",encoding="utf-8") as f:
label=f.read()
return image,label

def __len__(self):
return len(self.img_list)

root_dir="./dataset/train"
image_dir="ants_image"
label_dir="ants_label"
ant_dataset=MyDataset(root_dir,image_dir,label_dir)
image,label=ant_dataset[0]
image.show()
print(label)
posted @ 2025-06-05 16:45  SaulGoodman1  阅读(26)  评论(0)    收藏  举报