将ndarray(OpenCV中的图像)作为.jpg或.png上传到Google云端存储

时间:2018-04-04 12:43:23

标签: python google-cloud-platform google-cloud-storage opencv3.0

我有类似的问题,例如How to upload a bytes image on Google Cloud Storage from a Python script

我试过这个

from google.cloud import storage
import cv2
from tempfile import TemporaryFile
import google.auth
credentials, project = google.auth.default()
client = storage.Client()
# https://console.cloud.google.com/storage/browser/[bucket-id]/
bucket = client.get_bucket('document')
# Then do other things...
image=cv2.imread('/Users/santhoshdc/Documents/Realtest/15.jpg')
with TemporaryFile() as gcs_image:
    image.tofile(gcs_image)
    blob = bucket.get_blob(gcs_image)
    print(blob.download_as_string())
    blob.upload_from_string('New contents!')
    blob2 = bucket.blob('document/operations/15.png')

    blob2.upload_from_filename(filename='gcs_image')

这是错误的错误

> Traceback (most recent call last):   File
> "/Users/santhoshdc/Documents/ImageShapeSize/imageGcloudStorageUpload.py",
> line 13, in <module>
>     blob = bucket.get_blob(gcs_image)   File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/storage/bucket.py",
> line 388, in get_blob
>     **kwargs)   File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/storage/blob.py",
> line 151, in __init__
>     name = _bytes_to_unicode(name)   File "/Users/santhoshdc/.virtualenvs/test/lib/python3.6/site-packages/google/cloud/_helpers.py",
> line 377, in _bytes_to_unicode
>     raise ValueError('%r could not be converted to unicode' % (value,)) ValueError: <_io.BufferedRandom name=7> could not be
> converted to unicode

任何人都可以指导我出错或者我做错了什么吗?

2 个答案:

答案 0 :(得分:2)

根据@ A.Queue in的建议(29天后删除)

from google.cloud import storage
import cv2
from tempfile import TemporaryFile

client = storage.Client()

bucket = client.get_bucket('test-bucket')
image=cv2.imread('example.jpg')
with TemporaryFile() as gcs_image:
    image.tofile(gcs_image)
    gcs_image.seek(0)
    blob = bucket.blob('example.jpg')
    blob.upload_from_file(gcs_image)

文件已上传,但上传numpy ndarray并未保存为google-cloud-storage

上的图片文件

PS:

numpy array必须在保存之前转换为任何图片格式。

这很简单,使用创建的tempfile来存储图片,这里是代码。

with NamedTemporaryFile() as temp:

    #Extract name to the temp file
    iName = "".join([str(temp.name),".jpg"])

    #Save image to temp file
    cv2.imwrite(iName,duplicate_image)

    #Storing the image temp file inside the bucket
    blob = bucket.blob('ImageTest/Example1.jpg')
    blob.upload_from_filename(iName,content_type='image/jpeg')

    #Get the public_url of the saved image 
    url = blob.public_url

答案 1 :(得分:1)

你正在呼叫blob = bucket.get_blob(gcs_image),这没有任何意义。 get_blob()应该得到一个字符串参数,即您想要获取的blob的名称。 名称。但是你传递了一个文件对象。

我建议这段代码:

with TemporaryFile() as gcs_image:
    image.tofile(gcs_image)
    gcs_image.seek(0)
    blob = bucket.blob('documentation-screenshots/operations/15.png')
    blob.upload_from_file(gcs_image)