Reconhecimento de Faces – Passo a Passo

Reconhecimento de Faces – Passo a Passo

Atualmente as cameras modernas dos celulares podem identificar as faces das pessoas e ajudar a rapidamente efetuar o enquadramento da imagem. Abaixo os passo para identificar as faces utilizando OpenCV.

Encontrar todas as faces

No inicio dos anos 2000 Paul Viola e Michal Jones demonstraram uma forma de detectar faces que era rápido e eficiente para ser executado em cameras baratas. Esse método é relativamente simples de implementar, apesar de falhar em algumas situações.

from re import S
import numpy as np
import cv2
import sys
import os

file_name = sys.argv[1]

cv2_base_dir = os.path.dirname(os.path.abspath(cv2.__file__))

haar_model = os.path.join(cv2_base_dir, 'data/haarcascade_frontalface_default.xml')
eye_model = os.path.join(cv2_base_dir, 'data/haarcascade_eye.xml')


face_cascade = cv2.CascadeClassifier(haar_model)
eye_cascade = cv2.CascadeClassifier(eye_model)

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

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:
    cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey, ew, eh) in eyes:
        cv2.rectangle(roi_color, (ex,ey), (ex+ew, ey+eh), (0,255,0),2)

cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

if (len(sys.argv) == 3):
    save_file = sys.argv[2]
    cv2.imwrite(save_file, img)

Face detection is a great feature for cameras. When the camera can automatically pick out faces, it can make sure that all the faces are in focus before it takes the picture. But we’ll use it for a different purpose — finding the areas of the image we want to pass on to the next step in our pipeline.

Face detection went mainstream in the early 2000’s when Paul Viola and Michael Jones invented a way to detect faces that was fast enough to run on cheap cameras. However, much more reliable solutions exist now. We’re going to use a method invented in 2005 called Histogram of Oriented Gradients — or just HOG for short.

To find faces in an image, we’ll start by making our image black and white because we don’t need color data to find faces:

Step 1: Finding all the Faces

The first step in our pipeline is face detection. Obviously we need to locate the faces in a photograph before we can try to tell them apart!

If you’ve used any camera in the last 10 years, you’ve probably seen face detection

Step 1: Finding all the Faces

The first step in our pipeline is face detection. Obviously we need to locate the faces in a photograph before we can try to tell them apart!

If you’ve used any camera in the last 10 years, you’ve probably seen face detection in action:

Salir de la versión móvil