Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save OzTamir/0a00f62b0b0a0ae81ed0 to your computer and use it in GitHub Desktop.

Select an option

Save OzTamir/0a00f62b0b0a0ae81ed0 to your computer and use it in GitHub Desktop.
Warning: This script will make you cry
from PIL import Image
import urllib
import urllib2
import json
import os
import sys
API_ENDPOINT = 'http://rekognition.com/func/api/?'
TEAR_IMG_URL = 'http://i.imgur.com/7VAlEVf.png'
API_KEY = ''
API_SECRET = ''
def encode_request_url(img_url):
''' Get the request URL '''
req_params = {
'api_key' : API_KEY,
'api_secret' : API_SECRET,
'jobs' : 'face_part',
'urls' : img_url
}
return API_ENDPOINT + urllib.urlencode(req_params)
def get_face_data(url):
''' Get the face recognition data from the API '''
response = urllib2.urlopen(url)
data = json.load(response)
try:
return data['face_detection'][0]
except IndexError:
print 'No Faces found.'
sys.exit(0)
def get_image(url, name=None):
''' Download the image to the CWD '''
if name is None:
name = url.split('/')[-1]
with open(name,'wb') as f:
f.write(urllib.urlopen(url).read())
return name
def add_tear(picname, data, tear_file, eye_side):
''' Add the tear '''
path = os.path.dirname(os.path.abspath(__file__))
picname = os.path.join(path, picname)
tear_file = os.path.join(path, tear_file)
background = Image.open(picname)
foreground = Image.open(tear_file)
factor = 2.0
try:
ratio_h = int(data['eye_left']['y']) / 4
except KeyError:
print 'No faces found.'
return
ratio_w = int((float(foreground.size[0]) * float(ratio_h) / 100.0)) / 4
foreground = foreground.resize((ratio_w, ratio_h))
if eye_side == 'l':
eye = (max(int(data['eye_left']['x']) - int(foreground.size[0] / factor * 2), 0), int(data['eye_left']['y']) + int(foreground.size[1] / (factor * 2)))
else:
eye = (max(int(data['eye_right']['x']) - int(foreground.size[0] / factor * 2), 0), int(data['eye_right']['y']) + int(foreground.size[1] / (factor * 2)))
background.paste(foreground, eye, foreground)
background.show()
background.save(picname)
def main(image_url, side='l'):
print 'Downloading image...'
picname = get_image(image_url)
print 'Saved as %s' % picname
tear_file_name = get_image(TEAR_IMG_URL, 'tear.png')
url = encode_request_url(image_url)
print 'Getting face data...'
face_data = get_face_data(url)
print 'Meshing...'
add_tear(picname, face_data, tear_file_name, side)
if __name__ == '__main__':
if len(sys.argv) < 2 or len(sys.argv) > 3:
print 'Usage: python cry.py IMAGE_URL [LR]'
sys.exit(1)
print 'URL: %s' % sys.argv[1]
if len(sys.argv) == 2:
main(sys.argv[1])
elif len(sys.argv) == 3:
main(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment