process_model.py 2.88 KB
Newer Older
Arne Gerdes's avatar
Arne Gerdes committed
1 2 3 4
import cv2
import glob
import random
import numpy as np
tihmels's avatar
tihmels committed
5 6 7
import logging
import sys
import signal
Arne Gerdes's avatar
Arne Gerdes committed
8

tihmels's avatar
tihmels committed
9 10 11
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='logs/process_model.log')
Arne Gerdes's avatar
Arne Gerdes committed
12

tihmels's avatar
tihmels committed
13 14
emotions = ["anger", "disgust", "happy", "neutral", "surprise"]  # Emotion list
fishface = cv2.face.FisherFaceRecognizer_create()
Arne Gerdes's avatar
Arne Gerdes committed
15 16

def get_files(emotion):  # Define function to get file list, randomly shuffle it and split 80/20
tihmels's avatar
tihmels committed
17
    files = glob.glob('Basis_data/dataset/%s/*' % emotion)
Arne Gerdes's avatar
Arne Gerdes committed
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
    random.shuffle(files)
    training = files[:int(len(files) * 0.8)]  # get first 80% of file list
    prediction = files[-int(len(files) * 0.2):]  # get last 20% of file list
    return training, prediction


def make_sets():
    training_data = []
    training_labels = []
    prediction_data = []
    prediction_labels = []
    for emotion in emotions:
        training, prediction = get_files(emotion)
        # Append data to training and prediction list, and generate labels 0-7
        for item in training:
            image = cv2.imread(item)  # open image
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # convert to grayscale
            training_data.append(gray)  # append image array to training data list
            training_labels.append(emotions.index(emotion))

        for item in prediction:  # repeat above process for prediction set
            image = cv2.imread(item)
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            prediction_data.append(gray)
            prediction_labels.append(emotions.index(emotion))

tihmels's avatar
tihmels committed
44

Arne Gerdes's avatar
Arne Gerdes committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    return training_data, training_labels, prediction_data, prediction_labels


def run_recognizer():
    training_data, training_labels, prediction_data, prediction_labels = make_sets()

    print("training fisher face classifier")
    print("size of training set is:", len(training_labels), "images")
    fishface.train(training_data, np.asarray(training_labels))

    print("predicting classification set")
    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))


# Now run it
metascore = []
tihmels's avatar
tihmels committed
72 73

logging.debug("fisherface training initialized")
Arne Gerdes's avatar
Arne Gerdes committed
74 75 76 77 78
for i in range(0, 10):
    correct = run_recognizer()
    print("got", correct, "percent correct!")
    metascore.append(correct)

tihmels's avatar
tihmels committed
79 80 81 82 83 84 85
print("\nend score:", np.mean(metascore), "percent correct!")

logging.info("finished {} iterations:".format(len(metascore)))
for idx, meta in enumerate(metascore):
    logging.debug("{} : {}%".format(idx, meta))

logging.debug("fisherface finished with {}%\n".format(np.mean(metascore)))
Arne Gerdes's avatar
Arne Gerdes committed
86 87

fishface.write('Basis_data/models/detection_model.xml')