Upload ndarray(image in OpenCV) on to google cloud storage as a .jpg or .png

前端 未结 2 2015
傲寒
傲寒 2021-01-22 19:19

I have a similar issues like How to upload a bytes image on Google Cloud Storage from a Python script.

I tried this

from google.cloud import storage
imp         


        
2条回答
  •  不要未来只要你来
    2021-01-22 20:12

    As suggested by @A.Queue in(gets deleted after 29 days)

    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)
    

    The file got uploaded,but uploading a numpy ndarray doesn't get saved as an image file on the google-cloud-storage

    PS:

    numpy array has to be convert into any image format before saving.

    This is fairly simple, use the tempfile created to store the image, here's the code.

    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
    

提交回复
热议问题