我无法列出包含不同图像的文件夹的内容

I can't list the contents of the folder that contains the different images

我正在做一个带有深度学习的图像识别应用程序,但我无法在代码中找到每个文件夹中存在的不同图像

train_dir = 'C:/Users/dell/Documents/training_set/training_set'
test_dir = 'C:/Users/dell/Documents/test_set/test_set'

### Séparation des élements "dog" et "cat"

train_dogs = ['C:/Users/dell/Documents/training_set/training_set/{}'.format(i) for i in os.listdir(train_dir) if 'dog' in i] 
train_cats = ['C:/Users/dell/Documents/training_set/training_set/{}'.format(i) for i in os.listdir(train_dir) if 'cat' in i]  

#### On stocke les élements du jeu de test (liste de chemin) dans la variable test_imgs
test_imgs = ['C:/Users/dell/Documents/test_set/test_set/{}'.format(i) for i in os.listdir(test_dir)] 

当我执行时列表是空的

train_dogs[1:10]
[]

train_dogs
['C:/Users/dell/Documents/training_set/training_set/dogs']

首先是教育

os.listdir会return列出指定目录下的files/folders,不会递归列出整个目录及其子目录

现在是您问题的答案

有2个选项:

  1. 假设我们不知道子文件夹的确切名称:
train_dir = 'C:/Users/dell/Documents/training_set/training_set/'
test_dir = 'C:/Users/dell/Documents/test_set/test_set/'

train_folders = [train_dir + i + '/' for i in os.listdir(train_dir)]
train_dogs = [i + j for i in train_folders for j in os.listdir(i) if 'dog' in i] 
train_cats = [i + j for i in train_folders for j in os.listdir(i) if 'cat' in i] 

test_imgs = ['C:/Users/dell/Documents/test_set/test_set/{}'.format(i) for i in os.listdir(test_dir)]
  1. 如您所述,我们知道子目录名称!
train_dir = 'C:/Users/dell/Documents/training_set/training_set/'
test_dir = 'C:/Users/dell/Documents/test_set/test_set/'

train_dogs = [train_dir + 'dog/' + i for i in os.listdir(train_dir + 'dog')] 
train_cats = [train_dir + 'cats/' + i for i in os.listdir(train_dir + 'cats')] 

test_imgs = ['C:/Users/dell/Documents/test_set/test_set/{}'.format(i) for i in os.listdir(test_dir)]