face_detect.py 1.87 KB
Newer Older
1 2
import cv2

3

4 5 6 7
faceDet_one = 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')
8 9


tihmels's avatar
tihmels committed
10
def extract_faces(image, resize):
11
    faces = find_faces(image)
tihmels's avatar
tihmels committed
12
    normalized_faces = [preprocess_face(face, resize) for face in faces]
13 14
    return normalized_faces

Arne Gerdes's avatar
Arne Gerdes committed
15

16
def find_faces(image):
tihmels's avatar
tihmels committed
17
    faces_coordinates = locate_faces(image)
18
    cutted_faces = [image[y:y + h, x:x + w] for (x, y, w, h) in faces_coordinates]
19
    return cutted_faces
20 21


tihmels's avatar
tihmels committed
22
def preprocess_face(face, resize):
23
    face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
tihmels's avatar
tihmels committed
24
    face = cv2.resize(face, (resize, resize))
25 26
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    face = clahe.apply(face)
27 28 29
    return face


30
def locate_faces(image, scaleFactor=1.1, minNeighbors=6, minSize=(350, 350)):
31
    face = faceDet_one.detectMultiScale(image, scaleFactor, minNeighbors, minSize=minSize,
32
                                        flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
33

34 35
    if len(face) == 1:
        return face
tihmels's avatar
tihmels committed
36

37
    face = faceDet_two.detectMultiScale(image, scaleFactor, minNeighbors, minSize=minSize,
Arne Gerdes's avatar
Arne Gerdes committed
38
                                        flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
39

40 41
    if len(face) == 1:
        return face
tihmels's avatar
tihmels committed
42

43
    face = faceDet_three.detectMultiScale(image, scaleFactor, minNeighbors, minSize=minSize,
Arne Gerdes's avatar
Arne Gerdes committed
44
                                          flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
45

46 47
    if len(face) == 1:
        return face
tihmels's avatar
tihmels committed
48

49
    face = faceDet_four.detectMultiScale(image, scaleFactor, minNeighbors, minSize=minSize,
Arne Gerdes's avatar
Arne Gerdes committed
50
                                         flags=cv2.CASCADE_SCALE_IMAGE)
tihmels's avatar
tihmels committed
51

52 53
    if len(face) == 1:
        return face
tihmels's avatar
tihmels committed
54 55

    return ''