face_detect.py 1.78 KB
Newer Older
1 2 3 4 5
"""
This module contains face detections functions.
"""
import cv2

tihmels's avatar
tihmels committed
6 7 8 9
faceDet = cv2.CascadeClassifier('resources/Haarcascade/haarcascade_frontalface_default.xml')
faceDet_two = cv2.CascadeClassifier('resources/Haarcascade/haarcascade_frontalface_alt2.xml')
faceDet_three = cv2.CascadeClassifier('resources/Haarcascade/haarcascade_frontalface_alt.xml')
faceDet_four = cv2.CascadeClassifier('resources/Haarcascade/haarcascade_frontalface_alt_tree.xml')
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26


def find_faces(image):
    faces_coordinates = _locate_faces(image)
    cutted_faces = [image[y:y + h, x:x + w] for (x, y, w, h) in faces_coordinates]
    normalized_faces = [_normalize_face(face) for face in cutted_faces]
    return zip(normalized_faces, faces_coordinates)


def _normalize_face(face):
    face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
    face = cv2.resize(face, (250, 250))

    return face


def _locate_faces(image):
tihmels's avatar
tihmels committed
27
    face_one = faceDet.detectMultiScale(image, scaleFactor=2, minNeighbors=4, minSize=(50, 50),
28
                                        flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
29 30 31 32 33

    if len(face_one) == 1:
        return face_one

    face_two = faceDet_two.detectMultiScale(image, scaleFactor=2, minNeighbors=4, minSize=(50, 50),
34
                                            flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
35 36 37 38 39

    if len(face_two) == 1:
        return face_two

    face_three = faceDet_three.detectMultiScale(image, scaleFactor=2, minNeighbors=4, minSize=(50, 50),
40
                                                flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
41 42 43 44 45

    if len(face_three) == 1:
        return face_three

    face_four = faceDet_four.detectMultiScale(image, scaleFactor=2, minNeighbors=4, minSize=(50, 50),
46
                                              flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
47 48 49 50 51

    if len(face_four) == 1:
        return face_four

    return ''