-
Notifications
You must be signed in to change notification settings - Fork 0
/
detect_faces.py
102 lines (80 loc) · 2.77 KB
/
detect_faces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# -*- coding: utf-8 -*-
import logging
import requests
import os
import time
import io
import sys
import tensorflow as tf
from PIL import Image
FACE_API_URL = 'https://api.projectoxford.ai/face/v1.0/detect'
FACE_API_KEY = ''
FACE_API_HEADERS = {
'Content-Type' : 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : FACE_API_KEY
}
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('photo_dir', '/tmp/photos',
"""Directory where save photo.""")
tf.app.flags.DEFINE_string('face_dir', '/tmp/faces',
"""Directory where output the face.""")
tf.app.flags.DEFINE_string('api_key', 'xxxxxxxxxx',
"""Face API key.""")
MAX_PHOTO_SIZE = 1024
MIN_PHOTO_SIZE = 36
def detect_faces(img):
data = io.BytesIO()
img.save(data, format='JPEG')
r = requests.post(FACE_API_URL, headers=FACE_API_HEADERS, data=data.getvalue())
print 'status:{} text:{}'.format(r.status_code, r.text)
# check status code
if r.status_code != requests.codes.ok:
r.raise_for_status()
return r.json()
def fetch_and_save_faces_from_photo(img, faces):
# processing image
for item in faces:
faceId = item['faceId']
rect = item['faceRectangle']
left = rect['left']
top = rect['top']
right = left + rect['width']
lower = top + rect['height']
face = img.crop((left, top, right, lower))
face.save(os.path.join(FACES_DIR, faceId + '.jpg'), 'JPEG')
def main(args=None):
t = time.time()
step = 0
filenames = os.listdir(PHOTO_DIR)
for filename in filenames:
step = step + 1
print 'index: {} filename: {}'.format(step, filename)
img = Image.open(os.path.join(PHOTO_DIR, filename))
print 'original size: {}'.format(img.size)
width, height = img.size
if max(width, height) > MAX_PHOTO_SIZE:
ratio = min(MAX_PHOTO_SIZE / float(width), MAX_PHOTO_SIZE / float(height))
scaledSize = (int(width * ratio), int(height * ratio))
print 'scaled size: {}'.format(scaledSize)
img = img.resize(scaledSize, Image.ANTIALIAS)
try:
faces = detect_faces(img)
except Exception as e:
print e
continue
fetch_and_save_faces_from_photo(img, faces)
if step % 5 == 0:
print 'sleeping ...'
time.sleep(5)
# if step % 20 == 0:
# interval = int(time.time() - t);
# print 'interval: {}'.format(interval)
#
# if interval < 60:
# sleep = 60 - interval
# print 'sleep: {} secs'.format(sleep)
# time.sleep(sleep)
#
# t = time.time()
if __name__ == '__main__':
tf.app.run()