Repository navigation
Expand file tree
/
Copy pathcountYolo.py
More file actions
340 lines (291 loc) · 12.5 KB
/
Copy pathcountYolo.py
File metadata and controls
340 lines (291 loc) · 12.5 KB
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
import numpy as np
import argparse
import cv2
import os
import Vehicle
import time
import argparse
import os
#cv2.namedWindow('image', cv2.WINDOW_NORMAL)
#cv2.resizeWindow('image', 64,64)
#-------------------YOLO-----------------#
def extract_boxes_confidences_classids(outputs, confidence, width, height):
boxes = []
confidences = []
classIDs = []
for output in outputs:
for detection in output:
# Extract the scores, classid, and the confidence of the prediction
scores = detection[5:]
classID = np.argmax(scores)
conf = scores[classID]
# Consider only the predictions that are above the confidence threshold
if conf > confidence:
# Scale the bounding box back to the size of the image
box = detection[0:4] * np.array([width, height, width, height])
centerX, centerY, w, h = box.astype('int')
# Use the center coordinates, width and height to get the coordinates of the top left corner
x = int(centerX - (w / 2))
y = int(centerY - (h / 2))
boxes.append([x, y, int(w), int(h)])
confidences.append(float(conf))
classIDs.append(classID)
return boxes, confidences, classIDs
def draw_bounding_boxes(image, boxes, confidences, classIDs, idxs, colors):
if len(idxs) > 0:
for i in idxs.flatten():
# extract bounding box coordinates
x, y = boxes[i][0], boxes[i][1]
w, h = boxes[i][2], boxes[i][3]
# draw the bounding box and label on the image
color = [int(c) for c in colors[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = "{}: {:.4f}".format(labels[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
return image
def make_prediction(net, layer_names, labels, image, confidence, threshold):
height, width = image.shape[:2]
# Create a blob and pass it through the model
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(layer_names)
# Extract bounding boxes, confidences and classIDs
boxes, confidences, classIDs = extract_boxes_confidences_classids(outputs, confidence, width, height)
# Apply Non-Max Suppression
idxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence, threshold)
return boxes, confidences, classIDs, idxs
#----------------------------------------#
cnt_up = 0
cnt_down = 0
UpMTR = 0
UpLV = 0
UpHV = 0
DownLV = 0
DownHV = 0
# set input video
#cap = cv2.VideoCapture('D:/Stage/67 HA/DJI_0006.mp4')
cap = cv2.VideoCapture('autoroute.mp4')
# Capture the properties of VideoCapture to console (mengambil properties video eg. width, height dll)
for i in range(19):
# print properties video
print (i, cap.get(i))
# mengambil width dan heigth video dari properties (value w posisi ke 3, h posisi ke 4)
w = cap.get(3)
print ('Width', w)
h = cap.get(4)
print ('Height', h)
# luas frame area h*w
frameArea = h*w
areaTH = frameArea/800
print ('Area Threshold', areaTH)
# Input/Output Lines
# yang itung kendaraan turun (biru)
line_up = int(2*(h/5))
# yang itung kendaraan naik (merah), untuk setting garis
line_down = int(3*(h/5))
up_limit = int(1*(h/5))
down_limit = int(4*(h/5))
print("Red line y:", str(line_down))
print ("Blue line y:", str(line_up))
line_down_color = (255,0,0)
line_up_color = (0,0,255)
# set height garis
pt1 = [0, line_down]
# set lebar garis sesuai width video
pt2 = [w, line_down]
pts_L1 = np.array([pt1,pt2], np.int32)
pts_L1 = pts_L1.reshape((-1,1,2))
# set height garis
pt3 = [0, line_up]
# set lebar garis sesuai width video
pt4 = [w, line_up]
pts_L2 = np.array([pt3,pt4], np.int32)
pts_L2 = pts_L2.reshape((-1,1,2))
pt5 = [0, up_limit]
pt6 = [w, up_limit]
pts_L3 = np.array([pt5,pt6], np.int32)
pts_L3 = pts_L3.reshape((-1,1,2))
pt7 = [0, down_limit]
pt8 = [w, down_limit]
pts_L4 = np.array([pt7,pt8], np.int32)
pts_L4 = pts_L4.reshape((-1,1,2))
#Create the background subtractor
fgbg = cv2.createBackgroundSubtractorMOG2()
kernelOp = np.ones((3,3), np.uint8)
kernelOp2 = np.ones((5,5), np.uint8)
kernelCl = np.ones((11,11), np.uint8)
#Variables
font = cv2.FONT_HERSHEY_PLAIN
vehicles = []
max_p_age = 5
pid = 1
# Get the ouput layer names
while(cap.isOpened()):
#read a frame
ret, frame = cap.read()
for i in vehicles:
i.age_one() # age every person on frame
#################
# PREPROCESSING #
#################
fgmask = fgbg.apply(frame)
fgmask2 = fgbg.apply(frame)
# Binary to remove shadow
try:
#cv2.imshow('Frame', frame)
#cv2.imshow('Backgroud Subtraction', fgmask)
ret, imBin = cv2.threshold(fgmask, 200, 255, cv2.THRESH_BINARY)
ret, imBin2 = cv2.threshold(fgmask2, 200, 255, cv2.THRESH_BINARY)
#Opening (erode->dilate) to remove noise
mask = cv2.morphologyEx(imBin, cv2.MORPH_OPEN, kernelOp)
mask2 = cv2.morphologyEx(imBin2, cv2.MORPH_OPEN, kernelOp)
#Closing (dilate->erode) to join white region
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernelCl)
mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, kernelCl)
cv2.imshow('Image Threshold', cv2.resize(fgmask, (400, 300)))
# cv2.imshow('Image Threshold2', cv2.resize(fgmask2, (400, 300)))
cv2.imshow('Masked Image', cv2.resize(mask, (400, 300)))
# cv2.imshow('Masked Image2', cv2.resize(mask2, (400, 300)))
except:
#If there is no more frames to show...
print('EOF')
print ('UP:', cnt_up)
print ('DOWN:', cnt_down)
break
##################
## FIND CONTOUR ##
##################
contours0, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours0:
# membuat kontur/garis mengikuti objek bergerak
# cv2.drawContours(frame, cnt, -1, (0,255,0), 3, 8)
area = cv2.contourArea(cnt)
# print area," ",areaTH
# if area > areaTH and area < 20000:
# mengatur ukuran kendaraan yang dideteksi
if area > areaTH:
# print 'Area:::', area
################
# TRACKING #
################
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
x,y,w,h = cv2.boundingRect(cnt)
# the object is near the one which already detect before
new = True
for i in vehicles:
if abs(x-i.getX()) <= w and abs(y-i.getY()) <= h:
new = False
i.updateCoords(cx,cy) # Update the coordinates in the object and reset age
# jika objek melewati garis biru duluan berarti going up, dicek di Vehicle.py
if i.going_UP(line_down, line_up) == True:
roi = frame[y:y + h, x:x + w]
rectangle = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
height = h
width = w
kll = 2 * (height + width)
# atur parameter luas rectangle berdasarkan video
if kll < 300:
UpMTR += 1
elif kll < 500:
UpLV += 1
elif kll > 500:
UpHV += 1
# cv2.imshow('Region of Interest', roi)
# cv2.imshow('Rectangle', rectangle)
# print "Area equal to ::::", area
cnt_up += 1
# jika objek melewati garis merah duluan berarti going down, dicek di Vehicle.py
elif i.going_DOWN(line_down, line_up) == True:
roi = frame[y:y+h, x:x+w]
rectangle = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
height = y+h
width = x+w
luas = height*width
# print 'Height:::', height
# print 'Width:::', width
# print 'Luas:::', luas
# atur parameter luas rectangle berdasarkan video
if luas < 600000:
DownLV += 1
elif luas > 600000:
DownHV += 1
# cv2.imshow('Region of Interest', roi)
# cv2.imshow('Rectangle', rectangle)
# print "Area equal to ::::", area
cnt_down += 1
print ("ID:", i.getId(), 'crossed going down at', time.strftime("%c"))
break
if i.getState() == '1':
if i.getDir() == 'down' and i.getY() > down_limit:
i.setDone()
elif i.getDir() == 'up' and i.getY() < up_limit:
i.setDone()
if i.timedOut():
# Remove from the list person
index = vehicles.index(i)
vehicles.pop(index)
del i
if new == True:
p = Vehicle.MyVehicle(pid,cx,cy, max_p_age)
vehicles.append(p)
pid += 1
##################
## DRAWING ##
##################
cv2.circle(frame,(cx,cy),5, (0,0,255), -1)
img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1)
# height = y+h
# print 'height::::', height
# print 'Rectangle size', img
#cv2.drawContours(frame, cnt, -1, (0,255,0), 3)
#cv2.imshow('Image', cv2.resize(img, (400, 300)))
for i in vehicles:
"""
if len(i.getTracks()) >= 2:
pts = np.array(i.getTracks(), np.int32)
pts = pts.reshape((-1,1,2))
frame = cv2.polylines(frame, [pts], False, i.getRGB())
if i.getId() == 9:
print str(i.getX()), ',', str(i.getY())
"""
cv2.putText(frame, str(i.getId()), (i.getX(),i.getY()),font,0.5,i.getRGB(),1,cv2.LINE_AA)
###############
## IMAGE ##
###############
# str_up = 'UP: ' + str(cnt_up)
MTR_up = 'Up Motor: ' + str(UpMTR)
LV_up = 'Up Mobil: ' + str(UpLV)
HV_up = 'Up Truck/Bus: ' + str(UpHV)
# str_down = 'DOWN: ' + str(cnt_down)
LV_down = 'Down Mobil: ' + str(DownLV)
HV_down = 'Down Truck/Bus: ' + str(DownHV)
frame = cv2.polylines(frame, [pts_L1], False, line_down_color, thickness=2)
frame = cv2.polylines(frame, [pts_L2], False, line_up_color, thickness=2)
frame = cv2.polylines(frame, [pts_L3], False, (255,255,255), thickness=1)
frame = cv2.polylines(frame, [pts_L4], False, (255,255,255), thickness=1)
# cv2.putText(frame, str_up, (10,40),font,2,(255,255,255),2,cv2.LINE_AA)
# cv2.putText(frame, str_up, (10,40),font,2,(0,0,255),1,cv2.LINE_AA)
# cv2.putText(frame, "FPS: {:05.2f}".format(fps), (10, 30), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)
# cv2.putText(frame, MTR_up, (10, 30), font, 2, (255, 255, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, MTR_up, (10, 40), font,1, (0, 0, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, LV_up, (10, 60), font, 1, (255, 255, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, LV_up, (10, 60), font, 1, (0, 0, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, HV_up, (10, 80), font, 1, (255, 255, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, HV_up, (10, 80), font, 1, (0, 0, 255), 1, cv2.FONT_HERSHEY_PLAIN)
# cv2.putText(frame, str_down, (10,90),font,2,(255,255,255),2,cv2.LINE_AA)
# cv2.putText(frame, str_down, (10,90),font,2,(255,0,0),1,cv2.LINE_AA)
cv2.putText(frame, LV_down, (10, 120), font, 1, (255, 255, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, LV_down, (10, 120), font, 1, (255, 0, 0), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, HV_down, (10, 140), font, 1, (255, 255, 255), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.putText(frame, HV_down, (10, 140), font, 1, (255, 0, 0), 1, cv2.FONT_HERSHEY_PLAIN)
cv2.imshow('Frame', cv2.resize(frame, (600, 500)))
# cv2.imshow('Frame', cv2.resize(frame, (1280, 720)))
#cv2.imshow('Backgroud Subtraction', fgmask)
#Abort and exit with 'Q' or ESC
k = cv2.waitKey(120) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()