【问题标题】:Colab/Jupyter/Python: How to read uploaded fileColab/Jupyter/Python:如何读取上传的文件
【发布时间】:2020-12-17 22:55:22
【问题描述】:

我熟悉 Python,但尝试在 google drive/colab 中使用它。我似乎无法使用以下代码加载图像(该文件与代码/笔记本位于同一文件夹中)。有什么想法吗?

import cv2 
file1 = 'image1.JPG'
image = cv2.imread(file1)
if(image):
  print("File present")
else:
  print("File not present")

【问题讨论】:

  • 您在哪里上传了图片 colab 或 google drive?尝试打印os.listdir() 并检查结果中的文件
  • 谢谢。 listdir() 的结果是这样的:['.config', 'sample_data']。代码和上传的文件似乎不在同一个目录中 - 不知道为什么?
  • 文件没有上传?你能在侧边栏中看到文件吗
  • 我在 google 驱动器(我的驱动器> Colab Notebooks)的同一目录中看到 .ipynb 和图像文件,但列出的文件夹内容不显示图像文件。因此,.ipynb 和 .jpg 位于不同的文件夹中,即使它们显示在 Google Drive 的同一个文件夹中。
  • 您将文件 colab 或 google drive 上传到哪里?

标签: python jupyter google-colaboratory


【解决方案1】:

检查您的图像是否确实存在,一种方法是使用内置的 IPython 库

from IPython.display import Image
Image('file1.JPG')

我在上面运行您的代码时使用了一个工作图像,但由于检查 numpy 数组是否存在的模糊性而出现错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

考虑到这些建议,并使用绝对有效的 url 链接稍微更改您的代码,即可获得所需的输出:

import cv2 
file1 = 'file1.JPG'
image = cv2.imread(file1)
print(type(image))
if image.any():
  print("File present")
else:
  print("File not present")

# Returns "File present"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2021-07-02
    • 2019-07-14
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多