process_model.py 3.22 KB
Newer Older
Arne Gerdes's avatar
Arne Gerdes committed
1
2
3
4
"""
Diese Klasse macht das Training des Models möglich
"""

Arne Gerdes's avatar
Arne Gerdes committed
5
6
7
8
import cv2
import glob
import random
import numpy as np
tihmels's avatar
tihmels committed
9
import sys
tihmels's avatar
tihmels committed
10
import logging
Arne Gerdes's avatar
Arne Gerdes committed
11

Arne Gerdes's avatar
Arne Gerdes committed
12
13
14
"""
Erstellt und gibt das Log-File aus 
"""
tihmels's avatar
tihmels committed
15
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s',
tihmels's avatar
tihmels committed
16
17
                    datefmt='%m-%d %H:%M',
                    filename='logs/process_model.log')
18

Arne Gerdes's avatar
Arne Gerdes committed
19
20
21
22
"""
Liest Input Parameter 
"""
args = sys.argv
tihmels's avatar
tihmels committed
23
logging.debug('Fisherface training initialized')
Arne Gerdes's avatar
Arne Gerdes committed
24

tihmels's avatar
tihmels committed
25
file = open("{}.csv".format('_'.join(args[1:]).lower()), "w")
26

Arne Gerdes's avatar
Arne Gerdes committed
27

28
29
30
31
32
33
def _get_faces_from_emotion(emotion):
    """
    Holt alle Dateien zu einer Emotion aus dem Dataset, mischt sie und teilt sie in ein Trainings- und Prognoseset.
    :param emotion: Die Emotion
    :return: training, prediction
    """
34
    files = glob.glob('img_data/dataset/{}/*'.format(emotion))
Arne Gerdes's avatar
Arne Gerdes committed
35
    random.shuffle(files)
Arne Gerdes's avatar
Arne Gerdes committed
36
37
38
39
40
41
42

    """
    Mischt das Dataset in Trainings- und Vergleichsbilder im Verhältnis 80 zu 20 
    """
    training = files[:int(len(files) * 0.8)]
    prediction = files[-int(len(files) * 0.2):]

Arne Gerdes's avatar
Arne Gerdes committed
43
44
    return training, prediction

Arne Gerdes's avatar
Arne Gerdes committed
45

46
47
48
49
50
51
52
53
def image_preprocessing(image):
    """
    Preprocessing der Dateien
    :param item: Bild
    :return:
    """
    img = cv2.imread(image)  # open image
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # convert to grayscale
54
55
56
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    face = clahe.apply(gray)
    return face
Arne Gerdes's avatar
Arne Gerdes committed
57

Arne Gerdes's avatar
Arne Gerdes committed
58

Arne Gerdes's avatar
Arne Gerdes committed
59
60
61
62
63
64
def make_sets():
    training_data = []
    training_labels = []
    prediction_data = []
    prediction_labels = []
    for emotion in emotions:
65
        training, prediction = _get_faces_from_emotion(emotion)
Arne Gerdes's avatar
Arne Gerdes committed
66
67
        # Append data to training and prediction list, and generate labels 0-7
        for item in training:
tihmels's avatar
tihmels committed
68
69
            img = image_preprocessing(item)
            training_data.append(img)  # append image array to training data list
Arne Gerdes's avatar
Arne Gerdes committed
70
71
72
            training_labels.append(emotions.index(emotion))

        for item in prediction:  # repeat above process for prediction set
tihmels's avatar
tihmels committed
73
74
            img = image_preprocessing(item)
            prediction_data.append(img)
Arne Gerdes's avatar
Arne Gerdes committed
75
76
77
78
            prediction_labels.append(emotions.index(emotion))

    return training_data, training_labels, prediction_data, prediction_labels

Arne Gerdes's avatar
Arne Gerdes committed
79

Arne Gerdes's avatar
Arne Gerdes committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def run_recognizer():
    training_data, training_labels, prediction_data, prediction_labels = make_sets()

    fishface.train(training_data, np.asarray(training_labels))

    cnt = 0
    correct = 0
    incorrect = 0
    for image in prediction_data:
        pred, conf = fishface.predict(image)
        if pred == prediction_labels[cnt]:
            correct += 1
            cnt += 1
        else:
            incorrect += 1
            cnt += 1
    return ((100 * correct) / (correct + incorrect))

Arne Gerdes's avatar
Arne Gerdes committed
98

tihmels's avatar
tihmels committed
99
100
101
if len(args) > 1:
    tags = ', '.join(args[1:])
    logging.debug(tags.upper())
tihmels's avatar
tihmels committed
102

Arne Gerdes's avatar
Arne Gerdes committed
103
104
105
106
"""
Emotions Liste 
"""
emotions = ["happy", "neutral", "surprise"]
tihmels's avatar
tihmels committed
107
fishface = cv2.face.FisherFaceRecognizer_create()
Arne Gerdes's avatar
Arne Gerdes committed
108

Arne Gerdes's avatar
Arne Gerdes committed
109

Arne Gerdes's avatar
Arne Gerdes committed
110
metascore = []
tihmels's avatar
tihmels committed
111

112
for i in range(0, 40):
Arne Gerdes's avatar
Arne Gerdes committed
113
    correct = run_recognizer()
114
    file.write("{}\n".format(int(correct)))
tihmels's avatar
tihmels committed
115
    logging.debug("{} : {}%".format(i, int(correct)))
Arne Gerdes's avatar
Arne Gerdes committed
116
    metascore.append(correct)
117

118
file.close()
Arne Gerdes's avatar
Arne Gerdes committed
119

tihmels's avatar
tihmels committed
120
logging.debug("{} iterations - {}% average\n".format(len(metascore), np.mean(metascore)))
121
fishface.write('img_data/models/detection_model.xml')