我正在尝试操作存储在我的Google Drive中不同图像目录中的图像,以便进行深入学习。然而,我得到了一个FileNotFound
异常
假设我在Google Colab中的主目录是:
MainDirectory ='/content/drive/My Drive/Colab Notebooks/2020YearDeepLearning/Animals/PetImages/'
这个文件夹中有两个目录Dog
和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)
它将打印目录:
/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')
该错误很可能是由文件路径中的空格引起的。在
MainDirectory
文件路径之前添加r
字符串文字前缀,用作原始字符串。以下是更正后的代码:相关问题 更多 >
编程相关推荐