在python中读取多个图像和标签

在python中读取多个图像和标签,python,opencv,dataset,Python,Opencv,Dataset,我的数据集由100个文件夹组成,每个文件夹包含一些图像,如下所示。如何读取这些图像和标签,以便在调用文件夹标签时,它将具有图像的集合?(例如,如果我调用Cat标签,它将由img_001和img_032组成,而不仅仅是img_001或img_032)。我已经尝试使用dictionary作为下面的代码,但是dictionary只获取每个文件夹的第一个图像,而我希望获取所有图像。如何做到这一点?多谢各位 (Folder Structure) Cat: -img_001.jpg -img_032.j

我的数据集由100个文件夹组成,每个文件夹包含一些图像,如下所示。如何读取这些图像和标签,以便在调用文件夹标签时,它将具有图像的集合?(例如,如果我调用Cat标签,它将由img_001和img_032组成,而不仅仅是img_001或img_032)。我已经尝试使用dictionary作为下面的代码,但是dictionary只获取每个文件夹的第一个图像,而我希望获取所有图像。如何做到这一点?多谢各位

(Folder Structure)
Cat:
 -img_001.jpg
 -img_032.jpg
Dog:
 -img_002.jpg
 -img_012.jpg
 -img_011.jpg
 -img_000.jpg
Bird:
 -img_003.jpg
... until 100 folders

您正在使用文件夹名称作为字典的键。 在这种情况下,要存储多个文件,应使用列表类型作为值。 使用[]作为列表创建的文本,并使用append()方法向列表中追加值,尝试执行以下操作:

path = 'animal/'
img_dict = dict()

for root, dirs, files in os.walk(path):
    print(os.path.basename(root))
    my_key = os.path.basename(root)

    dir_images = []
    for file_ in files:
        full_file_path = os.path.join(root, file_)
        img = cv2.imread(full_file_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        dir_images.append(img)

    img_dict[my_key] = dir_images
(Output using my code with only one images per labels)
Cat:
 -img_001.jpg
Dog:
 -img_002.jpg
Bird:
 -img_003.jpg
... until end of dictionary (100 labels)
path = 'animal/'
img_dict = dict()

for root, dirs, files in os.walk(path):
    print(os.path.basename(root))
    my_key = os.path.basename(root)

    dir_images = []
    for file_ in files:
        full_file_path = os.path.join(root, file_)
        img = cv2.imread(full_file_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        dir_images.append(img)

    img_dict[my_key] = dir_images