Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!
In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.
There are three main parts to this project:
Part 1 : Investigating OpenCV, pre-processing, and face detection
Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints
Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!
*Here's what you need to know to complete the project:
In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.
a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.
a. Each section where you will answer a question is preceded by a 'Question X' header.
b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.
Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.
Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.
In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!
The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.
Part 1 : Investigating OpenCV, pre-processing, and face detection
Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints
Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!
Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.
At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.
We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures
directory.
In [1]:
# Import required libraries for this section
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import math
import cv2 # OpenCV library for computer vision
from PIL import Image
import time
Next, we load in and display a test image for performing face detection.
Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor
function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.
In [2]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[2]:
There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.
This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.
Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!
To learn more about the parameters of the detector see this post.
In [3]:
# Convert the RGB image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Out[3]:
In the above code, faces
is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x
and y
) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w
and h
) specify the width and height of the box.
There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.
To test your eye detector, we'll first read in a new test image with just a single face.
In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.
So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.
In [5]:
# Convert the RGB image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Out[5]:
To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml
, located in the detector_architectures
subdirectory. In the next code cell, create your eye detector and store its detections.
A few notes before you get started:
First, make sure to give your loaded eye detector the variable name
eye_cascade
and give the list of eye regions you detect the variable name
eyes
Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces
. This will minimize false detections.
Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.
In [6]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)
# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)
# Do not change the code above this comment!
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
eyes = eye_cascade.detectMultiScale(gray, 1.20, 6)
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
for (x,y,w,h) in eyes:
for (fx, fy, fw, fh) in faces:
# check coordinates are within face bounds
if x >= fx and x <= fx+fw and y >= fy and y <= fy+fh:
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(0,255,0), 3)
# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Out[6]:
It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!
Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.
The next cell contains code for a wrapper function called laptop_camera_face_eye_detector
that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.
Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.
Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!
In [7]:
### Add face and eye detection to this laptop camera function
# Make sure to draw out all faces/eyes found in each frame on the shown video feed
import cv2
import time
# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep the video stream open
while rval:
# Plot the image from camera with all the face and eye detections marked
cv2.imshow("face detection activated", frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # Exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
# Make sure window closes on OSx
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
In [8]:
# Call the laptop camera face/eye detector function above
#laptop_camera_go()
Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!
When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.
In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.
In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.
In [9]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')
# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Make an array copy of this image
image_with_noise = np.asarray(image)
# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level
# Add this noise to the array image copy
image_with_noise = image_with_noise + noise
# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])
# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[9]:
In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.
In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.
In [10]:
# Convert the RGB image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Out[10]:
With this added noise we now miss one of the faces!
Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored
- de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.
You can find its official documentation here and a useful example here.
Note: you can keep all parameters except photo_render
fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.
In [11]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!
denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise, None, 20, 15, 21, 7)
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Denoised Image')
ax1.imshow(denoised_image)
Out[11]:
In [12]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result
# Convert the RGB image to grayscale
gray_noise = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
denoised_image_with_detections = np.copy(denoised_image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(denoised_image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(denoised_image_with_detections)
Out[12]:
Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!
Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.
Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.
Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.
Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.
In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.
In [16]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')
# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Perform Canny edge detection
edges = cv2.Canny(gray, 100, 200)
# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)
# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[16]:
Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).
In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.
Blur the image by using OpenCV's filter2d
functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.
In [44]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality,
# Use an averaging kernel, and a kernel width equal to 4
# Load in the image
image = cv2.imread('images/fawzia.jpg')
# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
width = 4
kernel = np.ones((width, width),np.float32)/16
dst = cv2.filter2D(image, -1, kernel)
## TODO: Then perform Canny edge detection and display the output
# Convert to grayscale
gray = cv2.cvtColor(dst, cv2.COLOR_RGB2GRAY)
# Perform Canny edge detection
edges = cv2.Canny(gray, 50, 200)
# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)
# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[44]:
If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.
Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D
to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.
In [15]:
# Load in the image
image = cv2.imread('images/gus.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[15]:
In [16]:
## TODO: Implement face detection
def blur_face(image, denoiser):
denoised_image = denoiser(image)
gray = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.1, 10)
# Make a copy of the orginal image to blur
final_image = np.copy(image)
## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
width = 60
kernel = np.ones((width, width),np.float32) / 3600
image_with_blur = cv2.filter2D(image, -1, kernel)
for (x,y,w,h) in faces:
padding = 30
x_start = max(x - padding, 0)
y_start = max(y - padding, 0)
x_end = min(x + w + padding, image.shape[1])
y_end = min(y + h + padding, image.shape[0])
final_image[y_start:y_end, x_start:x_end] = cv2.filter2D(image_with_blur[y_start:y_end, x_start:x_end], -1, kernel)
return final_image
def denoiser(image):
return cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 21, 7)
final_image = blur_face(image, denoiser)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Blurred Face')
ax1.imshow(final_image)
Out[16]:
In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.
As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.
The next cell contains code a wrapper function called laptop_camera_identity_hider
that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.
Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.
Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!
In [17]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time
# tweaked to my camera / lighting at the time of development
def denoiser_laptop(image):
return cv2.fastNlMeansDenoisingColored(image, None, 20, 20, 21, 7)
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep video stream open
while rval:
# Plot image from camera with detections marked
blur_frame = blur_face(frame, denoiser_laptop)
cv2.imshow("face detection activated", blur_frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # Exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
In [18]:
# Run laptop identity hider
# laptop_camera_go()
OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.
You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.
Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.
Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.
But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.
In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data
directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.
To load in this data, run the Python cell below - notice we will load in both the training and testing sets.
The load_data
function is in the included utils.py
file.
In [19]:
from utils import *
# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
y_train.shape, y_train.min(), y_train.max()))
# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
The load_data
function in utils.py
originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.
Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data
function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data
function to include the incomplete data points.
In [20]:
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_train[i], y_train[i], ax)
For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.
Review the plot_data
function in utils.py
to understand how the 30-dimensional training labels in y_train
are mapped to facial locations, as this function will prove useful for your pipeline.
In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.
Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.
In [21]:
# helpers for training CNNs
import keras
import timeit
# graph the history of model.fit
def show_history_graph(history, extra=''):
# summarize history for accuracy
print(history.history.keys())
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title(f'model accuracy {extra}')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
# summarize history for mean absolute error
plt.plot(history.history['mean_absolute_error'])
plt.plot(history.history['val_mean_absolute_error'])
plt.title(f'model mean absolute error {extra}')
plt.ylabel('error')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
# summarize history for mean absolute error
plt.plot(history.history['mean_squared_error'])
plt.plot(history.history['val_mean_squared_error'])
plt.title(f'model mean squared error {extra}')
plt.ylabel('error')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title(f'model loss {extra}')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
In [22]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
# TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)
# This is the lasagne network from:
# http://danielnouri.org/notes/2014/12/17/using-convolutional-neural-nets-to-detect-facial-keypoints-tutorial/
# pretty straight forwards Conv2D Max Pool type CNN network
# layers=[
# ('input', layers.InputLayer),
# ('conv1', layers.Conv2DLayer),
# ('pool1', layers.MaxPool2DLayer),
# ('conv2', layers.Conv2DLayer),
# ('pool2', layers.MaxPool2DLayer),
# ('conv3', layers.Conv2DLayer),
# ('pool3', layers.MaxPool2DLayer),
# ('hidden4', layers.DenseLayer),
# ('hidden5', layers.DenseLayer),
# ('output', layers.DenseLayer),
# ],
# input_shape=(None, 1, 96, 96),
# conv1_num_filters=32, conv1_filter_size=(3, 3), pool1_pool_size=(2, 2),
# conv2_num_filters=64, conv2_filter_size=(2, 2), pool2_pool_size=(2, 2),
# conv3_num_filters=128, conv3_filter_size=(2, 2), pool3_pool_size=(2, 2),
# hidden4_num_units=500, hidden5_num_units=500,
# output_num_units=30, output_nonlinearity=None,
model = Sequential()
model.add(Convolution2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(filters=128, kernel_size=(2, 2), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512)) # base 2 rather than 500 in lasagne network
model.add(Dense(512)) # base 2 rather than 500 in lasagne network
model.add(Dense(30))
# Summarize the model
model.summary()
Use the compile
method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD
vs. RMSprop
, etc), but take the time to empirically verify your theories.
Use the fit
method to train the model. Break off a validation set by setting validation_split=0.2
. Save the returned History
object in the history
variable.
Your model is required to attain a validation loss (measured as mean squared error) of at least XYZ. When you have finished training, save your model as an HDF5 file with file path my_model.h5
.
In [23]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam
optimizers = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam', 'Nesterov']
mse_history = {}
epochs = 10
for optimizer in optimizers:
# the lasagne network suggested using SGD Nesterov with lr 0.01 and momentum 0.9
# CS231n Recommends: http://cs231n.github.io/neural-networks-3/#summary
# The two recommended updates to use are either SGD+Nesterov Momentum or Adam.
if optimizer == 'Nesterov':
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
else:
opt = optimizer
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mse'])
hist = model.fit(X_train, y_train, validation_split=0.2, epochs=epochs, verbose=0)
mse_history[optimizer] = hist.history['mean_squared_error']
In [24]:
legend = []
plt.figure(figsize=(20, 10))
for key, opt in mse_history.items():
plt.plot(opt)
legend.append(key)
plt.title(f'optimizer mean squared error')
plt.ylabel('mean squared error')
plt.xlabel('epoch')
plt.legend(legend, loc='upper right')
plt.ylim(0, 0.01)
plt.show()
In [ ]:
# Adam / Adamax seem to be doing the best here
In [31]:
model2 = Sequential()
model2.add(Convolution2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model2.add(MaxPooling2D(pool_size=(2, 2)))
model2.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model2.add(MaxPooling2D(pool_size=(2, 2)))
model2.add(Convolution2D(filters=128, kernel_size=(2, 2), activation='relu'))
model2.add(MaxPooling2D(pool_size=(2, 2)))
model2.add(Flatten())
model2.add(Dense(512)) # base 2 rather than 500 in lasagne network
model2.add(Dense(512)) # base 2 rather than 500 in lasagne network
model2.add(Dense(30))
# Summarize the model
model2.summary()
opt = 'Adamax'
epochs = 10
model2.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model2.fit(X_train, y_train, validation_split=0.2, epochs=epochs, shuffle=True)
show_history_graph(hist)
In [ ]:
# Seems to be converging okay, lets try adding some dropout
In [32]:
model3 = Sequential()
model3.add(Convolution2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model3.add(MaxPooling2D(pool_size=(2, 2)))
model3.add(Dropout(0.5))
model3.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model3.add(MaxPooling2D(pool_size=(2, 2)))
model3.add(Dropout(0.5))
model3.add(Convolution2D(filters=128, kernel_size=(2, 2), activation='relu'))
model3.add(MaxPooling2D(pool_size=(2, 2)))
model3.add(Dropout(0.5))
model3.add(Flatten())
model3.add(Dense(512)) # base 2 rather than 500 in lasagne network
model3.add(Dropout(0.5))
model3.add(Dense(512)) # base 2 rather than 500 in lasagne network
model3.add(Dropout(0.5))
model3.add(Dense(30))
# Summarize the model
model3.summary()
In [33]:
opt = 'Adamax'
epochs = 10
model3.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model3.fit(X_train, y_train, validation_split=0.2, epochs=epochs, shuffle=True)
show_history_graph(hist)
In [34]:
# something weird going on lets try more dimensionality reduction
In [35]:
model4 = Sequential()
model4.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model4.add(MaxPooling2D(pool_size=(2, 2)))
model4.add(Dropout(0.5))
model4.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model4.add(MaxPooling2D(pool_size=(2, 2)))
model4.add(Dropout(0.5))
model4.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model4.add(MaxPooling2D(pool_size=(2, 2)))
model4.add(Dropout(0.5))
model4.add(Flatten())
model4.add(Dense(512)) # base 2 rather than 500 in lasagne network
model4.add(Dropout(0.5))
model4.add(Dense(30))
# Summarize the model
model4.summary()
In [36]:
opt = 'Adamax'
epochs = 10
model4.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model4.fit(X_train, y_train, validation_split=0.2, epochs=epochs, shuffle=True)
show_history_graph(hist)
In [37]:
# lets reduce it more
In [38]:
model5 = Sequential()
model5.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model5.add(MaxPooling2D(pool_size=(2, 2)))
model5.add(Dropout(0.5))
model5.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model5.add(MaxPooling2D(pool_size=(2, 2)))
model5.add(Dropout(0.5))
model5.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model5.add(MaxPooling2D(pool_size=(2, 2)))
model5.add(Dropout(0.5))
model5.add(Flatten())
model5.add(Dense(256))
model5.add(Dropout(0.5))
model5.add(Dense(30))
# Summarize the model
model5.summary()
In [ ]:
In [39]:
opt = 'Adamax'
epochs = 30
model5.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model5.fit(X_train, y_train, validation_split=0.2, epochs=epochs, shuffle=True)
show_history_graph(hist)
In [41]:
model6 = Sequential()
model6.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model6.add(MaxPooling2D(pool_size=(2, 2)))
model6.add(Dropout(0.5))
model6.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model6.add(MaxPooling2D(pool_size=(2, 2)))
model6.add(Dropout(0.5))
model6.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model6.add(MaxPooling2D(pool_size=(2, 2)))
model6.add(Dropout(0.5))
model6.add(Flatten())
model6.add(Dense(256))
model6.add(Dropout(0.5))
model6.add(Dense(30))
# Summarize the model
model6.summary()
In [42]:
# lets see nesterov momentum for comparison
In [43]:
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
epochs = 30
model6.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model6.fit(X_train, y_train, validation_split=0.2, epochs=epochs, shuffle=True)
show_history_graph(hist)
In [ ]:
# the two look quite similar, but the accuracy looks like its overfitting and not generalizing properly
# lets try making the drop out more progressive
In [45]:
model7 = Sequential()
model7.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model7.add(MaxPooling2D(pool_size=(2, 2)))
model7.add(Dropout(0.1))
model7.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model7.add(MaxPooling2D(pool_size=(2, 2)))
model7.add(Dropout(0.2))
model7.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model7.add(MaxPooling2D(pool_size=(2, 2)))
model7.add(Dropout(0.3))
model7.add(Flatten())
model7.add(Dense(256))
model7.add(Dropout(0.5))
model7.add(Dense(30))
# Summarize the model
model7.summary()
In [46]:
opt = 'Adamax'
epochs = 30
model7.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model7.fit(X_train, y_train, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [ ]:
# better, also looks like we could try relu activation on the hidden fully connected layer
In [47]:
model8 = Sequential()
model8.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model8.add(MaxPooling2D(pool_size=(2, 2)))
model8.add(Dropout(0.1))
model8.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model8.add(MaxPooling2D(pool_size=(2, 2)))
model8.add(Dropout(0.2))
model8.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model8.add(MaxPooling2D(pool_size=(2, 2)))
model8.add(Dropout(0.3))
model8.add(Flatten())
model8.add(Dense(256, activation='relu'))
model8.add(Dropout(0.5))
model8.add(Dense(30))
# Summarize the model
model8.summary()
opt = 'Adamax'
epochs = 30
model8.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model8.fit(X_train, y_train, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [ ]:
In [48]:
# lets add more data with data augmentation by horizontally flipping all the images and labels
In [49]:
X_train.shape
Out[49]:
In [50]:
X_train_flipped = np.flip(np.copy(X_train), axis=2)
In [51]:
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_train_flipped[i], y_train[i], ax)
In [52]:
y_train.shape
Out[52]:
In [53]:
# now we need to flip the x values which are even indexes
flipped_indices = [
(0, 2), (1, 3),
(4, 8), (5, 9), (6, 10), (7, 11),
(12, 16), (13, 17), (14, 18), (15, 19),
(22, 24), (23, 25)
]
y_train_flipped = np.copy(y_train)
points = y_train_flipped.shape[1]
for i in range(len(y_train_flipped)):
for x in range(0, points, 2):
y_train_flipped[i][x] *= -1
for (a, b) in flipped_indices:
y_train_flipped[i][a], y_train_flipped[i][b] = y_train_flipped[i][b], y_train_flipped[i][a]
In [54]:
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_train_flipped[i], y_train_flipped[i], ax)
In [55]:
#combine data sets
In [56]:
X_train_all = np.concatenate((X_train, X_train_flipped), axis=0)
y_train_all = np.concatenate((y_train, y_train_flipped), axis=0)
# from sklearn.utils import shuffle
# X_train_all, y_train_all = shuffle(X_train_all, y_train_all, random_state=42)
In [57]:
# make sure we didn't stuff anything up
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_train_all[i], y_train_all[i], ax)
In [285]:
X_train_all.shape
Out[285]:
In [58]:
model9 = Sequential()
model9.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model9.add(MaxPooling2D(pool_size=(2, 2)))
model9.add(Dropout(0.1))
model9.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model9.add(MaxPooling2D(pool_size=(2, 2)))
model9.add(Dropout(0.2))
model9.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model9.add(MaxPooling2D(pool_size=(2, 2)))
model9.add(Dropout(0.3))
model9.add(Flatten())
model9.add(Dense(256, activation='relu'))
model9.add(Dropout(0.5))
model9.add(Dense(30))
# Summarize the model
model9.summary()
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
epochs = 50
model9.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model9.fit(X_train, y_train, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [ ]:
In [59]:
model10 = Sequential()
model10.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model10.add(MaxPooling2D(pool_size=(2, 2)))
model10.add(Dropout(0.1))
model10.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model10.add(MaxPooling2D(pool_size=(2, 2)))
model10.add(Dropout(0.2))
model10.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model10.add(MaxPooling2D(pool_size=(2, 2)))
model10.add(Dropout(0.3))
model10.add(Flatten())
model10.add(Dense(256, activation='relu'))
model10.add(Dropout(0.5))
model10.add(Dense(30))
# Summarize the model
model10.summary()
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
epochs = 50
model10.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model10.fit(X_train_all, y_train_all, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [60]:
model11 = Sequential()
model11.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model11.add(MaxPooling2D(pool_size=(2, 2)))
model11.add(Dropout(0.1))
model11.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model11.add(MaxPooling2D(pool_size=(2, 2)))
model11.add(Dropout(0.2))
model11.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model11.add(MaxPooling2D(pool_size=(2, 2)))
model11.add(Dropout(0.3))
model11.add(Flatten())
model11.add(Dense(256, activation='relu'))
model11.add(Dropout(0.5))
model11.add(Dense(30))
# Summarize the model
model11.summary()
opt = 'Adamax'
epochs = 50
model11.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model11.fit(X_train, y_train, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [61]:
model12 = Sequential()
model12.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model12.add(MaxPooling2D(pool_size=(2, 2)))
model12.add(Dropout(0.1))
model12.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model12.add(MaxPooling2D(pool_size=(2, 2)))
model12.add(Dropout(0.2))
model12.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model12.add(MaxPooling2D(pool_size=(2, 2)))
model12.add(Dropout(0.3))
model12.add(Flatten())
model12.add(Dense(256, activation='relu'))
model12.add(Dropout(0.5))
model12.add(Dense(30))
# Summarize the model
model12.summary()
opt = 'Adamax'
epochs = 50
model12.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model12.fit(X_train_all, y_train_all, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [62]:
model13 = Sequential()
model13.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model13.add(MaxPooling2D(pool_size=(2, 2)))
model13.add(Dropout(0.1))
model13.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model13.add(MaxPooling2D(pool_size=(2, 2)))
model13.add(Dropout(0.2))
model13.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model13.add(MaxPooling2D(pool_size=(2, 2)))
model13.add(Dropout(0.3))
model13.add(Flatten())
model13.add(Dense(256, activation='relu'))
model13.add(Dropout(0.5))
model13.add(Dense(30))
# Summarize the model
model13.summary()
opt = 'Adam'
epochs = 50
model13.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model13.fit(X_train_all, y_train_all, validation_split=0.2, epochs=epochs)
show_history_graph(hist)
In [ ]:
# looks like Adamax is still the winner over SGD + Nesterov and using augemented data has improved the validation
# accuracy by almost 7% over the non augmented data to val_acc: 0.7734
# However Adam seems to get slightly better validation accuracy at val_acc: 0.8002
# so lets give it a try on a longer run
In [63]:
model14 = Sequential()
model14.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
model14.add(MaxPooling2D(pool_size=(2, 2)))
model14.add(Dropout(0.1))
model14.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
model14.add(MaxPooling2D(pool_size=(2, 2)))
model14.add(Dropout(0.2))
model14.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
model14.add(MaxPooling2D(pool_size=(2, 2)))
model14.add(Dropout(0.3))
model14.add(Flatten())
model14.add(Dense(256, activation='relu'))
model14.add(Dropout(0.5))
model14.add(Dense(30))
# Summarize the model
model14.summary()
from keras.callbacks import ModelCheckpoint, EarlyStopping
opt = 'Adam'
epochs = 400
early = EarlyStopping(monitor='val_loss', min_delta=0, patience=150, verbose=0, mode='auto')
model_file = './model14_adam_long.hdf5'
checkpointer = ModelCheckpoint(filepath=model_file, verbose=0, save_best_only=True)
model14.compile(loss='mean_squared_error', optimizer=opt, metrics=['acc', 'mae', 'mse'])
hist = model14.fit(X_train_all, y_train_all, validation_split=0.2, epochs=epochs, callbacks=[early, checkpointer], shuffle=True)
show_history_graph(hist)
Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.
Answer:
First I started with the network architecture mentioned in the suggested article:
Its a pretty standard CNN architecture with ReLUs and layers of Convolution and Maxpooling doubling in size for several iterations.
To provide some parameter space for learning so many different x,y coords it seemed like a good idea to include multiple fully connected hidden layers. I changed 500 to 512 just to match the base 2 sizes of everything else.
The end is a fully connected layer with 30 outputs matching the required output and a default linear activation function.
After this I benchmarked several optimizers to see which might be the best for this problem.
It seems that the Adam family was the better choice, although the article suggested SGD + Nesterov as does the Stanford CS231n course.
The model seemed to perform okay so I decided to add dropout putting a 50% dropout on each layer of the network.
The test error and accuracy seems to leap to a point and not improve drastically so I figured it might be worth reducing the number of filters being used and removing one of the hidden fully connected layers.
I did this again by reducing the size of the fully connected hidden layer.
Now it appears to have more of a nice hockey stick curve on the loss graph, although the accuracy for test was leaping to 70% and flatlining which was concerning.
Perhaps it was getting stuck and unable to advance due to the high level of dropout?
Adding a more progressive dropout provided a nicer moving accuracy line.
I added a ReLU activation to the final hidden layer but the affect wasn't hugely apparently.
Then I figured the accuracy wasn't too bad at val_loss: 0.0033, val_acc: 0.6963 so it was time to look at adding some more data with data augmentation.
As discussed in the suggested article I flipped all the images and their key facial points and combined them with the original.
I did try randomizing the combined results but didn't see much affect.
Next I compared SGD + Nesterov and Adamax against 50 epochs with and without the new augmented data.
Adamax still beat SGD + Nesterov as previously and the augmented data provided for an improvement of nearly 7% which is huge, although it could simply be that more of the duplicated data appears in the testing set.
The error was reduced from val_loss: 0.0017 to val_loss: 0.0012.
I also thought it was worth trying Adam and was pleased to see that it was even better than Adamax.
Finally to see where the model can go I trained Adam with 400 epochs, early stopping at 150 epochs without change, and a model checkpointer.
Training stopped at 356 Epochs.
The best result was about: val_loss: 0.00091924 - val_acc: 0.8259.
The predictions are fairly good, although they could still be better in some cases. I think more unique data is required.
The network size and epochs is probably overkill for this accuracy and there is probably a smaller more light weight network which can achieve better more generalized results than this.
Given more time I would try to reduce it to the point where it suffers performance and build it back up from there.
Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?
Answer:
The original article and the Stanford CS231n course both recommend SGD + Nesterov or Adam optimizers for CNN tasks.
For loss function because this is a regression task across 30 continuous x,y pair values rather than a Classification task across 30 discrete labels, it makes sense to use a loss function like mean squared error rather than something like categorical cross entropy.
A quick test of categorical cross entropy showed this in its terrible results.
For optimizers, I tested SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam and SGD + Nesterov.
Looking at the graph of results I chose to do the rest of my development on Adamax and then near the end compared SGD + Nesterov and Adam again to see if there was much difference.
In the end I chose Adam as the results were the best.
Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.
In [64]:
## TODO: Visualize the training and validation loss of your neural network
show_history_graph(hist)
Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).
Answer:
In earlier iterations of the network without dropout it seemed as though there was issues gaining traction with the test accuracy. After reducing the layers and filters and adding progressively increasing dropout I managed to get a nice smooth hockey stick like curve that you can see above.
I would assume that there is some overfitting in the above model for several reasons, one the augmented data is probably leaking into the validation set in a way that prevents good generalization.
In [65]:
y_test = model14.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
plot_data(X_test[i], y_test[i], ax)
With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now
In this Subsection you will do just this!
Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps
Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.
When complete you should be able to produce example images like the one below
In [66]:
from utils import *
# reload model
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
final_model = Sequential()
final_model.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(96, 96, 1)))
final_model.add(MaxPooling2D(pool_size=(2, 2)))
final_model.add(Dropout(0.1))
final_model.add(Convolution2D(filters=32, kernel_size=(2, 2), activation='relu'))
final_model.add(MaxPooling2D(pool_size=(2, 2)))
final_model.add(Dropout(0.2))
final_model.add(Convolution2D(filters=64, kernel_size=(2, 2), activation='relu'))
final_model.add(MaxPooling2D(pool_size=(2, 2)))
final_model.add(Dropout(0.3))
final_model.add(Flatten())
final_model.add(Dense(256, activation='relu'))
final_model.add(Dropout(0.5))
final_model.add(Dense(30))
# Summarize the model
final_model.summary()
final_model_file = './model14_adam_long.hdf5'
final_model.load_weights(final_model_file)
In [67]:
# Accept a color image.
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_copy = np.copy(image)
# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image_copy)
Out[67]:
In [68]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net
## TODO : Paint the predicted keypoints on the test image
# Convert the image to grayscale.
gray = cv2.cvtColor(image_copy, cv2.COLOR_RGB2GRAY)
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# Detect and crop the face contained in the image.
# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)
# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))
# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Out[68]:
In [69]:
# Locate the facial keypoints in the cropped image.
face_patches = []
for (x,y,w,h) in faces:
face_patch = gray[y:y+h, x:x+w]
face_patch = cv2.resize(face_patch, (96, 96))
face_patch = np.expand_dims(face_patch, axis=2)
face_patches.append(face_patch / 255)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(len(face_patches)):
face = face_patches[i]
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
ax.set_title('Face patches in grayscale')
ax.imshow(np.squeeze(face), cmap='gray') # plot the image
In [70]:
# Overlay the facial keypoints in the original (color, uncropped) image.
X_faces = np.asarray(face_patches)
y_faces = final_model.predict(X_faces)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(len(faces)):
ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
ax.set_title('Face patches with keypoints')
plot_data(X_faces[i], y_faces[i], ax)
In [71]:
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
for i in range(len(faces)):
x, y, w, h = faces[i]
x_features = y_faces[i][0::2] * 48 + 48
x_scaled = (x_features * w / 96) + x
y_features = y_faces[i][1::2] * 48 + 48
y_scaled = (y_features * h / 96) + y
ax1.scatter(x_scaled, y_scaled, marker='.', c='w', s=20)
ax1.set_title('Original image with facial keypoints')
ax1.imshow(image)
Out[71]:
In [72]:
import io
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
def keypoint_detection(image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.25, 6)
# Make a copy of the orginal image to draw face detections on
image_draw = np.copy(image)
# Get the bounding box for each detected face
for (x,y,w,h) in faces:
# Add a red bounding box to the detections image
cv2.rectangle(image_draw, (x,y), (x+w,y+h), (255,0,0), 3)
# Locate the facial keypoints in the cropped image.
face_patches = []
for (x,y,w,h) in faces:
face_patch = gray[y:y+h, x:x+w]
face_patch = cv2.resize(face_patch, (96, 96))
face_patch = np.expand_dims(face_patch, axis=2)
face_patches.append(face_patch / 255)
# Overlay the facial keypoints in the original (color, uncropped) image.
X_faces = np.asarray(face_patches)
y_faces = final_model.predict(X_faces)
for i in range(len(faces)):
x, y, w, h = faces[i]
x_features = y_faces[i][0::2] * 48 + 48
x_scaled = (x_features * w / 96) + x
y_features = y_faces[i][1::2] * 48 + 48
y_scaled = (y_features * h / 96) + y
for x, y in zip(x_scaled, y_scaled):
cv2.circle(image_draw, (x, y), 3, (0, 255, 0), -1)
return image_draw
image = cv2.imread('images/obamas4.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
im = keypoint_detection(image)
print(f'Thanks Obama! 😂')
fig = plt.figure(figsize = (20,10))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(im)
Out[72]:
Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.
The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!
In [73]:
import cv2
import time
from keras.models import load_model
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# Try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# keep video stream open
while rval:
# plot image from camera with detections marked
keypoint_frame = keypoint_detection(frame)
cv2.imshow("face detection activated", keypoint_frame)
# exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # exit by pressing any key
# destroy windows
cv2.destroyAllWindows()
# hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
for i in range (1,5):
cv2.waitKey(1)
return
# read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
In [74]:
# Run your keypoint face painter
# laptop_camera_go()
Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.
To produce this effect an image of a pair of sunglasses shown in the Python cell below.
In [75]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)
# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');
This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).
Notice that this image actually has 4 channels, not just 3.
In [76]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.
This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.
Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.
In [77]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)
# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).
One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.
With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.
In [78]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[78]:
In [79]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image
# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# https://stackoverflow.com/questions/40895785/using-opencv-to-overlay-transparent-image-onto-another-image
def blend_transparent(face_img, overlay_t_img):
# Split out the transparency mask from the colour info
overlay_img = overlay_t_img[:,:,:3] # Grab the BRG planes
overlay_mask = overlay_t_img[:,:,3:] # And the alpha plane
# Again calculate the inverse mask
background_mask = 255 - overlay_mask
# Turn the masks into three channel, so we can use them as weights
overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)
# Create a masked out face image, and masked out overlay
# We convert the images to floating point in range 0.0 - 1.0
face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))
# And finally just add them together, and rescale it back to an 8bit integer image
return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0))
feature_mapping = {}
feature_mapping[1] = 'eye_right'
feature_mapping[2] = 'eye_left'
feature_mapping[3] = 'inner_eye_right'
feature_mapping[4] = 'outer_eye_right'
feature_mapping[5] = 'inner_eye_left'
feature_mapping[6] = 'outer_eye_left'
feature_mapping[7] = 'inner_eyebrow_right'
feature_mapping[8] = 'outer_eyebrow_right'
feature_mapping[9] = 'inner_eyebrow_left'
feature_mapping[10] = 'outer_eyebrow_left'
feature_mapping[11] = 'nose'
feature_mapping[12] = 'mouth_right'
feature_mapping[13] = 'mouth_left'
feature_mapping[14] = 'mouth_top'
feature_mapping[15] = 'mouth_bottom'
def add_overlay(image, overlays):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.25, 6)
# Make a copy of the orginal image to draw face detections on
image_draw = np.copy(image)
# Get the bounding box for each detected face
# for (x,y,w,h) in faces:
# # Add a red bounding box to the detections image
# cv2.rectangle(image_draw, (x,y), (x+w,y+h), (255,0,0), 3)
# Locate the facial keypoints in the cropped image.
face_patches = []
for (x,y,w,h) in faces:
face_patch = gray[y:y+h, x:x+w]
face_patch = cv2.resize(face_patch, (96, 96))
face_patch = np.expand_dims(face_patch, axis=2)
face_patches.append(face_patch / 255)
# Overlay the facial keypoints in the original (color, uncropped) image.
X_faces = np.asarray(face_patches)
y_faces = final_model.predict(X_faces)
face_features = []
for i in range(len(faces)):
x, y, w, h = faces[i]
x_features = y_faces[i][0::2] * 48 + 48
x_scaled = (x_features * w / 96) + x
y_features = y_faces[i][1::2] * 48 + 48
y_scaled = (y_features * h / 96) + y
count = 0
features = {}
for x, y in zip(x_scaled, y_scaled):
count += 1
if count in feature_mapping:
name = feature_mapping[count]
features[name] = (x, y)
face_features.append(features)
for overlay in overlays:
for features in face_features:
image_draw = overlay(image_draw, features)
return image_draw
def glasses(overlay):
def apply(image, features):
padding_ratio = 1.3 # glasses need to be bigger than facial points
l = features['outer_eyebrow_left']
r = features['outer_eyebrow_right']
overlay_height = overlay.shape[0]
overlay_width = overlay.shape[1]
# calculate width based on eyebrow distance
width = int(r[0] - l[0])
scaled_width = int(width * padding_ratio)
width_diff = scaled_width - width
# calculate height based on ratio
ratio = overlay_width / width
height = int(overlay_height / ratio)
scaled_height = int(height * padding_ratio)
height_diff = scaled_height - height
# scale overlay to match eyebrow distance * padding ratio
overlay_resize = cv2.resize(overlay, (scaled_width, scaled_height))
ly = int(l[1] - (height_diff / 2))
lx = int(l[0] - (width_diff / 2))
foreground = overlay_resize
background = image[ly:ly+scaled_height, lx:lx+scaled_width]
composite = blend_transparent(background, foreground)
image[ly:ly+scaled_height, lx:lx+scaled_width] = composite[:, :, :3]
return image
return apply
def cigarette(overlay):
def apply(image, features):
padding_ratio = 1 # glasses need to be bigger than facial points
l = features['outer_eyebrow_left']
r = features['outer_eyebrow_right']
ml = features['mouth_left']
overlay_height = overlay.shape[0]
overlay_width = overlay.shape[1]
# calculate width based on eyebrow distance
width = int(r[0] - l[0])
scaled_width = int(width * padding_ratio)
width_diff = scaled_width - width
# calculate height based on ratio
ratio = overlay_width / width
height = int(overlay_height / ratio)
scaled_height = int(height * padding_ratio)
height_diff = scaled_height - height
# scale overlay to match eyebrow distance * padding ratio
overlay_resize = cv2.resize(overlay, (scaled_width, scaled_height))
ly = int(ml[1] - (scaled_height * 0.5))
lx = int(ml[0] - (scaled_width * 0.85))
foreground = overlay_resize
background = image[ly:ly+scaled_height, lx:lx+scaled_width]
composite = blend_transparent(background, foreground)
image[ly:ly+scaled_height, lx:lx+scaled_width] = composite[:, :, :3]
return image
return apply
def hat(overlay):
def apply(image, features):
padding_ratio = 2.0 # glasses need to be bigger than facial points
l = features['outer_eyebrow_left']
r = features['outer_eyebrow_right']
er = features['eye_right']
n = features['nose']
overlay_height = overlay.shape[0]
overlay_width = overlay.shape[1]
# calculate width based on eyebrow distance
width = int(r[0] - l[0])
scaled_width = int(width * padding_ratio)
width_diff = scaled_width - width
# calculate height based on ratio
ratio = overlay_width / width
height = int(overlay_height / ratio)
scaled_height = int(height * padding_ratio)
height_diff = scaled_height - height
# scale overlay to match eyebrow distance * padding ratio
overlay_resize = cv2.resize(overlay, (scaled_width, scaled_height))
eye_nose_distance = n[1] - er[1]
ly = int(l[1] - (eye_nose_distance * 4))
lx = int(l[0] - (width_diff / 2))
foreground = overlay_resize
if ly < 0:
scaled_height = scaled_height + ly
foreground = foreground[abs(ly):, :, :]
ly = 0
background = image[ly:ly+scaled_height, lx:lx+scaled_width]
composite = blend_transparent(background, foreground)
image[ly:ly+scaled_height, lx:lx+scaled_width] = composite[:, :, :3]
return image
return apply
In [80]:
# The ex-Australian Prime Minister at his best!
In [81]:
def rgba2bgra(image):
sub = Image.fromarray(image)
sub = sub.convert("RGBA")
data = np.array(sub)
red, green, blue, alpha = data.T
data = np.array([blue, green, red, alpha])
data = data.transpose()
return data
image = cv2.imread('images/obamas4.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
oakleys = cv2.imread("images/oakleys.png", cv2.IMREAD_UNCHANGED)
oakleys = rgba2bgra(oakleys)
cig = cv2.imread("images/cigarette.png", cv2.IMREAD_UNCHANGED)
cig = rgba2bgra(cig)
swag = cv2.imread("images/hat.png", cv2.IMREAD_UNCHANGED)
swag = rgba2bgra(swag)
image = add_overlay(image, [hat(swag), glasses(oakleys), cigarette(cig)])
fig = plt.figure(figsize = (20,10))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(image)
print('Move over Tony theres a new Dealer in town 😭')
Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.
The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!
In [82]:
import cv2
import time
from keras.models import load_model
import numpy as np
def laptop_camera_go():
# Create instance of video capturer
cv2.namedWindow("face detection activated")
vc = cv2.VideoCapture(0)
# try to get the first frame
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Keep video stream open
while rval:
# Plot image from camera with detections marked
overlay_frame = add_overlay(frame, [glasses(oakleys)])
cv2.imshow("face detection activated", overlay_frame)
# Exit functionality - press any key to exit laptop video
key = cv2.waitKey(20)
if key > 0: # exit by pressing any key
# Destroy windows
cv2.destroyAllWindows()
for i in range (1,5):
cv2.waitKey(1)
return
# Read next frame
time.sleep(0.05) # control framerate for computation - default 20 frames per sec
rval, frame = vc.read()
In [83]:
# Run sunglasses painter
# laptop_camera_go()