import os import os.path def get_files_list(dir): images_list=[] for parent,dirnames,imagesnames in os.walk(dir): for imagename in imagesnames: curr_file=parent.split(os.sep)[-1] if curr_file=='flower': labels=0 elif curr_file=='guitar': labels=1 elif curr_file=='animal': labels=2 elif curr_file=='houses': labels=3 elif curr_file=='plane': labels=4 cur_image_path=dir+'/'+curr_file+'/'+imagename images_list.append([cur_image_path,labels]) return images_list def write_txt(content,filename,mode='w'): with open(filename,mode) as f: for line in content: str_line="" for col,data in enumerate(line): if not col==len(line)-1: str_line=str_line+str(data)+" " else: str_line=str_line+str(data)+" " f.write(str_line) if __name__=='__main__': train_dir='D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/train' train_txt='D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/train.txt' train_data=get_files_list(train_dir) write_txt(train_data,train_txt,mode='w') validation_dir='D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/validation' validation_txt='D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/validation.txt' validation_data=get_files_list(validation_dir) write_txt(validation_data,validation_txt,mode='w') test_dir = 'D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/test' test_txt = 'D:/软件/pycharmProject/wenyuPy/Dataset/VGG16/test.txt' test_data = get_files_list(test_dir) write_txt(test_data, test_txt, mode='w')
有个地方要说明一下,就是
for line in content: str_line="" for col,data in enumerate(line):
这个地方,要知道,开始的时候,我们是将图像的信息即图像的绝对路径地址和图像的标签存储在了一个列表中,这个列表是这样的[[image1,label1],[image2,label1],[image3,label1]..........]就是大列表里面套小的列表,content其实就是这个大的列表,line 就好比这里面的[image1,label1],然后col,data就分别代表image1,和label1了,搞清楚这几行,这个程序就清楚了,其他的代码就都很简单啦,也是从我上一篇帖子那个大神那扒的,连接可以看上一篇帖子