在Colab中从GDrive读取图像时发现FileNotFound错误

2024-10-16 17:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试操作存储在我的Google Drive中不同图像目录中的图像,以便进行深入学习。然而,我得到了一个FileNotFound异常

假设我在Google Colab中的主目录是:

MainDirectory ='/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/'

这个文件夹中有两个目录DogCat。我可以通过运行以下代码来验证这一点:

MainDirectory ='/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/'
Categories =['Dog','Cat']

for category in Categories:
    path = os.path.join(MainDirectory,category)
    print(path)

它将打印目录:

/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/Dog
/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/Cat

我现在要做的是显示图像,为此我编写了以下代码:

MainDirectory = '/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/'
Categories =['Dog','Cat']
for category in Categories:
   path =os.path.join(MainDirectory,category)
   print(path)
    
   for img in os.listdir(path):
      img_array =cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)
      plt.imshow(img_array,cmap="gray")
      plt.show()

但是,这会导致以下错误:

FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/Dog'

补充资料


我已导入以下库:

import numpy as np
import matplotlib.pyplot as plt
import os
import cv2

并使用以下命令安装我的驱动器:

from google.colab import drive
drive.mount('/content/drive')

Tags: pathimportosmydrivecontentcatcategories
1条回答
网友
1楼 · 发布于 2024-10-16 17:20:26

该错误很可能是由文件路径中的空格引起的。在MainDirectory文件路径之前添加r字符串文字前缀,用作原始字符串。以下是更正后的代码:

MainDirectory = r'/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/'

相关问题 更多 >