What is OpenCV used for?

I will explain you what is the purpose of opencv, and some cool applications. Plus I will show you how to perform face detection with opencv. FIVE LINES OF CODE!!

Card image cap

This article shows what is the purpose of openCV, how to download it and some cool stuff that you can do with openCV. Plus showing you how to perform face detection on an image using openCV. This library makes this task extremely simple. Let’s get started

OpenCV Python Tutorial | Face Recognition in 5 Simple Steps https://img.youtube.com/vi/TkalWRARPhc/default.jpg OpenCV Python Tutorial | Face Recognition in 5 Simple Steps 2020-09-15 https://youtu.be/TkalWRARPhc

What is the purpose of OpenCV?

What is the purpose of OpenCV? OpenCV is a library for solving vision problems. Used for video and image analysis. For instance, you can analyse an image and find the number of people present in the image. Some cool things that you can do with this library are:

  • Face Detection
  • License plate reading
  • Character recognition
  • Gesture recognition
  • And a lot more!! 🙂

Where can I download opencv?

Now you know what opencv is. Let’s download it! First you need to download python in your machine. Once you installed python, the package manager called pip will be available for you to use. You will use package manager to download modules and keep track of the installed modules.

To make sure, both python and pip are correctly installed, run these commands from your terminal:

python3 --version
pip3 --version

Now you are ready to download any library you like via pip. Let’s set up openCV. First you need to install the numpy library. Numpy is a library for efficient array and matrix computing. OpenCV uses numpy to convert images to pixel matrices that can be easily manipulated. To install numpy and opencv on your laptop, run the following commands from your terminal:

pip install numpy

pip install opencv-python

How to do face detection?

You just installed all necessary libraries. Now you are ready to do some cool stuff like face detection. Using opencv you can achieve face detection with about 5 lines of code! To be more concrete, here are the steps I will follow to perform face detection. First, loading an image saved in my machine. Next, drawing a rectangle around any face found in the image. It sounds like a simple task, however if you try to program this, without using libraries, the amount of code you need to write will be insane.

Step 1) Select an image and load it

Pick any image you like containing a face, and place it in a directory in your machine. Any directory as long as it is the same directory where you are gonna write your python script. As a quick note, I am using the same folder just for simplicity. My image is called sample_image.png. Next I will create a python file called face_detection.py and add the following code:

import cv2
image = cv2.imread('sample_image.png')

Please note you will need to import the opencv library, so all the image analysing functionality is available to use in your script. The code above will load the image and store it in a variable.

Step 2) Convert image to grayscale

Now we need to convert the image to grayscale. Why is this necessary? Converting to grey will remove all colour information which is useless for object detection. This will make the analysis easier for opencv. Adding the following line to our script, will create a greysacle image:

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Step 3) Create the face classifier

Next step is creating a face classifier. Simpler than you think. The classifier is an algorithm that has been already trained to detect specific objects, in this case faces. The algorithm is trained by processing a lot of images, with and without faces. After processing a huge number of images, the algorithm gathers the rules that help determine how to find a face within an image. You can download the classifier algorithm from this url, and save it in the same folder as your script:

Open and Download the classifier from here

Once you saved the file and called it haarcascade_frontalface_alt2.xml, you can add the following code in your script to create the classifier:

face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')

Step 4) Find the faces

Now we are ready to run the face detection analysis on our grey image and find the faces.

faces_rectangles = face_classifier.detectMultiScale(gray_image)

This will return a list of rectangles that surround the faces in our image.

Step 5) Final step! Draw the rectangles surrounding the faces

We found the faces. Now all left to do is drawing the rectangles on top of our original image . This way we can visualise the analysis and make sure the algorithm detect the faces correctly.

for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) # Draw the rectangle

cv2.imshow('Loaded image',image) # Display the original image

cv2.waitKey(0) # Program waits for user to press a key
cv2.destroyAllWindows() # Close all windows

And here are the results:

face detection

These is the full script:

#Loading the image
import cv2
image = cv2.imread('sample_image.png')

#Convert to gray scale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Face classifier
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')

# Analysis
faces_rectangles = face_classifier.detectMultiScale(gray_image)

# Drawing the rectangles
for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) # Draw the rectangle

cv2.imshow('Loaded image',image) # Display the original image

cv2.waitKey(0) # Program waits for user to press a key
cv2.destroyAllWindows() # Close all windows

Possible errors

OpenCV !_src.empty() in function ‘cv::cvtColor’ error

You might encounter the following error: OpenCV !_src.empty() in function ‘cv::cvtColor’ error. The cvtColor function will throw this error when the image received is empty. Therefore you should double check that the image was correctly loaded. Check the file name spelling, and also make sure the image and your script are saved in the same folder.

Hope you enjoy the article. As you can see, opencv makes face detection extremely simple. Happy coding!

What’s next?

Fun projects for beginners using python

Automate your youtube downloads using python

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java