"FileNotFoundError" 在 Google Colab 上从 PIL 导入图像时

"FileNotFoundError" when importing Image from PIL on Google Colab

我想从 PIL 导入 Google Colab 上的图像。通过这样做:

from PIL import Image
img = Image.open('smallhouse.jpg')
img

但是,我得到了这个错误。

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-20-8ab03a99a9db> in <module>()
      1 
      2 from PIL import Image
----> 3 img = Image.open('smallhouse.jpg')
      4 img

/usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode)
   2807 
   2808     if filename:
-> 2809         fp = builtins.open(filename, "rb")
   2810         exclusive_fp = True
   2811 

FileNotFoundError: [Errno 2] No such file or directory: 'smallhouse.jpg'

不知道为什么。谢谢!

1. 您必须将 smallhouse.jpg 图片上传到您的 Google 驱动器.

2. 在您的 .ipynb 文件中,您需要在申请的开头包含此代码:drive.mount('/content/gdrive').

转到提供的URL。然后,系统将提示您授予访问 Google 驱动器的权限。复制提供的代码,访问您的应用程序并将代码粘贴到那里。

3. 最后,您可以传递图像的路径,现在是:/content/gdrive/My Drive/smallhouse.jpg.

您的代码将如下所示:

# Imports
from google.colab import drive
from PIL import Image

# Mount Google Drive for fast, responsible access to files
drive.mount('/content/gdrive')

# Open image
img = Image.open('/content/gdrive/My Drive/smallhouse.jpg')
img