Learn how you can use the open-source library OpenCV with a Raspberry Pi to create face and object detection!

OpenCV (open source computer vision library) is a very useful library — it provides many useful features such as text recognition, face recognition, object detection, the creation of depth maps, and machine learning. 

This article will show you how to install OpenCV and other libraries on Raspberry Pi that will come in handy when doing object detection and other projects. From there, we will learn how to perform image and video operations by executing an object recognition and machine learning project. Specifically, we will write a simple code to detect faces in an image.

What is OpenCV?

OpenCV is an open source computer vision and machine learning software library. OpenCV is released under a BSD license making it free for both academic and commercial use. It has C++, Python, and Java interfaces and supports Windows, Linux, Mac OS, iOS, and Android. 

OpenCV was designed for computational efficiency and a strong focus on real-time applications.

How to Install OpenCV on a Raspberry Pi

To install OpenCV, we need to have Python installed. Since Raspberry Pis are preloaded with Python, we can install OpenCV directly.

Type the commands below to make sure your Raspberry Pi is up to date and to update the installed packages on your Raspberry Pi to the latest versions.

        sudo apt-get update
sudo apt-get upgrade
    

Type the following commands in the terminal to install the required packages for OpenCV on your Raspberry Pi.

        sudo apt install libatlas3-base libsz2 libharfbuzz0b libtiff5 libjasper1 libilmbase12 libopenexr22 libilmbase12 libgstreamer1.0-0 libavcodec57 libavformat57 libavutil55 libswscale4 libqtgui4 libqt4-test libqtcore4
    

Type the following command to install OpenCV 3 for Python 3 on your Raspberry Pi, pip3 tells us that OpenCV will get installed for Python 3.

        sudo pip3 install opencv-contrib-python libwebp6
    

After those steps, OpenCV should be installed. Let's test our work!

Testing OpenCV 

To check whether OpenCV is correctly installed or not, try importing OpenCV by typing:

        Python3
    

then:

        import cv2
    

If no errors are shown, your installation was successful!

To know which version of OpenCV you have, type the following command:

        cv2.__version__
    
which version of OpenCV is installed

This message tells you which version on OpenCV you installed on your Raspberry Pi.

Recommended Optional Libraries

There are also other libraries to install that will come in handy when you do object detection and other projects, so I highly recommend you also install these.

NumPy

The first library is NumPy — a library that makes array operations in Python easy to perform. Install NumPy by typing the following command:

        pip3 install python-numpy
    

Matplotlib

The second library is Matplotlib. Matplotlib is a Python plotting library that produces publication quality figures in a variety of hard copy formats and interactive environments across platforms. Install Matplotlib by typing the following command:

        pip3 install python-matplotlib
    

Now we are done installing OpenCV and helpful accompanying libraries on Raspberry Pi. Let's move forward to object detection and machine learning using OpenCV on Raspberry Pi.

Face Detection in Pictures Using OpenCV

Let's start by writing the code that will detect faces in the images it receives. For face detection, you need a cascade file. Save this file in the working directory as "haarcascade_frontalface_default.xml".

Enter the path of the image you want to detect faces in into the code below and run the code. 

        # Import OpenCV library
import cv2

# Load a cascade file for detecting faces
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");

# Load image
image = cv2.imread('obamafamily.jpg')

# Convert into grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Look for faces in the image using the loaded cascade file
faces = faceCascade.detectMultiScale(gray, 1.2, 5)
for (x,y,w,h) in faces:
	# Create rectangle around faces
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),2)

# Create the resizeable window
cv2.namedWindow('Obama', cv2.WINDOW_NORMAL)

# Display the image
cv2.imshow('Obama', image)

# Wait until we get a key
k=cv2.waitKey(0)

# If pressed key is 's'
if k == ord('s'):
    # Save the image
    cv2.imwrite('convertedimage.jpg', image)
    # Destroy all windows
    cv2.destroyAllWindows()
# If pressed key is ESC
elif k == 27:
    # Destroy all windows
    cv2.destroyAllWindows()
    

After running the code, it will draw rectangles around the faces as shown in the picture below.

face detection with OpenCV

After running the code, rectangles will appear around all detected faces.

Reginald Watson
I love challenging myself by creating new projects using different microcontrollers to see what I can come up with.