Face Detection using Raspberry Pi

by Mar 28, 2020Raspberry Pi projects

Raspberry Pi is a powerful tool, and when coupled with OpenCV library can be used for many image processing projects. At the end of this article you will learn to build one such application ‘Face detection’. Face detection is exactly what is sounds like, the camera will capture an image and find the faces in the image and show the user. For this purpose, we will use a cascade classifier that OpenCV already has in order to detect the face. In this project we will also use the Raspberry Pi camera module to take the pictures for analysis.

What are cascade classifiers?

Cascade classifier is a training approach wherein there are hundreds of positive and negative examples that are agglomerated. The data thus made are stored as XML files and can be used in to detect the object that it was trained for. Thus, ensuring that the target is identified irrespective of variations and lighting. ‘Cascade’ implies that there are several simple stages that are applied till either the image passes all the stages, or fails at one stage. In this application we use haar cascade classifier.

Hardware requirements:

  1. Raspberry Pi with OS installed (available on the official website)
  2. Camera module
  3. Power cable
  4. Monitor
  5. HDMI connector
  6. USB or Bluetooth mouse
  7. USB or Bluetooth keyboard

Setup:

Software:

Before starting the project, download OpenCV and extract it from the official website. After which, if you open the file you should see a sub folder called sources. In sources, click on data sub-folder, in which you can open a file called haarcascades.

pic1.jpg

In this list, copy the ‘haarcascade_frontalface_default’ XML and paste it in the same folder that you are going to use to save your program.

Hardware:

  1. Connect the Raspberry Pi camera module and enable it (for any help on that, check out our article on that https://iot4beginners.com/how-to-capture-image-and-video-in-raspberry-pi/).
  2. Use the HDMI cable to connect your Raspberry Pi to a display
  3. Connect your mouse and keyboard as well (through USB or Bluetooth)
  4. Make sure to install NumPy and OpenCV library on your Raspberry Pi before you start

pic2

Code:

import numpy as np
import cv2
import io
import picamera

stream = io.BytesIO()

with picamera.PiCamera() as camera:
    camera.capture(stream,format='jpeg')

numparray = numpy.fromstring(stream.getvalue(),dtype=numpy.uint8)
image = cv2.imdecode(numparray,1)
faceDetectset= cv2.CascadeClassifier('haarcascade_frontalface_default.xml');

#convert to gray scale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#now we can look for faces
faces = faceDetectset.detectMultiScale(gray,1.3,5);
for (x,y,w,h) in faces:
    #draw box on original
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,0),2)

#show the output in window
cv2.imshow("Detected",img)
if cv2.waitKey()==ord('q'):
    break;

stream.truncate(0)
cv2.destroyAllWindows()

Code Explanation:

First we start the code by importing the libraries necessary for the program.

import numpy as np
import cv2
import io
import picamera
import time

We then create a stream to avoid using memory space on your Pi for every image you capture. After this, we use the Raspberry Pi camera to capture an image after showing preview.

stream = io.BytesIO()

#capture image
with picamera.PiCamera() as camera:
    camera.start_preview()
    time.sleep(5)
    camera.capture(stream,format='jpeg')

To use the image captured with OpenCV and make the processing speed faster, we convert the image to a NumPy array. We then assign the variable name ‘image’ to read data from the ‘numparray’ and decode to image format.

numparray = numpy.fromstring(stream.getvalue(),dtype=numpy.uint8)

image = cv2.imdecode(numparray,1)

Remember that XML file we found and pasted in the same folder as your program? We are going to finally use that by assigning a variable name to it. It is also worthy to note that classifiers usually only work for gray scale images, but the image your pi cam takes is color (i.e.,RGB). As a result, we have to convert the image to gray scale.

faceDetectset= cv2.CascadeClassifier('haarcascade_frontalface_default.xml');

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

Now we can look for faces and using the function .detectMultiScale() we can find the coordinates of the object we are looking for (also as I’ve specified in the program feel free to play around with the scaling factors). Which in this case, is the face! After finding the face in the image, we then draw a rectangle around the location of the face to indicate it. For this, the parameters we specify are the variable name of the image, the start and end coordinates, the color specification for the rectangle (in this case, black) and then the thickness.

After the box is drawn, we then display the original colored image with the box drawn on it in a separate window called ‘Detected’ until the key ‘e’ is clicked to exit the window.

faces = faceDetectset.detectMultiScale(gray,1.3,5);#scaling factors can be varied
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,0),2)

cv2.imshow("Detected",img)
if cv2.waitKey()==ord('e'):
    break;

stream.truncate(0)
cv2.destroyAllWindows()

Output:

facedetection.jpg

There’s me being detected!

facedetection1.jpg

Here’s me holding up a stock image of a group of random people that I found online!

And with that, your project is over. Feel free to move around and take pictures under different lighting conditions, face orientations and expressions and you should be able to see the program detecting and drawing a box around your face! This is a fun project that is a precursor towards building a face recognition system which requires you to create your own classifier or tree with images of specific people that you want to detect.

Click to download the code

Creating a multiplication Skill in Alexa using python

Written By Jyotsna Rajaraman

Hi! I'm Jyotsna, an electronics and communication undergrad who likes reading, writing, talking and learning. So when it comes to teaching, all my favorite things come together! I hope my articles have helped and taught you something. 🙂

RELATED POSTS

Magic Wand using Raspberry Pi and OpenCV

Magic Wand using Raspberry Pi and OpenCV

What if I could do things with a swing of a wand? Practically impossible but with technology maybe not. In this tutorial, we will use a raspberry pi and OpenCV to try and recreate something similar to a wand. It will perform specific functions when it recognizes...

IBM Watson IoT Platform with Raspberry Pi

IBM Watson IoT Platform with Raspberry Pi

IBM Watson is one of the leading cloud computing platforms there is. It has almost all the features one could expect from a modern-day cloud platform, from machine learning support to IoT, even till edge computing. In this tutorial, we will use raspberry pi and an...

Home Automation With Telegram and Raspberry Pi

Home Automation With Telegram and Raspberry Pi

In this Article we will see how we can use Telegram for Home Automation. Telegram is an extremely popular multi-platform messaging service. Just like any other messaging platform, it is used to send messages and exchange photos, videos, stickers, audio, and files of...

Home Automation System with Raspberry Pi and Flask

Home Automation systems are becoming increasingly popular for the level of convenience they offer. Imagine sitting on your couch and turning on/off lights or fans in the room without having to get up. You could also control blinds or even door locks. This project is a...

Smart Alarm Clock with Raspberry Pi

Smart Alarm Clock with Raspberry Pi

Smart Alarms are very common today yet the good ones expensive. What if you wanted to make a smart alarm clock on your own using as little hardware and cost as possible? You may ask isn't the RPI costly, yes it is but, the only purpose of using an RPI is easy to net...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....