Google Colab:如何在 Google Colab 中从 Google 驱动器读取多个图像

Google Colab: How To Read Multiple Images From a Google Drive in Google Colab

I Want to Read Multiple Image Files From The Google Drive into My Google Colab Python Notebook Below is My Google Drive Folder Structure

--Drive

  --Main_Folder

    --Sub_Folder_1

      --imagefile1.jpg
      --imagefile2.jpg
      --imagefile3.jpg

    --Sub_Folder_2

      --imagefile1.jpg
      --imagefile2.jpg
      --imagefile3.jpg

    --Sub_Folder_3

      --imagefile1.jpg
      --imagefile2.jpg
      --imagefile3.jpg

首先在您的 colab 实例上安装 google 驱动器,然后执行此操作。

import os
from PIL import Image

info = []
for root, __, files in os.walk("path/to/google/drive/folder"):
  for f in files:
      if f.endswith(".jpg"):
         info.append({
                     "img": Image.open(os.path.join(root, f)), # add an appropriate reading flag if you want
                     # optional
                     # "foldername": os.path.dirname(root)
                     })

# do whatever you want with the infolist you have now

我通过以下代码解决了这个问题

import os
from os import listdir
from os.path import isfile, join

images = {}
im2 = []

for root, dirs, files in os.walk("Main-Folder-Path"):
   path = root.split(os.sep)
   for index, file in enumerate(files):
      im2 = [ f for f in listdir(root) if isfile(join(root,f)) ]
      images[index] = join(root,im2[index])

现在它将逐个迭代每个文件夹

第一个 Sub_Folder_1 & Sub_Folder_1

中的所有文件

& 之后所有文件夹和文件