sorted_set_facedetector.py 4.57 KB
Newer Older
Arne Gerdes's avatar
Arne Gerdes committed
1
2
import cv2
import glob
3
import logging
4
5
6
7
8
9
import argparse
import shutil
import sys

import os

10
from email_service import sendMail
tihmels's avatar
tihmels committed
11
from face_detect import locate_faces
Arne Gerdes's avatar
Arne Gerdes committed
12

13
14
15
16
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='logs/sorted_set_facedetector.log',
                    filemode='w')
Arne Gerdes's avatar
Arne Gerdes committed
17
"""
18
Argument Parser erlaubt Parameter für die Verarbeitung anzugeben.
Arne Gerdes's avatar
Arne Gerdes committed
19
"""
20
21

parser = argparse.ArgumentParser(description='Sorted Set Face Creator Application')
22
23
24
25
26
27
28
29
30
31
parser.add_argument('--source', action='store', dest='img_source', default='resources/img_data/sorted_set/',
                    help='path to image source')
parser.add_argument('--dataset', action='store', dest='dataset', default='resources/img_data/dataset/', help='path to dataset')
parser.add_argument('--r', action='store', dest='resize', default=150, type=int, help='resize factor')
parser.add_argument('-e', action='append', dest='emotions', default=['happy', 'neutral', 'surprised'], help='declare emotions that should be processed')
parser.add_argument('-c', action='store', dest='scaleFactor', default=1.1, type=float,
                    help='scale factor - haar')
parser.add_argument('-n', action='store', dest='minNeighbors', default=6, type=int, help='min neighbors - haar')
parser.add_argument('-s', action='store', dest='minSize', default=40, type=int, help='min size - haar')
parser.add_argument('-x', action='store_true', help='activate email notifications')
32
arguments = parser.parse_args()
33
logging.DEBUG(arguments)
34
35
36
37
38

datasetPath = arguments.dataset

if len(glob.glob(datasetPath + '*')) > 0:
    deleteDataset = input(
39
        'Im Dataset befinden sich Dateien. Durch diesen Vorgang werden die existierenden Daten gelöscht. Fortfahren (y/n): ')
40
41
42
43
44

    if deleteDataset == 'y':
        for file in glob.glob(datasetPath + '*'):
            shutil.rmtree(file)
    else:
45
        logging.info('Execution canceled from user')
46
        sys.exit()
Arne Gerdes's avatar
Arne Gerdes committed
47

tihmels's avatar
tihmels committed
48
49
50
totalFiles: int = 0
totalFaces: int = 0
undetected: list = []
51
img_source = arguments.img_source
tihmels's avatar
tihmels committed
52

Arne Gerdes's avatar
Arne Gerdes committed
53

Arne Gerdes's avatar
Arne Gerdes committed
54
def detect_faces(emotion):
Arne Gerdes's avatar
Arne Gerdes committed
55
56
57
    """
    Holt alle Dateien zu einer Emotion aus dem sorted_set
    """
58
    files = glob.glob(img_source + '{}/*'.format(emotion))
59
60
61
62

    global undetected
    global totalFaces
    global totalFiles
Arne Gerdes's avatar
Arne Gerdes committed
63

64
    logging.info("Found {} {} files".format(len(files), emotion))
65
66

    fileNumber = 0
Arne Gerdes's avatar
Arne Gerdes committed
67
68
    for f in files:
        frame = cv2.imread(f)  # Open image
69
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # Convert image to grayscale
Arne Gerdes's avatar
Arne Gerdes committed
70

71
        facefeatures = locate_faces(gray, arguments.scaleFactor, arguments.minNeighbors, (arguments.minSize, arguments.minSize))
tihmels's avatar
tihmels committed
72
73

        if facefeatures is '':
74
            logging.info('No face detected ' + f)
75
            undetected.append(f)
76
77
78

            if len(undetected) == 150 and arguments.x:
                sendMail('Already 150 not detected faces', filepath='logs/sorted_set_facedetector.log')
79
80
81
82
83
84
        else:
            # Cut and save face
            for (x, y, w, h) in facefeatures:  # get coordinates and size of rectangle containing face
                totalFaces += 1
                gray = gray[y:y + h, x:x + w]  # Cut the frame to size
                try:
85
86
87
                    out = cv2.resize(gray, (arguments.resize, arguments.resize))  # Resize face so all images have same size
                    success = cv2.imwrite(datasetPath + '{}/{}.jpg'.format(emotion, fileNumber), out)  # Write image
                    if not success:
88
89
90
                        logging.error('Problem while writing file occurred...')
                        if arguments.x:
                            sendMail('Problem while writing file', body=f + ' to ' + datasetPath + '{}/{}.jpg'.format(emotion, fileNumber))
91
                except:
92
93
94
                    logging.error('Some error with ' + f)
                    if arguments.x:
                        sendMail('Problem while writing file', body=f)
95
                    pass  # If error, pass file
96

tihmels's avatar
tihmels committed
97
        totalFiles += 1  # Increment image number
98
        fileNumber += 1
tihmels's avatar
tihmels committed
99

100
101
if arguments.x:
    sendMail('Facedetector started notification')
102
103

for emotion in arguments.emotions:
Arne Gerdes's avatar
Arne Gerdes committed
104

105
106
    if not os.path.exists(datasetPath + emotion):
        os.makedirs(datasetPath + emotion)
Arne Gerdes's avatar
Arne Gerdes committed
107

108
109
    detect_faces(emotion)  # Call functional

110
111
logging.info('{} faces in {} files found'.format(totalFaces, totalFiles))
logging.info('In {} files no face could be detected'.format(totalFiles - totalFaces))
tihmels's avatar
tihmels committed
112

113
for f in undetected:
114
115
116
117
    logging.info(f)

if arguments.x:
    sendMail('Facedetector finished notification', filepath='logs/sorted_set_facedetector.log')