Building a Cat Face Recognizer in Python

How to detect the difference between human and cat faces?

In this post, I will show you how to write a simple program that detects cat faces. In a previous most, I showed how to detect human faces using Python. When I was testing the code with many images, I realized that there were animals in some of them. But the face detection model that we created was not recognizing animal faces. Then I wondered if there is a way to detect animal faces in images, after a little research on the internet, yes it was possible. Even found many free datasets on Kaggle with hundreds of pictures. Kaggle is a great place to find free datasets, they are also organizing data science contests. It’s a great place to practice your data science skills and learn from others. Anyways, back to our project. I am so excited to combine both human and cat face detection models in one program so this way our machine will learn to differentiate between humans and cats. This will a fun project to work on. Let’s get started!!

Library

First things first, the paperwork. Installing and importing the libraries is necessary when you are working on machine learning projects. We will use two libraries for this project, and they are called OpenCV and Pillow. OpenCV is a highly optimized library with focus on real-time applications. Pillow is a great image processing library. Pillow will be installed as ‘pillow’, but imported as PIL. They are the same thing, don’t get confused.

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.

https://opencv.org

Installation process is very simple and easy. Write the following line of code in your terminal window:

pip install opencv-python pillow

After the installation is completed, we can import it to our program.

import cv2
from PIL import Image

OpenCV already contains many pre-trained classifiers for face, eyes, smile, etc. Those XML files are stored in a GitHub folder. We will use the cat face detection and human face detection models.

Here are the links:

Cat Face: https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalcatface_extended.xml

Human Face: https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

You can either download the XML files from Github if you have an account. If you don’t, feel free to copy the code from the link above and paste it into your text editor and save them. I saved them as “catface_detector.xml” and “humanface_detector.xml”.

After saving the files in your folder, let’s load them into our program.

# Load the cascades
catface_cascade = cv2.CascadeClassifier('catface_detector.xml')
humanface_cascade = cv2.CascadeClassifier('humanface_detector.xml')

Images

In this step, you will choose an image that you want to test your code on. Make sure you have at least couple of images to check the accuracy of your program. The images can have both human and cat or just one of them. If you having hard time to find cat images, I found a free dataset on Kaggle. Feel free to download and test your program.

Here are the images I will be using in this exercise:

After choosing your images, let’s rename them. Make sure the image files are in the same folder you are working on. After saving them, now we will do little retouches on the images.

Image Manipulation

In this step, we will do some little retouches on the images for a better processing. I’ve published a post on commonly used image manipulation techniques. Doing these retouching does help our machine to process and give much better results. For this exercise, first let’s resize the images so that they are at same size. Next, we’ll convert them to grayscale, our model works faster with grayscale images.

To use these image editing techniques we will use the Image module that we imported in the beginning of the post.

Resize

newsize = (600, 600)
imgr1 = Image.open("test1.jpg")
imgr1 = imgr.resize(newsize)
imgr1.save("resized1.jpg")
imgr2 = Image.open("test2.jpg")
imgr2 = imgr.resize(newsize)
imgr2.save("resized2.jpg")

Grayscale

imgr1 = imgr1.convert('L') 
imgr1.save('ready1.jpg')

imgr2 = imgr2.convert('L')
imgr2.save("ready2.jpg")

Import edited images

Lastly, let’s import the edited ready images to our program so that we can run the cat face and human face detection models. We are using opencv library to import the images.

# Read the input image
img1 = cv2.imread('ready1.jpg')
img2 = cv2.imread('ready2.jpg')

Face Detection

Cascades

It’s time to detect the faces. We will run two lines of code. First one to detect human faces in the image. Second line is to detect cat faces in the image. As mentioned earlier we are suing the opencv classifiers.

human_faces = humanface_cascade.detectMultiScale(img1, scaleFactor=1.3, minNeighbors=5, minSize=(75, 75))
cat_faces = catface_cascade.detectMultiScale(img2, scaleFactor=1.3, minNeighbors=5, minSize=(75, 75))

Draw rectangles

In this step, we are going to draw rectangles around the faces detected. These rectangles can be in different colors and their thickness level is also adjustable.

for (i, (x, y, w, h)) in enumerate(human_faces):
   cv2.rectangle(img1, (x, y), (x+w, y+h), (220, 90, 230), 3)
   cv2.putText(img1, "Human Face - #{}".format(i + 1), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (220, 90, 230), 2)

for (i, (x, y, w, h)) in enumerate(cat_faces):
   cv2.rectangle(img2, (x, y), (x+w, y+h), (0,255, 0), 3)
   cv2.putText(img2, "Cat Faces - #{}".format(i + 1), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2)
  • (220, 90, 230) and (0,255,0) are the colors of the rectangles we want to draw. You can play with them and see how the color changes.
  • (3) is the thickness of the lines. You can change the value and see how it looks.

Save your results

Lastly, we will save the images with detected faces. To see the final results of your work, best way is to save them and check. Make sure the variable names are passed correctly. Before you run this final code, I recommend going ahead and checking the whole code if everything looks okay.

cv2.imwrite("faces_detected1.png", img1)
cv2.imwrite("faces_detected2.png", img2)

Results

Here are the results of my work. First one is the human face detection and the second one is the cat face detection results.

Extra

Instead of testing each image one by one, let’s see what happens when we combine both images in one and run the code. We can see that our machine is now able to understand and differentiate between and cat and human faces.

Congrats!! You have created a program that detects cat and human faces in an image. Now, you have an idea on how to teach a machine to do couple things at the same time for you. Hoping that you enjoyed this tutorial and learn something new today. Computer Vision is a great field and things you can do is unlimited. Feel free to test your code on different images and see how it works. It might not work on all images because the prediction depends on the trained data. In a future post, I am planning to show you how to train the machine with your own dataset so that it can give you a better predictions.

Follow my blog and Towards Data Science to stay inspired.

Thank you,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s