-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemotion.py
More file actions
59 lines (52 loc) · 1.8 KB
/
Copy pathemotion.py
File metadata and controls
59 lines (52 loc) · 1.8 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
#coding=utf-8
import cv2
from keras.models import load_model
import numpy as np
# import chineseText
import datetime
from PIL import Image, ImageDraw, ImageFont
startTime = datetime.datetime.now()
emotion_classifier = load_model(
'classifier/emotion_models/simple_CNN.530-0.65.hdf5'
)
endTime = datetime.datetime.now()
print(endTime - startTime)
emotion_labels = {
0: '生气',
1: '厌恶',
2: '恐惧',
3: '开心',
4: '难过',
5: '惊喜',
6: '平静'
}
img = cv2.imread("img/emotion/emotion.png")
face_classifier = cv2.CascadeClassifier(
"/Users/zhangjun/code/python/faceCV/data/haarcascades/haarcascade_frontalface_default.xml"
)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(
gray, scaleFactor=1.2, minNeighbors=3, minSize=(40, 40)
)
color = (255, 0, 0)
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
if(isinstance(img, np.ndarray)):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
draw.text((left, top), text, textColor, font=fontText)
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
for(x, y, w, h) in faces:
gray_face = gray[(y):(y+h), (x):(x+w)]
gray_face = cv2.resize(gray_face, (48, 48))
gray_face = gray_face / 255.0
gray_face = np.expand_dims(gray_face, 0)
gray_face = np.expand_dims(gray_face, -1)
emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face))
emotion = emotion_labels[emotion_label_arg]
cv2.rectangle(img, (x+10, y+10), (x+h-10, y+w-10), (255, 255, 255), 2)
print(emotion)
img = cv2ImgAddText(img, emotion, x+h*0.3, y, color, 20)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()