Skip to content

Instantly share code, notes, and snippets.

@tibaes
Created June 28, 2019 04:12
Show Gist options
  • Save tibaes/dbdc2813be2e25055216a0a35cb84e4b to your computer and use it in GitHub Desktop.
Save tibaes/dbdc2813be2e25055216a0a35cb84e4b to your computer and use it in GitHub Desktop.
VisionAPI & Functions
# opencv-python
# google-cloud-storage
# google-cloud-vision
from google.cloud import storage
from google.cloud import vision
import numpy as np
import cv2 as cv
import logging
import os
import io
def hello_gcs(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.
"""
file = event
sclient = storage.Client()
vclient = vision.ImageAnnotatorClient()
logging.info('Downloading image GCloud -> /tmp...')
img_name = os.path.split(file['name'])[-1]
img_src = '/tmp/' + img_name
bucket_src = sclient.get_bucket(file['bucket'])
blob_img = storage.Blob(file['name'], bucket_src)
blob_img.download_to_filename(img_src)
logging.info('Getting face information at VisionAPI...')
with io.open(img_src, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = vclient.face_detection(image=image)
faces = response.face_annotations
logging.info('Computing faces ROI...')
img = cv.imread(img_src)
face_img = []
for face in faces:
x = [vertex.x for vertex in face.bounding_poly.vertices]
y = [vertex.y for vertex in face.bounding_poly.vertices]
x_min = min(x)
x_max = max(x)
y_min = min(y)
y_max = max(y)
fimg = img[y_min:y_max, x_min:x_max].copy()
gray = cv.cvtColor(fimg, cv.COLOR_RGB2GRAY)
face_img.append(gray)
logging.info('Uploading faces...')
bucket_dst = sclient.get_bucket('up_teaching_face')
for i, face in enumerate(face_img):
cv.imwrite('/tmp/face.png', face)
blob_face = storage.Blob(img_name + '.' + str(i) + '.png', bucket_dst)
blob_face.upload_from_filename('/tmp/face.png')
logging.info('done.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment