Skip to content

Instantly share code, notes, and snippets.

@meganspeir
Created October 29, 2015 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save meganspeir/f1037370441360e81806 to your computer and use it in GitHub Desktop.
Save meganspeir/f1037370441360e81806 to your computer and use it in GitHub Desktop.
The Martian
import requests
from flask import Flask
from flask import request, send_from_directory
from twilio import twiml
from martianify import martianify
UPLOAD_FOLDER = '/path/to/your/project/'
# App declaration and configuration
app = Flask(__name__)
app.config
# SMS/MMS Request URL
@app.route('/sms', methods=['POST', 'GET'])
def sms():
response = twiml.Response()
response.message("Please wait for launch 3, 2, 1...")
if request.form['NumMedia'] != '0':
filename = request.form['MessageSid'] + '.jpg'
f = open(filename, 'wb')
f.write(requests.get(request.form['MediaUrl0']).content)
f.close()
martianify('/path/to/your/project/{}'.format(filename))
with response.message() as message:
message.body = "{0}".format("Welcome to Mars.")
message.media('http://YourNgrokUrl/uploads/{}'.format(filename))
else:
response.message("Face forward and text me a selfie!")
return str(response)
# Martian Media URL
@app.route('/uploads/<filename>', methods=['GET', 'POST'])
def uploaded_file(filename):
return send_from_directory(UPLOAD_FOLDER,
filename)
if __name__ == "__main__":
app.debug = True
app.run()
import cv2
def martianify(original_image_path):
# Load the face detection cascade file.
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/2.4.12/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
# Load our Martian as foreground image with alpha transparency.
# The -1 reads the alpha transparency of our image otherwise known as the face hole.
foreground_image = cv2.imread('/Users/sagnew/Downloads/martian.png', -1)
# Create foreground mask from alpha transparency.
foreground_mask = foreground_image[:, :, 3]
# Create inverted background mask.
background_mask = cv2.bitwise_not(foreground_mask)
# Convert foreground image to BGR.
foreground_image = foreground_image[:, :, 0:3]
# Declare foreground size.
foreground_size = 630
foreground_ratio = float(foreground_size)
# Declare background size and padding.
background_size = 1100
padding_top = ((background_size - foreground_size) / 3) * 2
padding_bottom = background_size - padding_top
padding_left = (background_size - foreground_size) / 2
padding_right = (background_size - foreground_size) / 2
# Capture selfie image in OpenCV.
cv_image = cv2.imread(original_image_path)
# Find that face.
faces = face_cascade.detectMultiScale(
cv_image,
scaleFactor=1.1,
minNeighbors=3,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Iterate over each face found - roi: region of interest
for (x1, y1, w, h) in faces:
# Extract image of face.
x2 = x1 + w
y2 = y1 + h
face_roi = cv_image[y1:y2, x1:x2]
# Resize image of face.
ratio = foreground_ratio / face_roi.shape[1]
dimension = (foreground_size, int(face_roi.shape[0] * ratio))
face = cv2.resize(face_roi, dimension, interpolation = cv2.INTER_AREA)
# Add padding to background image
background_image = cv2.copyMakeBorder(face, padding_top, padding_bottom,
padding_left, padding_right, cv2.BORDER_CONSTANT)
# Region of interest for Martian from background proportional to martian size.
background_src = background_image[0:background_size, 0:background_size]
# roi_bg contains the original image only where the martian is not
# in the region that is the size of the Martian.
roi_bg = cv2.bitwise_and(background_src, background_src, mask=background_mask)
# roi_fg contains the image of the Martian only where Martian is
roi_fg = cv2.bitwise_and(foreground_image, foreground_image, mask=foreground_mask)
# Join the roi_bg and roi_fg.
dst = cv2.add(roi_bg, roi_fg)
# Write the final image back to file path, overwriting original image.
cv2.imwrite(original_image_path, dst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment