【问题标题】:How to display image stored in Google Cloud bucket如何显示存储在 Google Cloud 存储桶中的图像
【发布时间】:2019-10-03 14:37:58
【问题描述】:

我可以使用以下代码从我的 PC 上运行的 python 代码成功访问谷歌云存储桶。

client = storage.Client()
bucket = client.get_bucket('bucket-name')
blob = bucket.get_blob('images/test.png')

现在我不知道如何在不写入硬盘驱动器上的文件的情况下从“blob”中检索和显示图像?

【问题讨论】:

  • 用例是什么?在网页上显示图像?
  • 没有。我只想在本地计算机上运行的 python 代码中显示和处理图像。
  • 调用 blob.download_as_string() 将 blob 作为字节字符串返回给您,您可以将其存储在内存中并在不写入磁盘的情况下继续工作。您的绘图和处理方法需要哪些输入格式?
  • bucket 的输入文件是 .png 格式,我想用枕头/opencv/matplotlib 显示/处理它。
  • 这里有一些关于pillow/opencv的解释,关于如何使用内存中的图像stackoverflow.com/questions/33754935/…

标签: python google-cloud-platform google-cloud-storage


【解决方案1】:

例如,您可以生成一个临时 url

from gcloud import storage
client = storage.Client()  # Implicit environ set-up
bucket = client.bucket('my-bucket')
blob = bucket.blob('my-blob')
url_lifetime = 3600  # Seconds in an hour
serving_url = blob.generate_signed_url(url_lifetime)

否则,您可以在存储桶中将图像设置为公开,并使用您可以在对象详细信息中找到的永久链接

https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME

【讨论】:

    【解决方案2】:

    在 Jupyter 笔记本中,您可以使用 download_as_bytes 直接显示图像:

    from google.cloud import storage
    from IPython.display import Image
    
    client = storage.Client() # Implicit environment set up
    # with explicit set up:
    # client = storage.Client.from_service_account_json('key-file-location')
    
    bucket = client.get_bucket('bucket-name')
    blob = bucket.get_blob('images/test.png')
    Image(blob.download_as_bytes())
    

    【讨论】:

    • 我得到'Blob'对象没有属性'download_as_bytes'使用你的答案
    【解决方案3】:

    从 GCS 以字节的形式下载图像,将其包装在 BytesIO 对象中以使字节像文件一样,然后作为 PIL Image 对象读入。

    from io import BytesIO
    from PIL import Image
    
    img = Image.open(BytesIO(blob.download_as_bytes()))
    

    然后你可以用img做任何你想做的事情——例如,要显示它,使用plt.imshow(img)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多