face_detect.py 1.83 KB
Newer Older
Arne Gerdes's avatar
Arne Gerdes committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
This module contains face detections functions.
"""
import cv2

faceDet = cv2.CascadeClassifier("Haarcascade\\haarcascade_frontalface_default.xml")
faceDet_two = cv2.CascadeClassifier("Haarcascade\\haarcascade_frontalface_alt2.xml")
faceDet_three = cv2.CascadeClassifier("Haarcascade\\haarcascade_frontalface_alt.xml")
faceDet_four = cv2.CascadeClassifier("Haarcascade\\haarcascade_frontalface_alt_tree.xml")


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):
    face_one = faceDet.detectMultiScale(image, scaleFactor=1.1, minNeighbors=15, minSize=(70, 70),
                                        flags=cv2.CASCADE_SCALE_IMAGE)
    face_two = faceDet_two.detectMultiScale(image, scaleFactor=1.1, minNeighbors=15, minSize=(70, 70),
                                            flags=cv2.CASCADE_SCALE_IMAGE)
    face_three = faceDet_three.detectMultiScale(image, scaleFactor=1.1, minNeighbors=15, minSize=(70, 70),
                                                flags=cv2.CASCADE_SCALE_IMAGE)
    face_four = faceDet_four.detectMultiScale(image, scaleFactor=1.1, minNeighbors=15, minSize=(70, 70),
                                              flags=cv2.CASCADE_SCALE_IMAGE)
    if len(face_one) == 1:
        facefeatures = face_one
    elif len(face_two) == 1:
        facefeatures = face_two
    elif len(face_three) == 1:
        facefeatures = face_three
    elif len(face_four) == 1:
        facefeatures = face_four
    else:
        facefeatures = ""

    return facefeatures