1.所需环境:
python3
依赖包: opencv tensorflow keras dlib
这些包的下载教程全网可搜到 所以这就是我懒得写的借口了。
2.代码块
import os
import cv2
import time
import numpy as np
import argparse
import dlib
from contextlib import contextmanager
from wide_resnet import WideResNet
from keras.utils.data_utils import get_file
from keras.models import model_from_json
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.5/weights.28-3.73.hdf5"
modhash = ''
emotion_labels = ['angry', 'fear', 'happy', 'pingjing', 'surprise', 'neutral']
# load json and create model arch
json_file = open('model.json','r')
loaded_model_json = json_file.read()
json_file.close()
#将json重构为model结构
model = model_from_json(loaded_model_json)
# load weights into new model
model.load_weights('model.h5')
def predict_emotion(face_image_gray): # a single cropped face
resized_img = cv2.resize(face_image_gray, (48,48), interpolation = cv2.INTER_AREA)
image = resized_img.reshape(1, 1, 48, 48)
im = cv2.resize(resized_img,(90,100))
cv2.imwrite('face.bmp', im)
list_of_list = model.predict(image, batch_size=1, verbose=1)
angry, fear, happy, sad, surprise, neutral = [prob for lst in list_of_list for prob in lst]
return [angry, fear, happy, sad, surprise, neutral]
def get_args():
parser = argparse.ArgumentParser(description="This script detects faces from web cam input, "
"and estimates age and gender for the detected faces.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#改成自己的地址
parser.add_argument("--weight_file", type=str, default="./weights.28-3.73.hdf5",
help="path to weight file (e.g. weights.28-3.73.hdf5)")
parser.add_argument("--depth", type=int, default=16,
help="depth of network")
parser.add_argument("--width", type=int, default=8,
help="width of network")
args = parser.parse_args()
return args
def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,
font_scale=1, thickness=2):
size = cv2.getTextSize(label, font, font_scale, thickness)[0]
x, y = point
cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness)
@contextmanager
def video_capture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
def yield_images():
# capture video
camera = cv2.VideoCapture(0) # 初始化摄像头(0代表使用的第一个摄像头)。