-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvehicle.py
More file actions
80 lines (54 loc) · 2.22 KB
/
vehicle.py
File metadata and controls
80 lines (54 loc) · 2.22 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
from cmath import rect
import cv2
import numpy as np
#web camera
cap = cv2.VideoCapture('video.mp4')
min_width_react=80 #min width reactangle
min_hieght_react=80 #min width reactangle
count_line_position= 550
# Initialize Substructor
algo= cv2.bgsegm.createBackgroundSubtractorMOG()
def center_handle(x,y,w,h):
x1=int(w/2)
y1=int(h/2)
cx= x+x1
cy= y+y1
return cx,cy
detect = []
offset=6 #Allowable error between pixel
counter=0
while True:
ret,frame1= cap.read()
grey = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(grey,(3,3),5)
# applying on each frame
img_sub = algo.apply(blur)
dilat = cv2.dilate(img_sub,np.ones((5,5)))
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
dilatada = cv2.morphologyEx(dilat, cv2.MORPH_CLOSE, kernel)
dilatada = cv2.morphologyEx(dilatada, cv2.MORPH_CLOSE, kernel)
counterShape,h = cv2.findContours(dilatada, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.line(frame1,(25,count_line_position),(1200,count_line_position),(255,127,0),3)
for (i,c) in enumerate(counterShape):
(x,y,w,h)=cv2.boundingRect(c)
validate_counter = (w>= min_width_react) and (h>= min_hieght_react)
if not validate_counter:
continue
cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(frame1,"vehicle"+str(counter),(x, y-20), cv2.FONT_HERSHEY_TRIPLE, 1, (255,244,0), 2)
center= center_handle(x,y,w,h)
detect.append(center)
cv2.circle(frame1,center,4, (0,0,255),-1)
for (x,y) in detect:
if y<(count_line_position+offset) and y>(count_line_position+offset):
counter+=1
cv2.line(frame1,(25,count_line_position),(1200,count_line_position),(0,127,255),3)
detect.remove((x,y))
print("vehicle Counter:"+str(counter))
cv2.putText(frame1,"VEHICLE COUNTER:"+str(counter),(450,70),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),5)
#cv2.imshow('Detecter',dilatada)
cv2.imshow('Video Original',frame1)
if cv2.waitKey(1) == 13:
break
cv2.destroyAllWindows()
cap.release()