-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathextracting_faces.py
More file actions
60 lines (50 loc) · 2.65 KB
/
extracting_faces.py
File metadata and controls
60 lines (50 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#0916: Seongjin Shin
#sungjin712@gmail
#There are 2 requirements in this code
#1. Create folder called "sorted_set" and inside of it, emotion folders ("neutral", "anger" and so on) and images exists
#2. Create folder called "dataset" and insde of it, emotion folders("neutral", "anger" and so on) should exists
#It will extract face and save into "dataset folders"
import glob
import cv2
from shutil import copyfile
faceDet = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
faceDet2 = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
faceDet3 = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
faceDet4 = cv2.CascadeClassifier("haarcascade_frontalface_alt_tree.xml")
emotion = 'surprise'
emotions = ["neutral", "anger", "contempt", "disgust", "fear", "happy", "sadness", "surprise"] #Define emotions
files = glob.glob("sorted_set/%s/*" %emotion)
def detect_faces(emotion):
files = glob.glob("sorted_set/%s/*" %emotion) #Get list of all images with emotion
filenumber = 0
for f in files:
frame = cv2.imread(f) #Open image
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #Convert image to grayscale
#Detect face using 4 different classifiers
face = faceDet.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)
face2 = faceDet2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)
face3 = faceDet3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)
face4 = faceDet4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)
#Go over detected faces, stop at first detected face, return empty if no face.
if len(face) == 1:
facefeatures = face
elif len(face2) == 1:
facefeatures == face2
elif len(face3) == 1:
facefeatures = face3
elif len(face4) == 1:
facefeatures = face4
else:
facefeatures = ""
#Cut and save face
for (x, y, w, h) in facefeatures: #get coordinates and size of rectangle containing face
print "face found in file: %s" %f
gray = gray[y:y+h, x:x+w] #Cut the frame to size
try:
out = cv2.resize(gray, (350, 350)) #Resize face so all images have same size
cv2.imwrite("dataset/%s/%s.jpg" %(emotion, filenumber), out) #Write image
except:
pass #If error, pass file
filenumber += 1 #Increment image number
for emotion in emotions:
detect_faces(emotion) #Call functiona