-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.py
170 lines (140 loc) · 6.52 KB
/
Main.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
from tkinter import messagebox
from tkinter import *
from tkinter import simpledialog
import tkinter
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
import time
import cv2
import tensorflow as tf
from collections import namedtuple
from collections import defaultdict
from io import StringIO
from PIL import Image
import numpy as np
import winsound
main = tkinter.Tk()
main.title("Accident Detection")
main.geometry("1300x1200")
global filename
global detectionGraph
global msg
import vonage
client = vonage.Client(key="0a71f197", secret="yuMIXC3WFROfQH2N")
sms = vonage.Sms(client)
def loadModel():
global detectionGraph
detectionGraph = tf.Graph()
with detectionGraph.as_default():
od_graphDef = tf.GraphDef()
with tf.gfile.GFile('model/frozen_inference_graph.pb', 'rb') as file:
serializedGraph = file.read()
od_graphDef.ParseFromString(serializedGraph)
tf.import_graph_def(od_graphDef, name='')
messagebox.showinfo("Training model loaded","Training model loaded")
def beep():
frequency = 2500 # Set Frequency To 2500 Hertz
duration = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)
def uploadVideo():
global filename
filename = filedialog.askopenfilename(initialdir="videos")
pathlabel.config(text=filename)
text.delete('1.0', END)
text.insert(END,filename+" loaded\n");
def calculateCollision(boxes,classes,scores,image_np):
global msg
#cv2.putText(image_np, "NORMAL!", (230, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)
for i, b in enumerate(boxes[0]):
if classes[0][i] == 3 or classes[0][i] == 6 or classes[0][i] == 8:
if scores[0][i] > 0.5:
for j, c in enumerate(boxes[0]):
if (i != j) and (classes[0][j] == 3 or classes[0][j] == 6 or classes[0][j] == 8) and scores[0][j]> 0.5:
Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')
ra = Rectangle(boxes[0][i][3], boxes[0][i][2], boxes[0][i][1], boxes[0][i][3])
rb = Rectangle(boxes[0][j][3], boxes[0][j][2], boxes[0][j][1], boxes[0][j][3])
ar = rectArea(boxes[0][i][3], boxes[0][i][1],boxes[0][i][2],boxes[0][i][3])
col_threshold = 0.6*np.sqrt(ar)
area(ra, rb)
if (area(ra,rb)<col_threshold) :
print('accident')
msg = 'ACCIDENT OCCURRED!'
beep()
responseData = sms.send_message(
{
"from": "Vonage APIs",
"to": "919347515384",
"text": "Alert!Alert! Accident detected.location:https://maps.app.goo.gl/Hpa1oDHCqGhdJYAAA",
})
if responseData["messages"][0]["status"] == "0":
print("Message sent successfully.")
else:
print(f"Message failed with error: {responseData['messages'][0]['error-text']}")
return True
else:
return False
def rectArea(xmax, ymax, xmin, ymin):
x = np.abs(xmax-xmin)
y = np.abs(ymax-ymin)
return x*y
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
def area(a, b): # returns None if rectangles don't intersect
dx = min(a.xmax, b.xmax) - max(a.xmin, b.xmin)
dy = min(a.ymax, b.ymax) - max(a.ymin, b.ymin)
return dx*dy
def detector():
global msg
msg = ''
cap = cv2.VideoCapture(filename)
with detectionGraph.as_default():
with tf.Session(graph=detectionGraph) as sess:
while True:
ret, image_np = cap.read()
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detectionGraph.get_tensor_by_name('image_tensor:0')
boxes = detectionGraph.get_tensor_by_name('detection_boxes:0')
scores = detectionGraph.get_tensor_by_name('detection_scores:0')
classes = detectionGraph.get_tensor_by_name('detection_classes:0')
num_detections = detectionGraph.get_tensor_by_name('num_detections:0')
(boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded})
calculateCollision(boxes, classes, scores, image_np)
cv2.putText(image_np, msg, (230, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('Accident Detection', image_np)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
def exit():
main.destroy()
font = ('times', 16, 'bold')
title = Label(main, text='Accident Detection')
title.config(bg='light cyan', fg='pale violet red')
title.config(font=font)
title.config(height=3, width=120)
title.place(x=0,y=5)
font1 = ('times', 13, 'bold')
uploadButton = Button(main, text="Load & Generate CNN Model", command=loadModel)
uploadButton.place(x=50,y=100)
uploadButton.config(font=font1)
pathlabel = Label(main)
pathlabel.config(bg='light cyan', fg='pale violet red')
pathlabel.config(font=font1)
pathlabel.place(x=460,y=100)
webcamButton = Button(main, text="Browse System Videos", command=uploadVideo)
webcamButton.place(x=50,y=150)
webcamButton.config(font=font1)
webcamButton = Button(main, text="Start Accident Detector", command=detector)
webcamButton.place(x=50,y=200)
webcamButton.config(font=font1)
exitButton = Button(main, text="Exit", command=exit)
exitButton.place(x=330,y=250)
exitButton.config(font=font1)
font1 = ('times', 12, 'bold')
text=Text(main,height=20,width=150)
scroll=Scrollbar(text)
text.configure(yscrollcommand=scroll.set)
text.place(x=10,y=250)
text.config(font=font1)
main.config(bg='snow3')
main.mainloop()