gpt4 book ai didi

python - 将 ndarray(OpenCV 中的图像)作为 .jpg 或 .png 上传到谷歌云存储

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:43 24 4
gpt4 key购买 nike

我有类似的问题 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

谁能指导我出了什么问题或我做错了什么?

最佳答案

根据@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 上保存为图像文件

附言:

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

关于python - 将 ndarray(OpenCV 中的图像)作为 .jpg 或 .png 上传到谷歌云存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49651351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com