3

我想从Python脚本上传Google云端存储中的图像。这是我的代码:如何从Python脚本上传Google云端存储中的字节图像

from oauth2client.service_account import ServiceAccountCredentials 
from googleapiclient import discovery 

scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] 
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop 
es) 
service = discovery.build('storage','v1',credentials = credentials) 

body = {'name':'my_image.jpg'} 

req = service.objects().insert(
    bucket='my_bucket', body=body, 
    media_body=googleapiclient.http.MediaIoBaseUpload(
     gcs_image, 'application/octet-stream')) 

resp = req.execute() 

如果gcs_image = open('img.jpg', 'r')代码工作和正确保存我的云存储图像。我怎样才能直接上传一个字节图像? (例如,从一个的OpenCV/numpy的阵列:gcs_image = cv2.imread('img.jpg')

回答

0

MediaIoBaseUpload期望并io.Base样物体,并提出以下错误:

'numpy.ndarray' object has no attribute 'seek' 

在接收到ndarray对象。为了解决这个问题,我使用TemporaryFilenumpy.ndarray().tofile()

from oauth2client.service_account import ServiceAccountCredentials 
from googleapiclient import discovery 
import googleapiclient 
import numpy as np 
import cv2 
from tempfile import TemporaryFile 


scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] 
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes) 
service = discovery.build('storage','v1',credentials = credentials) 

body = {'name':'my_image.jpg'} 
with TemporaryFile() as gcs_image: 
    cv2.imread('img.jpg').tofile(gcs_image) 
    req = service.objects().insert(
     bucket='my_bucket’, body=body, 
     media_body=googleapiclient.http.MediaIoBaseUpload(
      gcs_image, 'application/octet-stream')) 

    resp = req.execute() 

注意googleapiclient是不地道和仅维护(它不再开发)。我会推荐使用idiomatic one

相关问题