.
faceAPI.py 封装Face ++ 的Face Detection API 接口,并返回封装的struct或者string
import requests
import json
import jsonpath
from json import JSONDecoder
http_url ="https://api-cn.faceplusplus.com/facepp/v3/detect"
key ="XXXX"
secret ="yyyy"
data = {"api_key":key, "api_secret": secret, "return_attributes": "gender,age,emotion,beauty"}
class FaceAttributes():
def __init__(self):
self.id=[]
self.region=[]
self.age=[]
self.gender=[]
self.beauty=[]
self.emotion = []
class Struct():
def __init__(self,id,region,age,gender,beauty,emotion):
self.id = id
self.region = region
self.age = age
self.gender = gender
self.beauty = beauty
self.emotion = emotion
def create_struct(self,id,region,age,gender,beauty,emotion):
return self.Struct(id,region,age,gender,beauty,emotion)
emotion_index=['happiness', 'anger', 'fear', 'disgust', 'sadness', 'neutral', 'surprise']
def face_rectangle(imgpath):
files = {"image_file": open(imgpath, "rb")}
response = requests.post(http_url, data=data, files=files)
req_con = response.content.decode('utf-8')
req_dict = JSONDecoder().decode(req_con)
face_list = []
print(req_dict)
if str(req_dict).find("error_message") >=0:
num_face=-1
return num_face,face_list
num_face=len(req_dict["faces"])
for i in range(0,num_face,1):
#face_list.append(str(req_dict["faces"][i]["face_rectangle"]["left"])+','+str(req_dict["faces"][i]["face_rectangle"]["top"])+','+str(req_dict["faces"][i]["face_rectangle"]["width"])+','+str(req_dict["faces"][i]["face_rectangle"]["height"]))
#id
id =str(req_dict["faces"][i]["face_token"])
#region
region =str(req_dict["faces"][i]["face_rectangle"]["left"])+'#'+str(req_dict["faces"][i]["face_rectangle"]["top"])+'#'+str(req_dict["faces"][i]["face_rectangle"]["width"])+'#'+str(req_dict["faces"][i]["face_rectangle"]["height"])
#age
age = str(req_dict["faces"][i]["attributes"]["age"]["value"])
#gender
gender =str(req_dict["faces"][i]["attributes"]["gender"]["value"])
# emotion : ['happiness', 'anger', 'fear', 'disgust', 'sadness', 'neutral', 'surprise']
emotion_value = 0.0
for iter in emotion_index:
emotion_value_new = float(req_dict["faces"][i]["attributes"]["emotion"][iter])
if emotion_value_new>emotion_value:
emotion_value = emotion_value_new
emotion=iter
#beauty : female_score, male_score
# beauty =req_dict["faces"][i]["attributes"]["beauty"]
if gender=='Female':
beauty = str(req_dict["faces"][i]["attributes"]["beauty"]["female_score"])
else:
beauty = str(req_dict["faces"][i]["attributes"]["beauty"]["male_score"])
temp = id+","+region+","+age+","+gender+","+beauty+","+emotion
#face = FaceAttributes()
#face_struct = face.create_struct(id,region,age,gender,beauty,emotion)
#face_list.append(face_struct)
face_list.append(temp)
return num_face,face_list
imgpath='777.jpg'
if __name__ == '__main__':
num_face,face_list = face_rectangle(imgpath)
#print("Detected {} face".format(num_face))
for face_i in face_list:
print(face_i)
detectFace.py 使用opencv读取视频,每秒取一张图片,进行检测
import cv2
import sys
import os
import dlib
import numpy
from PIL import Image
import faceAPI
def CatchVideoFrame(window_name,save_list):
#cv2.namedWindow(window_name)
video = cv2.VideoCapture('G:/迅雷下载/建国大业.BD1280超清国语中英双字.mp4')
fps = int(video.get(cv2.CAP_PROP_FPS))
num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
print("VideoName:{},num_frames:{},fps:{}".format('建国大业',num_frames,fps))
fout = open(save_list, 'w')
idx = 0
for i in range(0,num_frames,fps):
video.set(1,i)
ok,frame = video.read()
if not ok:
print("video is break")
break
img_path = sys.path[0] + '/temp/' + str(i) + '.jpg'
cv2.imwrite(img_path, frame)
num_face, face_list = faceAPI.face_rectangle(img_path)
if num_face==-1:
continue
elif num_face >0:
for var in face_list:
fout.write(str(var) +"\n")
region_var = var.split(',')
print(region_var[1])
val = region_var[1].split('#')
region = frame[int(val[0]):int(val[0])+int(val[2]),int(val[1]):int(val[1])+int(val[3]),:]
cv2.imwrite(sys.path[0]+'/image/'+region_var[0]+'.jpg',region)
cv2.imshow("frame", frame)
cl = cv2.waitKey(10)
if cl & 0xFF == ord('q'):
break
video.release()
fout.close()
cv2.destroyAllWindows()
if __name__ == '__main__':
CatchVideoFrame("video_show","save_list.txt")