-
Notifications
You must be signed in to change notification settings - Fork 1
/
detect_age_file.py
167 lines (131 loc) · 5.37 KB
/
detect_age_file.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# python detect_age_video.py --face face_detector --age age_detector
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import cv2
import os
def detect_and_predict_age(frame, faceNet, ageNet, minConf=0.5):
# define the list of age buckets our age detector will predict
results = []
AGE_BUCKETS = ["(0-2)", "(4-6)", "(8-12)", "(15-20)", "(25-32)",
"(38-43)", "(48-53)", "(60-100)"]
# initialize our results list
# grab the dimensions of the frame and then construct a blob
# from it
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),
(104.0, 177.0, 123.0))
# pass the blob through the network and obtain the face detections
faceNet.setInput(blob)
detections = faceNet.forward()
# loop over the detections
for i in range(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated with
# the prediction
confidence = detections[0, 0, i, 2]
# filter out weak detections by ensuring the confidence is
# greater than the minimum confidence
if confidence > minConf:
# compute the (x, y)-coordinates of the bounding box for
# the object
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# extract the ROI of the face
face = frame[startY:endY, startX:endX]
# ensure the face ROI is sufficiently large
if face.shape[0] < 20 or face.shape[1] < 20:
continue
# construct a blob from *just* the face ROI
faceBlob = cv2.dnn.blobFromImage(face, 1.0, (227, 227),
(78.4263377603, 87.7689143744, 114.895847746),
swapRB=False)
# make predictions on the age and find the age bucket with
# the largest corresponding probability
ageNet.setInput(faceBlob)
preds = ageNet.forward()
i = preds[0].argmax()
age = AGE_BUCKETS[i]
ageConfidence = preds[0][i]
#Gender Prediction
genderNet = cv2.dnn.readNet( "deploy_gender.prototxt", "gender_net.caffemodel")
genderList = ['Male', 'Female']
blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), (78.4263377603, 87.7689143744, 114.895847746), swapRB=False)
genderNet.setInput(blob)
genderPreds = genderNet.forward()
j = genderPreds[0].argmax()
gender = genderList[j]
genderConfidence = genderPreds[0][j]
# construct a dictionary consisting of both the face
# bounding box location along with the age prediction,
# then update our results list
d = {
"loc": (startX, startY, endX, endY),
"age": (age, ageConfidence,gender,genderConfidence)
}
results.append(d)
# return our results to the calling function
return results
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
#ap.add_argument("-f", "--face", required=True,
# help="path to face detector model directory")
#ap.add_argument("-a", "--age", required=True,
# help="path to age detector model directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
# load our serialized face detector model from disk
print("[INFO] loading face detector model...")
prototxtPath = os.path.sep.join(["face_detector", "deploy.prototxt"])
weightsPath = os.path.sep.join(["face_detector",
"res10_300x300_ssd_iter_140000.caffemodel"])
faceNet = cv2.dnn.readNet("deploy.prototxt","res10_300x300_ssd_iter_140000.caffemodel")
# load our serialized age detector model from disk
print("[INFO] loading age detector model...")
prototxtPath = os.path.sep.join(["age_detector", "age_deploy.prototxt"])
weightsPath = os.path.sep.join(["age_detector", "age_net.caffemodel"])
ageNet = cv2.dnn.readNet("age_deploy.prototxt","age_net.caffemodel")
print("[INFO] loading gender detector model...")
# initialize the video stream and allow the camera sensor to warm up
print("[INFO] starting video stream...")
vs = cv2.VideoCapture('test.mp4')
time.sleep(2.0)
# loop over the frames from the video stream
while (vs.isOpened()):
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
ret, frame = vs.read()
#frame = vs.read()
if ret==False:
break
frame = imutils.resize(frame, width=400)
# detect faces in the frame, and for each face in the frame,
# predict the age
results = detect_and_predict_age(frame, faceNet, ageNet,
minConf=args["confidence"])
# loop over the results
for r in results:
# draw the bounding box of the face along with the associated
# predicted age
#text = "{}: {:.2f}%".format(r["age"][0], r["age"][1] * 100)
text="{}:{}:{:.2f}%:{}".format("True",r["age"][0], r["age"][1] * 100, r["age"][2]) if r["age"][0]=="(15-20)" or r["age"][0]=="(25-32)" or r["age"][0]=="(38-43)" or r["age"][0]=="(48-53)" or r["age"][0]=="(60-100)" else "{}:{}:{:.2f}%:{}".format("False", r["age"][0],r["age"][1] * 100, r["age"][2])
(startX, startY, endX, endY) = r["loc"]
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(frame, (startX, startY), (endX, endY),
(0, 0, 255), 1)
x = startX-50 if startX-50>50 else startX+50
cv2.putText(frame, text, (x, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
# show the output frame
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# do a bit of cleanup
vs.release()
cv2.destroyAllWindows()