The goal is to build a pipeline that can be used within a web or mobile app to process real-world, user-supplied images. Given an image of a dog, the algorithm will identify an estimate of the canine’s breed. If supplied an image of a human, the code will identify the resembling dog breed.
All the code is written in Python 3 and Keras with TensorFlow as backend. You can find all the code on my github
Clone the repository and navigate to the downloaded folder.
git clone https://github.com/munoztd0/dog_classifier
cd dog_classifier
Download the dog dataset. Unzip the folder and place it in the repo, at location img/dogImages
.
Download the human dataset. Unzip the folder and place it in the repo, at location img/lfw
. If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
Download the VGG-16 bottleneck features for the dog dataset. Place it in the repo, at location path/to/dog-project/bottleneck_features
.
(Optional) If you plan to install TensorFlow with GPU support on your local machine, follow the guide to install the necessary NVIDIA software on your system. If you are using an EC2 GPU instance, you can skip this step.
Install the necessary Python packages
pip install -r requirements.txt
# necessary imports
import numpy as np
import random
import cv2
import matplotlib.pyplot as plt
import sys
import os
import dlib
from skimage import io
from tqdm import tqdm
from glob import glob
from sklearn.datasets import load_files
from extract_bottleneck_features import *
from keras.callbacks import ModelCheckpoint
from keras.preprocessing import image
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions
from keras.utils import np_utils
from PIL import ImageFile
from IPython.core.display import Image, display
# define function to load train, test, and validation datasets
def load_dataset(path):
data = load_files(path)
dog_files = np.array(data['filenames'])
dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
return dog_files, dog_targets
# load train, test, and validation datasets
train_files, train_targets = load_dataset('img/dogImages/train')
valid_files, valid_targets = load_dataset('img/dogImages/valid')
test_files, test_targets = load_dataset('img/dogImages/test')
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("img/dogImages/train/*/"))]
# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories. There are 8351 total dog images. There are 6680 training dog images. There are 835 validation dog images. There are 836 test dog images.
In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/hf.xml')
random.seed(666)
# load filenames in shuffled human dataset
human_files = np.array(glob("img/lfw/*/*"))
#random.shuffle(human_files)
def boxe_face(image):
# load color (BGR) image
img = cv2.imread(image)
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print (faces)
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
boxe_face(human_files[3])
# print statistics about the dataset
print("Good ol' Elvis")
print('There are %d total human images.' % len(human_files))
[[ 71 70 109 109]] Number of faces detected: 1
There are 13233 total human images.
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 haarcascades directory.
In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale
function executes the classifier stored in face_cascade
and takes the grayscale image as a parameter.
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.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector_opencv(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
What percentage of the first 100 images in human_files
have a detected human face?
What percentage of the first 100 images in dog_files
have a detected human face?
Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. We will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short
and dog_files_short
.
So we see that the OpenCV's implementation of Haar feature-based cascade classifiers detects 100.0% of faces in the first 100 images in human_files
and 11.0% of faces in the first 100 images in dog_files
. When investigating each image where a face has been detected, we can see that for one image there is actually a human in the picture so the classifier is not making a mistake here. For 4 images, the classifier misclassifies the face of a human with a dog. For the rest of them, the classifier seems to detect faces in fur, wrinkle of fabrics...
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
## Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
def performance_face_detector_opencv(human_files_short, dog_files_short):
face_human = [int(face_detector_opencv(human_img)) for human_img in human_files_short]
ratio_human = sum(face_human)/len(face_human)*100
print ('{}% of faces detected in the first 100 images in human_files by OpenCV'.format(ratio_human))
face_dog = 0
for dog_img in dog_files_short:
if face_detector_opencv(dog_img):
img = cv2.imread(dog_img)
boxe_face(dog_img)
face_dog += 1
ratio_dog = face_dog/len(dog_files_short)*100
print ('{}% of faces detected in the first 100 images in dog_files by OpenCV'.format(ratio_dog))
performance_face_detector_opencv(human_files_short, dog_files_short)
98.0% of faces detected in the first 100 images in human_files by OpenCV [[160 159 108 108]] Number of faces detected: 1
[[188 139 102 102]] Number of faces detected: 1
[[202 96 47 47]] Number of faces detected: 1
[[235 174 83 83]] Number of faces detected: 1