Created
July 21, 2017 17:52
-
-
Save mcdickenson/8895a75871ec514cc384506e0ff2a852 to your computer and use it in GitHub Desktop.
Blur faces in imagery with Google Cloud Vision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import io | |
import json | |
import numpy as np | |
import os | |
from google.cloud import vision | |
from PIL import Image, ImageDraw | |
from StringIO import StringIO | |
# Load the image into memory | |
def load_image(img_filename): | |
with io.open(img_filename, 'rb') as image_file: | |
content = image_file.read() | |
return content | |
# Helper function to label an image | |
def label_image(client, content): | |
image = client.image(content=content) | |
# Perform face detection on the image file | |
faces = image.detect_faces() | |
return faces | |
# Blur faces in the image | |
def blur_image(image_content, faces, output_path): | |
img = Image.open(StringIO(image_content)) | |
img = np.array(img) | |
# RGB/BGR channel flip for PIL-OpenCV compatibility | |
img = img[:, :, ::-1] | |
for face in faces: | |
box = [(bound.x_coordinate, bound.y_coordinate) | |
for bound in face.bounds.vertices] | |
top_left = box[0] | |
bottom_right = box[2] | |
x = top_left[0] | |
y = top_left[1] | |
w = bottom_right[0] - top_left[0] | |
h = bottom_right[1] - top_left[1] | |
roi = img[y:y+h, x:x+w] | |
roi_blurred = cv2.blur(roi, (15,15)) | |
img[y:y+h, x:x+w] = roi_blurred | |
return img | |
# Mapping between blurred and unblurred imagery | |
def image_path_to_output_path(image_path): | |
fname, ext = image_path.split('.') | |
fname += '_blurred' | |
output_path = '.'.join([fname, ext]) | |
return output_path | |
# Instantiate a client | |
vision_client = vision.Client() | |
# Set up image paths | |
image_paths = ['img/car.png'] | |
for image_path in image_paths: | |
output_path = image_path_to_output_path(image_path) | |
print 'Loading {}'.format(image_path) | |
image_content = load_image(image_path) | |
print 'Labeling {}'.format(image_path) | |
faces = label_image(vision_client, image_content) | |
print 'Blurring {}'.format(image_path) | |
blurred = blur_image(image_content, faces, output_path) | |
print 'Saving {}'.format(output_path) | |
cv2.imwrite(output_path, blurred) | |
# If you need to rate limit (10 req/sec), uncomment this | |
# time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment