-
Notifications
You must be signed in to change notification settings - Fork 0
/
pedestrian_detect.py
432 lines (356 loc) · 14.2 KB
/
pedestrian_detect.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# ====================================================
# ==================== PACKAGES ======================
# ====================================================
## WORKING SPECS:
# OpenCV_3.1.0
# Python_2.7.12
import numpy as np
import cv2
import colorsys
import collections
# ====================================================
# ================== DEFINE CLASS ====================
# ====================================================
class Position(object):
def __init__(self, _x, _y, _w, _h):
self.x = _x
self.y = _y
self.w = _w
self.h = _h
def x(self):
return self.x
def y(self):
return self.y
def w(self):
return self.w
def h(self):
return self.h
class People(object):
def __init__(self, _x, _y, _w, _h, _roi, _hue):
# Position
self.x = _x
self.y = _y
self.w = _w
self.h = _h
self.roi = _roi
# Display of the contour while tracking
self.hue = _hue
self.color = hsv2rgb(self.hue % 1, 1, 1)
# Motion Descriptors
self.center = [_x + _w / 2, _y + _h / 2]
self.isIn = checkPosition(boundaryPt1, boundaryPt2, self.center, inCriterion)
self.isInChangeFrameCount = toleranceCountIOStatus
self.speed = [0, 0]
self.missingCount = 0
# ROI - Region of Interest
self.maxRoi = _roi
self.roi = _roi
def x(self):
return self.x
def y(self):
return self.y
def w(self):
return self.w
def h(self):
return self.h
def roi(self):
return self.roi
def color(self):
return self.color
def center(self):
return self.center
def maxRoi(self):
return self.maxRoi
def isIn(self):
return self.isIn
def speed(self):
return self.speed
def missingCount(self):
return self.missingCount
def isInChangeFrameCount(self):
return self.isInChangeFrameCount
def set(self, name, value):
if name == "x":
self.x = value
elif name == "y":
self.y = value
elif name == "w":
self.w = value
elif name == "h":
self.h = value
elif name == "center":
self.center = value
elif name == "roi":
self.roi = value
# Automatically update maxRoi as roi is updated
if self.roi.shape[0] * self.roi.shape[1] > self.maxRoi.shape[0] * self.maxRoi.shape[1]:
self.maxRoi = self.roi
elif name == "speed":
self.speed = value
elif name == "missingCount":
self.missingCount = value
elif name == "isIn":
self.isIn = value
elif name == "isInChangeFrameCount":
self.isInChangeFrameCount = value
else:
return
# ====================================================
# ===================== FUNCTION =====================
# ====================================================
def averageSize():
sum = 0
for i in humanSizeSample:
sum += i
return sum / sampleSize
# Only care about top and bottom
def checkTouchVSide(x, y, w, h, maxW, maxH, tolerance):
if x <= 0:
return True
elif y - tolerance <= 0:
return True
elif x + w >= maxW:
return True
elif y + h + tolerance >= maxH:
return True
else:
return False
def getExteriorRect(pts):
xArray = []
yArray = []
for pt in pts:
xArray.append(pt[0])
yArray.append(pt[1])
xArray = sorted(xArray)
yArray = sorted(yArray)
return (xArray[0], yArray[0], xArray[3] - xArray[0], yArray[3] - yArray[0])
def hsv2rgb(h, s, v):
return tuple(i * 255 for i in colorsys.hsv_to_rgb(h, s, v))
def checkPosition(boundaryPt1, boundaryPt2, currPos, inCriterion):
m = (boundaryPt2[1] - boundaryPt1[1]) / (boundaryPt2[0] - boundaryPt1[0])
c = boundaryPt2[1] - m * boundaryPt2[0]
if inCriterion == "<":
if currPos[0] * m + c < currPos[1]:
return True
else:
return False
elif inCriterion == ">":
if currPos[0] * m + c > currPos[1]:
return True
else:
return False
else:
return False
def nothing(x):
pass
# ====================================================
# ================== VIDEO SOURCE ====================
# ====================================================
srcTest = "E:\Data\Traffic_Surveillance_1_hour/JunctionQMUL.avi".replace('\\', '/')
srcWebcam = 0
srcMain = '' # live source here
cap = cv2.VideoCapture(srcTest) # Open video file
# ====================================================
# ================== PRE-CONFIG ======================
# ====================================================
minArea = 500 # default min area to be considered person
maxArea = 4000 # default max area to be considered person
noFrameToCollectSample = 100
toleranceRange = 50 # use for error calculation
toleranceCount = 10 # maximum number of frame an object need to present in order to be accepted
toleranceCountIOStatus = 3 # minimum number of frame between In/Out Status change -> prevent playing with the system
startHue = 0 # In HSV this is RED
hueIncrementValue = 0.1 # increment color every time to differentiate between different people
# ====================================================
# ====================== SETUP =======================
# ====================================================
# fgbg = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold = 16, detectShadows=True)
fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=True)
sampleSize = 100
humanSizeSample = collections.deque(maxlen=sampleSize)
midHeight = int(cap.get(4) / 2)
maxWidth = cap.get(3)
maxHeight = cap.get(4)
inCriterion = "<"
boundaryPt1 = [0, midHeight - 100]
boundaryPt2 = [maxWidth, midHeight]
# ====================================================
# ====================== MAIN ========================
# ====================================================
# Passage Control
allowPassage = True
peopleViolationIn = 0
peopleViolationOut = 0
switch = '0 : PASS \n1 : STOP'
# Controller
cv2.namedWindow('config')
cv2.createTrackbar(switch, 'config', 0, 1, nothing)
# Initializa Other Variable
averageArea = 0.000 # for calculation of min/max size for contour detected
peopleIn = 0 # number of people going up
peopleOut = 0 # number of people going up
frameCounter = 0
maskT = None
passImage = None
detectedPeople = []
detectedContours = []
# take first frame of the video
_, pFrame = cap.read()
while (cap.isOpened()):
# Check Passage Status
status = cv2.getTrackbarPos(switch, 'config')
if status == 0:
allowPassage = True
else:
allowPassage = False
# RE-Initialize
frameInfo = np.zeros((400, 500, 3), np.uint8)
averageArea = averageSize()
ret, frame = cap.read() # read a frame
frameForView = frame.copy()
# Clean Frame
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fgmask = fgbg.apply(gray)
blur = cv2.medianBlur(fgmask, 5)
thresh = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)[1] # shadow of MOG@ is grey = 127
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) # fill any small holes
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel) # remove noise
contours = cv2.findContours(opening.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[1]
mask_opening = cv2.inRange(opening, np.array([0]), np.array([128]))
noBg = cv2.bitwise_and(frame, frame, mask=mask_opening)
# Process Contours
for c in contours:
# Filter Contour By Size
if len(humanSizeSample) < 100:
if cv2.contourArea(c) < minArea or cv2.contourArea(c) > maxArea:
continue
else:
humanSizeSample.append(cv2.contourArea(c))
else:
if cv2.contourArea(c) < averageArea / 2 or cv2.contourArea(c) > averageArea * 3:
continue
(x, y, w, h) = cv2.boundingRect(c)
detectedContours.append(Position(x, y, w, h))
# Process Detected People
if len(detectedPeople) != 0:
for people in detectedPeople:
# Setup Meanshift/Camshift for Tracking
track_window = (people.x, people.y, people.w, people.h)
hsv_roi = pOpening[people.y:people.y + people.h, people.x:people.x + people.w]
mask = cv2.inRange(hsv_roi, np.array(128), np.array(256))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [100], [0, 256])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
term_criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 1,
1) # Setup the termination criteria, either 10 iteration or move by atleast 1 pt
dst = cv2.calcBackProject([opening], [0], roi_hist, [0, 256], 1)
ret, track_window = cv2.CamShift(dst, track_window, term_criteria)
# Process POST Tracking
pts = cv2.boxPoints(ret)
pts = np.int0(pts)
img2 = cv2.polylines(frameForView, [pts], True, people.color, 2)
pos = sum(pts) / len(pts)
isFound = False
for dC in detectedContours:
if dC.x - toleranceRange < pos[0] < dC.x + dC.w + toleranceRange \
and dC.y - toleranceRange < pos[1] < dC.y + dC.h + toleranceRange:
people.set("x", dC.x)
people.set("y", dC.y)
people.set("w", dC.w)
people.set("h", dC.h)
people.set("speed", pos - people.center)
people.set("center", pos)
people.set("missingCount", 0)
detectedContours.remove(dC)
isFound = True
tR = getExteriorRect(pts)
people.set("roi", frame[tR[1]:tR[1] + tR[3], tR[0]:tR[0] + tR[2]])
# Process Continuous Tracking
prevInStatus = people.isIn
currInStatus = checkPosition(boundaryPt1, boundaryPt2, people.center, inCriterion)
people.isIn = currInStatus
# Check In/Out Status Change
if prevInStatus != currInStatus and people.isInChangeFrameCount >= toleranceCountIOStatus:
if not allowPassage:
passImage = people.roi
people.set("isInChangeFrameCount", 0)
if currInStatus:
peopleIn += 1
if not allowPassage:
peopleViolationIn += 1
else:
peopleOut += 1
if not allowPassage:
peopleViolationOut += 1
else:
people.set("isInChangeFrameCount", people.isInChangeFrameCount + 1)
# Process DIS-continuous Tracking
if not isFound:
if people.missingCount > toleranceCount:
detectedPeople.remove(people)
else:
if checkTouchVSide(people.x + people.speed[0], people.y + people.speed[1], people.w,
people.h, maxWidth, maxHeight, toleranceRange):
detectedPeople.remove(people)
else:
people.set("missingCount", people.missingCount + 1)
people.set("x", people.x + people.speed[0])
people.set("y", people.y + people.speed[1])
people.set("center", people.center + people.speed)
# Check New People
for dC in detectedContours:
if checkTouchVSide(dC.x, dC.y, dC.w, dC.h, maxWidth, maxHeight, toleranceRange):
startHue += hueIncrementValue
detectedPeople.append(People(dC.x, dC.y, dC.w, dC.h, frame[dC.y:dC.y + dC.h, dC.x:dC.x + dC.w], startHue))
# RE-set
detectedContours = []
pFrame = frame
pNoBg = noBg
pOpening = opening
frameCounter += 1
# Output
try:
# Setup Stats
textNoOfPeople = "People: " + str(len(detectedPeople))
textNoIn = "In: " + str(peopleIn)
textNoOut = "Out: " + str(peopleOut)
textNoViolationIn = "In: " + str(peopleViolationIn)
textNoViolationOut = "Out: " + str(peopleViolationOut)
if allowPassage:
cv2.line(frameForView, (int(boundaryPt1[0]), int(boundaryPt1[1])),
(int(boundaryPt2[0]), int(boundaryPt2[1])), (0, 255, 0), 2)
else:
cv2.line(frameForView, (int(boundaryPt1[0]), int(boundaryPt1[1])),
(int(boundaryPt2[0]), int(boundaryPt2[1])), (0, 0, 255), 2)
# Draw Infos
cv2.putText(frameInfo, textNoOfPeople, (30, 40), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(frameInfo, textNoIn, (30, 80), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(frameInfo, textNoOut, (30, 120), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.line(frameInfo, (0, 160), (640, 160), (255, 255, 255), 1)
cv2.putText(frameInfo, "VIOLATION", (30, 200), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(frameInfo, textNoViolationIn, (30, 240), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(frameInfo, textNoViolationOut, (30, 280), cv2.FONT_HERSHEY_SIMPLEX
, 1, (255, 255, 255), 1, cv2.LINE_AA)
# Display
cv2.imshow('FrameForView', frameForView)
# cv2.imshow('Frame', frame)
if passImage != None:
cv2.imshow('Violators', passImage)
cv2.imshow('config', frameInfo)
except:
print('EOF')
break
# Abort and exit with 'Q' or ESC
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# else:
# cv2.imwrite(chr(k) + ".jpg", frame)
cap.release()
cv2.destroyAllWindows()