-
Notifications
You must be signed in to change notification settings - Fork 61
/
human_detect_track.py
212 lines (163 loc) · 8.38 KB
/
human_detect_track.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
'''
Only tracking, no reidentification.
Tracking is done using last k=15 frames.
'''
import numpy as np
import tensorflow as tf
import cv2
import time
import os
from run import Reid
#from run import main2
from importlib import import_module
class DetectorAPI:
def __init__(self, path_to_ckpt):
self.reid = Reid()
self.path_to_ckpt = path_to_ckpt
#self.module = import_module('run')
self.detection_graph = tf.Graph()
with self.detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.path_to_ckpt, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
self.default_graph = self.detection_graph.as_default()
self.sess = tf.Session(graph=self.detection_graph)
# Definite input and output Tensors for detection_graph
self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
def processFrame(self, image):
# Expand dimensions since the trained_model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image, axis=0)
# Actual detection.
start_time = time.time()
(boxes, scores, classes, num) = self.sess.run(
[self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections],
feed_dict={self.image_tensor: image_np_expanded})
end_time = time.time()
#print("Elapsed Time:", end_time-start_time)
im_height, im_width,_ = image.shape
boxes_list = [None for i in range(boxes.shape[1])]
for i in range(boxes.shape[1]):
boxes_list[i] = (int(boxes[0,i,0] * im_height),
int(boxes[0,i,1]*im_width),
int(boxes[0,i,2] * im_height),
int(boxes[0,i,3]*im_width))
return boxes_list, scores[0].tolist(), [int(x) for x in classes[0].tolist()], int(num[0])
def close(self):
self.sess.close()
self.default_graph.close()
def find(self, img, boxes_cur, box):
cv2.imwrite('./temporaryImg.jpg',img)
past_ppl = './past_ppl'
folders = os.listdir(past_ppl)
for folder in folders:
files = os.listdir(past_ppl + '/' + folder)
for f in files:
#cmd = 'python3 ./run.py --image1=./temporaryImg.jpg --image2=' + past_ppl + '/' + folder + '/' + f
#mod = import_module('run')
ret = self.reid.compare('./temporaryImg.jpg' , './past_ppl/' + folder + '/' + f)
#ret = run(past_ppl + '/' + folder + '/' + f , './temporaryImg.jpg')
if(ret == True):
person_no = len(files) + 1
cv2.imwrite(past_ppl + '/' + folder + '/' + str(person_no) + '.jpg',img)
boxes_cur[ int(folder) ] = box
return
l = len(folders)
os.makedirs(past_ppl + '/' + str( l ) )
cv2.imwrite(past_ppl + '/' + str( l ) + '/1.jpg',img)
boxes_cur.append( box )
return
def iou(box1, box2):
xa = max( box1[1] , box2[1] )
ya = max( box1[0] , box2[0] )
xb = min( box1[3] , box2[3] )
yb = min( box1[2] , box2[2] )
interArea = max(0, xb - xa ) * max(0, yb - ya )
box1Area = (box1[2] - box1[0]) * (box1[3] - box1[1] )
box2Area = (box2[2] - box2[0]) * (box2[3] - box2[1] )
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = float(interArea) / float(box1Area + box2Area - interArea)
# return the intersection over union value
return iou
if __name__ == "__main__":
# model_path = '/path/to/faster_rcnn_inception_v2_coco_2017_11_08/frozen_inference_graph.pb'
model_path = './model/frozen_inference_graph.pb'
past_ppl = './past_ppl'
odapi = DetectorAPI(path_to_ckpt=model_path)
threshold = 0.8
iou_threshold = 0.6
cap = cv2.VideoCapture('./video.avi')
#maximum number of previous frames to check iou with
k = 25
#this will store the bounding boxes detected in the previous frame.
boxes_prev = []
framenum = 1
start_time = time.time(); #seconds
#iterate over frames
while True:
r, img = cap.read()
img = cv2.resize(img, (1280, 720))
boxes, scores, classes, num = odapi.processFrame(img)
boxes_cur = []
for l in range(len(boxes_prev)):
if( len(boxes_prev[l]) < k ):
boxes_cur.append( [-1] + boxes_prev[l] )
else:
boxes_cur.append( [-1] + boxes_prev[l][0:k-1] )
for i in range(len(boxes)):
# Class 1 represents human
if classes[i] == 1 and scores[i] > threshold:
box = boxes[i]
#draw the bounding box on the image
cv2.rectangle(img,(box[1],box[0]),(box[3],box[2]),(255,0,0),2)
cropped_img = img[ box[0]:box[2] , box[1]:box[3] ]
maxthreshold = -1
maxindex = 101 #the index in boxes_prev indicating the matching person from the previous k frames.
for j in range( len(boxes_prev) ):
#Every boxes_prev[j] denotes a person. It is a list of the last k positions of the person j.
if( boxes_prev[j] == -1 ): #This previous person has already been alloted to another person in the current frame
continue
for kk in range( len(boxes_prev[j]) ):
if(boxes_prev[j][kk] == -1): #person was not detected in frame kk
continue
r = iou( boxes_prev[j][kk] ,box)
if( r > maxthreshold and r > iou_threshold):
maxthreshold = r
maxindex = j
#maxthreshold != -1 at this point means this person is the same as prevbox in the last frame.
if( maxthreshold != -1 ):
#print('tracked ###########')
boxes_cur[ maxindex ][0] = box
boxes_prev[ maxindex ] = -1
#also add this image of the person to his previous images
person_no = len( os.listdir( past_ppl + '/' + str(maxindex) ) ) + 1
cv2.imwrite(past_ppl + '/' + str(maxindex) + '/' + str(person_no) + '.jpg',cropped_img)
else:
#The person was not present in the previous frame. Add him to a new folder.
#The folder name should be equal to the index of the person in box_cur.
folders = os.listdir(past_ppl)
l = len(folders)
os.makedirs(past_ppl + '/' + str( l ) )
cv2.imwrite(past_ppl + '/' + str( l ) + '/1.jpg',cropped_img)
boxes_cur.append( [box] )
num_ppl = len(os.listdir(past_ppl))
print('#People: ' + str(num_ppl))
print(' ')
#print('Time for '+ str(framenum) + ' frames: (seconds)')
#print( time.time() - start_time )
framenum += 1
boxes_prev = boxes_cur
cv2.imshow("preview", img)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break