Read data from Google Storage Bucket to Array

Viewed 792

How can I replace this function if I want to read the data from a Google Cloud Storage bucket (as opposed to local storage) and put it in an array like in this function?

def load_data(img_dir):
  return np.array(
    [cv2.imread(os.path.join(img_dir, img), 0).flatten() for img in os.listdir(img_dir) if img.endswith(".jpg")])       
1 Answers

You'll need to use OpenCV's imdecode function instead, along with the google-cloud-storage package:

from google.cloud import storage

import numpy as np
import cv2

def load_data(bucket_name):
    bucket = storage.Client().get_bucket(bucket_name)

    return np.array(
        cv2.imdecode(
            np.asarray(bytearray(blob.download_as_string()), dtype=np.uint8), 0
        ).flatten()
        for blob in bucket.list_blobs()
        if blob.name.endswith(".jpg")
    )
Related