How to use OpenCv library with Python to recognize faces in a image

Original article was published on Artificial Intelligence on Medium

How to use OpenCv library with Python to recognize faces in a image

Photo by Maxwell Nelson on Unsplash

This is my first story at Medium. I always wanted to share the good things that I have learned and now, this is my first and small step.

The purpose in this story is demonstrate how we can use the OpenCV library with Python to recognize faces in an image.

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. It’s very easy to use and powerful.

Requirements

It’s necessary to have a Python environment ready in your notebook or PC and some libraries installed. Follow below the libraries:

The code

I’m using the following image to recognize the faces from Ronaldinho Gaúcho and Ronaldo.

The Python source code:

#Import the opencv library
import cv2

# Load the Haar cascade
cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

# Read the image
image = cv2.imread(‘ronaldinho_ronaldo.jpg’)

# Detect faces in the image
faces = cascade.detectMultiScale(image, 1.1, 4)

# Draw a white rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 3)

# Display the images detected
cv2.imshow(‘Faces Detected’, image)
cv2.waitKey()

You can save the source code above as detect_faces_opencv.py.

And run it using the command python detect_faces_opencv.py.

The result

As you can see in the image below, two faces was recognized in the image.

You can access the source code in the following repository: https://github.com/pivotoadami/detect_faces_opencv

Thanks for reading!!!

# Display the images detected
cv2.imshow(‘Faces Detected’, image)
cv2.waitKey()