10000 Vision face tutorial [(#880)](https://github.com/GoogleCloudPlatform/… · busunkim96/python-vision@f54c7bf · GitHub
[go: up one dir, main page]

Skip to content

Commit f54c7bf

Browse files
gguussdpebot
authored andcommitted
Vision face tutorial [(#880)](GoogleCloudPlatform/python-docs-samples#880)
* Updates sample to use the Cloud client library * Nits found after commit * Nudge for travis * flake8 hates my face
1 parent d4517f5 commit f54c7bf

File tree

7 files changed

+252
-0
lines changed

7 files changed

+252
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
out.jpg
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
.. This file is automatically generated. Do not edit this file directly.
2+
3+
Google Cloud Vision API Python Samples
4+
===============================================================================
5+
6+
This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content
7+
8+
9+
This sample demonstrates how to use the Cloud Vision API to do face detection.
10+
11+
12+
.. _Google Cloud Vision API: https://cloud.google.com/vision/docs
13+
14+
Setup
15+
-------------------------------------------------------------------------------
16+
17+
18+
Authentication
19+
++++++++++++++
20+
21+
Authentication is typically done through `Application Default Credentials`_,
22+
which means you do not have to change the code to authenticate as long as
23+
your environment has credentials. You have a few options for setting up
24+
authentication:
25+
26+
#. When running locally, use the `Google Cloud SDK`_
27+
28+
.. code-block:: bash
29+
30+
gcloud beta auth application-default login
31+
32+
33+
#. When running on App Engine or Compute Engine, credentials are already
34+
set-up. However, you may need to configure your Compute Engine instance
35+
with `additional scopes`_.
36+
37+
#. You can create a `Service Account key file`_. This file can be used to
38+
authenticate to Google Cloud Platform services from any environment. To use
39+
the file, set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to
40+
the path to the key file, for example:
41+
42+
.. code-block:: bash
43+
44+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json
45+
46+
.. _Application Default Credentials: https://cloud.google.com/docs/authentication#getting_credentials_for_server-centric_flow
47+
.. _additional scopes: https://cloud.google.com/compute/docs/authentication#using
48+
.. _Service Account key file: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
49+
50+
Install Dependencies
51+
++++++++++++++++++++
52+
53+
#. Install `pip`_ and `virtualenv`_ if you do not already have them.
54+
55+
#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
56+
57+
.. code-block:: bash
58+
59+
$ virtualenv env
60+
$ source env/bin/activate
61+
62+
#. Install the dependencies needed to run the samples.
63+
64+
.. code-block:: bash
65+
66+
$ pip install -r requirements.txt
67+
68+
.. _pip: https://pip.pypa.io/
69+
.. _virtualenv: https://virtualenv.pypa.io/
70+
71+
Samples
72+
-------------------------------------------------------------------------------
73+
74+
Face detection
75+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
76+
77+
78+
79+
To run this sample:
80+
81+
.. code-block:: bash
82+
83+
$ python faces.py
84+
85+
usage: faces.py [-h] [--out OUTPUT] [--max-results MAX_RESULTS] input_image
86+
87+
Detects faces in the given image.
88+
89+
positional arguments:
90+
input_image the image you'd like to detect faces in.
91+
92+
optional arguments:
93+
-h, --help show this help message and exit
94+
--out OUTPUT the name of the output file.
95+
--max-results MAX_RESULTS
96+
the max results of face detection.
97+
98+
99+
100+
101+
.. _Google Cloud SDK: https://cloud.google.com/sdk/
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# This file is used to generate README.rst
2+
3+
product:
4+
name: Google Cloud Vision API
5+
short_name: Cloud Vision API
6+
url: https://cloud.google.com/vision/docs
7+
description: >
8+
`Google Cloud Vision API`_ allows developers to easily integrate vision
9+
detection features within applications, including image labeling, face and
10+
landmark detection, optical character recognition (OCR), and tagging of
11+
explicit content
12+
13+
description: >
14+
This sample demonstrates how to use the Cloud Vision API to do face detection.
15+
16+
setup:
17+
- auth
18+
- install_deps
19+
20+
samples:
21+
- name: Face detection
22+
file: faces.py
23+
show_help: true
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2015 Google, Inc
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Draws squares around detected faces in the given image."""
18+
19+
import argparse
20+
21+
from google.cloud import vision
22+
from PIL import Image, ImageDraw
23+
24+
25+
def detect_face(face_file, max_results=4):
26+
"""Uses the Vision API to detect faces in the given file.
27+
28+
Args:
29+
face_file: A file-like object containing an image with faces.
30+
31+
Returns:
32+
An array of Face objects with information about the picture.
33+
"""
34+
content = face_file.read()
35+
# [START get_vision_service]
36+
image = vision.Client().image(content=content)
37+
# [END get_vision_service]
38+
39+
return image.detect_faces()
40+
41+
42+
def highlight_faces(image, faces, output_filename):
43+
"""Draws a polygon around the faces, then saves to output_filename.
44+
45+
Args:
46+
image: a file containing the image with the faces.
47+
faces: a list of faces found in the file. This should be in the format
48+
returned by the Vision API.
49+
output_filename: the name of the image file to be created, where the
50+
faces have polygons drawn around them.
51+
"""
52+
im = Image.open(image)
53+
draw = ImageDraw.Draw(im)
54+
55+
for face in faces:
56+
box = [(bound.x_coordinate, bound.y_coordinate)
57+
for bound in face.bounds.vertices]
58+
draw.line(box + [box[0]], width=5, fill='#00ff00')
59+
60+
im.save(output_filename)
61+
62+
63+
def main(input_filename, output_filename, max_results):
64+
with open(input_filename, 'rb') as image:
65+
faces = detect_face(image, max_results)
66+
print('Found {} face{}'.format(
67+
len(faces), '' if len(faces) == 1 else 's'))
68+
69+
print('Writing to file {}'.format(output_filename))
70+
# Reset the file pointer, so we can read the file again
71+
image.seek(0)
72+
highlight_faces(image, faces, output_filename)
73+
74+
75+
if __name__ == '__main__':
76+
parser = argparse.ArgumentParser(
77+
description='Detects faces in the given image.')
78+
parser.add_argument(
79+
'input_image', help='the image you\'d like to detect faces in.')
80+
parser.add_argument(
81+
'--out', dest='output', default='out.jpg',
82+
help='the name of the output file.')
83+
parser.add_argument(
84+
'--max-results', dest='max_results', default=4,
85+
help='the max results of face detection.')
86+
args = parser.parse_args()
87+
88+
main(args.input_image, args.output, args.max_results)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright 2016, Google, Inc.
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
import os
15+
16+
from PIL import Image
17+
18+
from faces import main
19+
20+
21+
def test_main(resource, tmpdir):
22+
out_file = os.path.join(tmpdir.dirname, 'face-output.jpg')
23+
in_file = resource('face-input.jpg')
24+
25+
# Make sure there isn't already a green box
26+
im = Image.open(in_file)
27+
pixels = im.getdata()
28+
greens = sum(1 for (r, g, b) in pixels if r == 0 and g == 255 and b == 0)
29+
assert greens < 1
30+
31+
main(in_file, out_file, 10)
32+
33+
# Make sure there now is some green drawn
34+
im = Image.open(out_file)
35+
pixels = im.getdata()
36+
greens = sum(1 for (r, g, b) in pixels if r == 0 and g == 255 and b == 0)
37+
assert greens > 10
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
google-cloud-vision==0.23.3
2+
Pillow==4.0.0
Loading

0 commit comments

Comments
 (0)
0