【问题标题】:Google Colab: How to loop through images in a folder?Google Colab:如何循环浏览文件夹中的图像?
【发布时间】:2019-01-22 06:11:35
【问题描述】:

我已根据Google Colab: how to read data from my google drive? 将大量 .jpg 图片从我的 Google 云端硬盘复制到 Google Colab:

local_download_path = os.path.expanduser('~/data')
try:
  os.makedirs(local_download_path)
except: pass

# 2. Auto-iterate using the query syntax
#    https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile(
    {'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList()

for f in file_list:
  # 3. Create & download by id.
  print('title: %s, id: %s' % (f['title'], f['id']))
  fname = os.path.join(local_download_path, f['title'])
  print('downloading to {}'.format(fname))
  f_ = drive.CreateFile({'id': f['id']})
  f_.GetContentFile(fname)

这样就完成了,所以所有的图像文件都应该在data 文件夹中。我现在如何实际访问这些文件?我想遍历 data 文件夹中所有 .jpg 类型的文件。

【问题讨论】:

  • 所有图片都在本地文件夹中?

标签: python


【解决方案1】:

获取所有文件并转换为numpy数组

import cv2
import glob
path = "/content/bb/*.*"
for file in glob.glob(path):
   print(file)
   a= cv2.imread(file)
   print(a)

【讨论】:

  • 这对我访问谷歌驱动器中的图像很有用!谢谢!
【解决方案2】:

另一种选择是使用已经实现的操作系统库。

# Just needed in case you'd like to append it to an array
data = []

for filename in os.listdir(local_download_path):
    if filename.endswith("jpg"): 
        # Your code comes here such as 
        print(filename)
        data.append(filename)

【讨论】:

    【解决方案3】:

    将数据下载到local_download_path 后,您可以 使用glob.glob按扩展名获取文件:

    import glob
    images = glob.glob(local_download_path + '/*.jpg')
    

    【讨论】:

      猜你喜欢
      • 2013-03-27
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      相关资源
      最近更新 更多