face_detect.py 1.87 KB
Newer Older
1 2
import cv2

3 4 5 6
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')
7 8


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

Arne Gerdes's avatar
Arne Gerdes committed
14

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


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


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

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

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

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

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

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

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

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

    return ''