[PYTHON] Cloud Functions to resize images using OpenCV with Cloud Storage triggers

This is a sample using python when you want to create a thumbnail of an uploaded image using a Cloud storage trigger in Cloud functions of GCP.

--The GCS trigger will also fire on the object uploaded by this script, so you need to include some logic to prevent it from looping. ――It is assumed that all the objects that come into this bucket are images. If other files come in, there is logic to repel --cv2.imwrite () does not work well without the extension, so you need to set it in the file name ――Since it is a thumbnail, I think that there are many requests such as a square with a height and width of 300px ...

requirements.txt


google-cloud-storage==1.28.1
opencv-python==4.2.0.32
# -*- coding: utf-8 -*-
import tempfile
import os
import cv2
from google.cloud import storage


NEW_FILE_PREFIX="thumbnail_"
client = storage.Client()


def main(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    name = event['name']
    bucket = event['bucket']

    _, _name = os.path.split(name)
    if _name.startswith(NEW_FILE_PREFIX):
        print(f"Blob {name} is already resized.")
        return

    file_name = download(bucket, name)
    resize(file_name)
    upload(bucket, name, file_name)

    os.remove(file_name)


def download(bucket, blob_name):
    blob = client.bucket(bucket).blob(blob_name)
    _, _ext = os.path.splitext(blob.name)
    _, temp_local_filename = tempfile.mkstemp(suffix=_ext)
    blob.download_to_filename(temp_local_filename)
    print(f"Blob {blob_name} downloaded to {temp_local_filename}.")
    return temp_local_filename


def upload(bucket, blob_name, file_name):
    _dir, _name = os.path.split(blob_name)
    new_file_name = os.path.join(_dir, NEW_FILE_PREFIX + _name)
    new_blob = client.bucket(bucket).blob(new_file_name)
    new_blob.upload_from_filename(file_name)
    print(f'New image uploaded to: gs://{bucket}/{new_file_name}')


def resize(file_name):
    img = cv2.imread(file_name)
    height = img.shape[0]
    width = img.shape[1]
    print(f"Old blob width {width}, height {height}")

    dst = cv2.resize(img, (int(width/2), int(height/2)))
    cv2.imwrite(file_name, dst) # requierd ext
    print(f"New blob width {dst.shape[0]}, height {dst.shape[1]}")
    return file_name

Referenced --Upload Objects -Download Objects -ImageMagick Tutorial

Recommended Posts

Cloud Functions to resize images using OpenCV with Cloud Storage triggers
Try using Python with Google Cloud Functions
Convert the spreadsheet to CSV and upload it to Cloud Storage with Cloud Functions
Upload images to S3 with GUI using tkinter
Try projective transformation of images using OpenCV with Python
How to not load images when using PhantomJS with Selenium
[Python] Using OpenCV with Python (Basic)
How to upload files to Cloud Storage with Firebase's python SDK
Using OpenCV with Python @Mac
How to upload a file to Cloud Storage using Python [Make a fixed point camera with Raspberry PI # 1]
Upload files to Aspera that comes with IBM Cloud Object Storage (ICOS) using SDK (Python version)
Changes to run "Using Cloud Dataflow + Cloud Pub / Sub + Fluentd ..." with SDK 2.1
I want to use an external library with IBM Cloud Functions
How to connect to Cloud Firestore from Google Cloud Functions with python code
Object extraction in images by pattern matching using OpenCV with Python
Upload file to GCP's Cloud Storage (GCS) ~ Load with local Python
The fastest way to get camera images regularly with python opencv
[Python] Try to recognize characters from images with OpenCV and pyocr
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
Using Cloud Storage from Python3 (Introduction)
Load gif images with Python + OpenCV
Convert files uploaded to Cloud Storage with Cloud Functions (Python) so that they are not garbled in Excel
[memo] Send table information to GCS with BigQuery Schedule and Cloud Functions
Get tweets with Google Cloud Function and automatically save images to Google Photos
Get the number of visits to each page with ReportingAPI + Cloud Functions
[Rails] How to detect radical images by analyzing images using Cloud Vision API
Copy data from Amazon S3 to Google Cloud Storage with Python (boto)
How to search using python's astroquery and get fits images with skyview
Regular export of Google Analytics raw data to BigQuery using cloud functions
I want to detect objects with OpenCV
Learn to colorize monochrome images with Chainer
Try using the camera with Python's OpenCV
Capturing images with Pupil, python and OpenCV
Deploy functions with Cloud Pak for Data
[GCP] Operate Google Cloud Storage with Python
Add images to iOS photos with Pythonista
[python, openCV] base64 Face recognition with images
[Python] Read images with OpenCV (for beginners)
Add Gaussian noise to images with python2.7
Upload images to Google Drive with Python
How to draw OpenCV images in Pygame
Convert the cURL API to a Python script (using IBM Cloud object storage)