SlideShare a Scribd company logo
I have to understand this code and i have to explain the each line of code to my Project guide
Can you plz add comment to each line of code which would be helpful me to understand the
code
Code for Accident detection using CNN:
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
import numpy as np
import winsound
main = tkinter.Tk()
main.title("Accident Detection")
main.geometry("1300x1200")
net =
cv2.dnn.readNetFromCaffe("model/MobileNetSSD_deploy.prototxt.txt","model/MobileNetSSD
_deploy.caffemodel")
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
global filename
global detectionGraph
global msg
def loadModel():
global detectionGraph
detectionGraph = tf.Graph()
with detectionGraph.as_default():
od_graphDef = tf.compat.v1.GraphDef()
with tf.compat.v2.io.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+" loadedn");
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!'
beep()
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.compat.v1.Session(graph=detectionGraph) as sess:
while True:
ret, image_np = cap.read()
(h, w) = image_np.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image_np, (300, 300)),0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
for i in np.arange(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.2:
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
if (confidence * 100) > 50:
label = "{}: {:.2f}%".format(CLASSES[idx],confidence * 100)
cv2.rectangle(image_np, (startX, startY), (endX, endY),COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
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')
if image_np_expanded[0] is not None:
(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(5) & 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()
Ad

Recommended

PDF
What is the UML Class diagram for accident detection using CNN- i have.pdf
anilagarwal8880432
 
PDF
Computer vision
Dmitry Ryabokon
 
PDF
Golf Swing Analysis and Posture Correction System
Mamoon Ismail Khalid
 
PDF
PyTorch to detect Humans Eating Food.pdf
Mamoon Ismail Khalid
 
PPTX
Realtime pothole detection system using improved CNN Models
nithinsai2992
 
PPTX
YU CS Summer 2021 Project | TensorFlow Street Image Classification and Object...
JacobSilbiger1
 
PPTX
29-kashyap-mask-detaction.pptx
KASHYAPPATHAK7
 
PDF
AIML4 CNN lab256 1hr (111-1).pdf
ssuserb4d806
 
PDF
GANS Project for Image idetification.pdf
VivekanandaGN1
 
PDF
CE344L-200365-Lab5.pdf
UmarMustafa13
 
PPTX
Digit recognition Model.................
kaushikbehera98765
 
PPTX
From Tensorflow Graph to Tensorflow Eager
Guy Hadash
 
PDF
Can someone please explain what the code below is doing and comment on.pdf
kuldeepkumarapgsi
 
PDF
A Tour of Tensorflow's APIs
Dean Wyatte
 
PDF
Templateless Marked Element Recognition Using Computer Vision
shivam chaurasia
 
PDF
Chainer ui v0.3 and imagereport
Preferred Networks
 
PPTX
Real Time Object Dectection using machine learning
pratik pratyay
 
PPTX
Object detection with Tensorflow Api
ArwinKhan1
 
DOCX
Assignment-1-NF.docx
KhondokerAbuNaim
 
PPTX
Cv mini project (1)
Kadambini Indurkar
 
PPTX
Explanation on Tensorflow example -Deep mnist for expert
홍배 김
 
PDF
Computer vision lane line detection
Jonathan Mitchell
 
PDF
Detection of Dense, Overlapping, Geometric Objects
gerogepatton
 
PDF
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
gerogepatton
 
PDF
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
ijaia
 
PPTX
Object Detection with Tensorflow
ElifTech
 
PPTX
slide-171212080528.pptx
SharanrajK22MMT1003
 
PDF
Eye deep
sveitser
 
PDF
In c++ Polymorphism is one of the hallmarks of OOP languages- What are (1).pdf
shreeaadithyaacellso
 
PDF
In Chapter 4 of LS- there is a case of Zappos and it describes how Zap.pdf
shreeaadithyaacellso
 

More Related Content

Similar to I have to understand this code and i have to explain the each line of.pdf (20)

PDF
GANS Project for Image idetification.pdf
VivekanandaGN1
 
PDF
CE344L-200365-Lab5.pdf
UmarMustafa13
 
PPTX
Digit recognition Model.................
kaushikbehera98765
 
PPTX
From Tensorflow Graph to Tensorflow Eager
Guy Hadash
 
PDF
Can someone please explain what the code below is doing and comment on.pdf
kuldeepkumarapgsi
 
PDF
A Tour of Tensorflow's APIs
Dean Wyatte
 
PDF
Templateless Marked Element Recognition Using Computer Vision
shivam chaurasia
 
PDF
Chainer ui v0.3 and imagereport
Preferred Networks
 
PPTX
Real Time Object Dectection using machine learning
pratik pratyay
 
PPTX
Object detection with Tensorflow Api
ArwinKhan1
 
DOCX
Assignment-1-NF.docx
KhondokerAbuNaim
 
PPTX
Cv mini project (1)
Kadambini Indurkar
 
PPTX
Explanation on Tensorflow example -Deep mnist for expert
홍배 김
 
PDF
Computer vision lane line detection
Jonathan Mitchell
 
PDF
Detection of Dense, Overlapping, Geometric Objects
gerogepatton
 
PDF
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
gerogepatton
 
PDF
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
ijaia
 
PPTX
Object Detection with Tensorflow
ElifTech
 
PPTX
slide-171212080528.pptx
SharanrajK22MMT1003
 
PDF
Eye deep
sveitser
 
GANS Project for Image idetification.pdf
VivekanandaGN1
 
CE344L-200365-Lab5.pdf
UmarMustafa13
 
Digit recognition Model.................
kaushikbehera98765
 
From Tensorflow Graph to Tensorflow Eager
Guy Hadash
 
Can someone please explain what the code below is doing and comment on.pdf
kuldeepkumarapgsi
 
A Tour of Tensorflow's APIs
Dean Wyatte
 
Templateless Marked Element Recognition Using Computer Vision
shivam chaurasia
 
Chainer ui v0.3 and imagereport
Preferred Networks
 
Real Time Object Dectection using machine learning
pratik pratyay
 
Object detection with Tensorflow Api
ArwinKhan1
 
Assignment-1-NF.docx
KhondokerAbuNaim
 
Cv mini project (1)
Kadambini Indurkar
 
Explanation on Tensorflow example -Deep mnist for expert
홍배 김
 
Computer vision lane line detection
Jonathan Mitchell
 
Detection of Dense, Overlapping, Geometric Objects
gerogepatton
 
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
gerogepatton
 
DETECTION OF DENSE, OVERLAPPING, GEOMETRIC OBJECTS
ijaia
 
Object Detection with Tensorflow
ElifTech
 
slide-171212080528.pptx
SharanrajK22MMT1003
 
Eye deep
sveitser
 

More from shreeaadithyaacellso (20)

PDF
In c++ Polymorphism is one of the hallmarks of OOP languages- What are (1).pdf
shreeaadithyaacellso
 
PDF
In Chapter 4 of LS- there is a case of Zappos and it describes how Zap.pdf
shreeaadithyaacellso
 
PDF
In C++ Plz LAB- Playlist (output linked list) Given main()- complete.pdf
shreeaadithyaacellso
 
PDF
In C Programming- not C++ Write a function which takes two formal pa.pdf
shreeaadithyaacellso
 
PDF
In chapter 17 you learned about the big picture of circulation through.pdf
shreeaadithyaacellso
 
PDF
In cell M11- enter a formula that will calculate the total amount due.pdf
shreeaadithyaacellso
 
PDF
In C++ Plz and In What Order Do I Put It In- LAB- Playlist (output li.pdf
shreeaadithyaacellso
 
PDF
In C++ Complete the program with the bold requirements #include #i.pdf
shreeaadithyaacellso
 
PDF
I am studying for a test tomorrow in my 494 Population Biology class-.pdf
shreeaadithyaacellso
 
PDF
I got the codes written down below- Basically- I am trying to implemen.pdf
shreeaadithyaacellso
 
PDF
I am trying to write a program that will converts a 32bit float number.pdf
shreeaadithyaacellso
 
PDF
I am stuck on this question- please show the solution step by step- Re.pdf
shreeaadithyaacellso
 
PDF
I et X and Y he two indenendent R(3n-1-3) random variables- Calculate.pdf
shreeaadithyaacellso
 
PDF
I am working on a coding project- and it asked me to combine five sets.pdf
shreeaadithyaacellso
 
PDF
I am needing to do a Point Factor Job Evaluation for a IT Company whos.pdf
shreeaadithyaacellso
 
PDF
i cant figure out this excel equation For the Year Ended December 31-.pdf
shreeaadithyaacellso
 
PDF
I am writing a program that will allow the user to move the crosshairs.pdf
shreeaadithyaacellso
 
PDF
I need simple java code for the below scenario- UML Diagrams(Class-Use.pdf
shreeaadithyaacellso
 
PDF
I need hlep I have posted this proble 4 times have gotten no help can.pdf
shreeaadithyaacellso
 
PDF
I need question 1 answer in java language- question 1)Create an applic.pdf
shreeaadithyaacellso
 
In c++ Polymorphism is one of the hallmarks of OOP languages- What are (1).pdf
shreeaadithyaacellso
 
In Chapter 4 of LS- there is a case of Zappos and it describes how Zap.pdf
shreeaadithyaacellso
 
In C++ Plz LAB- Playlist (output linked list) Given main()- complete.pdf
shreeaadithyaacellso
 
In C Programming- not C++ Write a function which takes two formal pa.pdf
shreeaadithyaacellso
 
In chapter 17 you learned about the big picture of circulation through.pdf
shreeaadithyaacellso
 
In cell M11- enter a formula that will calculate the total amount due.pdf
shreeaadithyaacellso
 
In C++ Plz and In What Order Do I Put It In- LAB- Playlist (output li.pdf
shreeaadithyaacellso
 
In C++ Complete the program with the bold requirements #include #i.pdf
shreeaadithyaacellso
 
I am studying for a test tomorrow in my 494 Population Biology class-.pdf
shreeaadithyaacellso
 
I got the codes written down below- Basically- I am trying to implemen.pdf
shreeaadithyaacellso
 
I am trying to write a program that will converts a 32bit float number.pdf
shreeaadithyaacellso
 
I am stuck on this question- please show the solution step by step- Re.pdf
shreeaadithyaacellso
 
I et X and Y he two indenendent R(3n-1-3) random variables- Calculate.pdf
shreeaadithyaacellso
 
I am working on a coding project- and it asked me to combine five sets.pdf
shreeaadithyaacellso
 
I am needing to do a Point Factor Job Evaluation for a IT Company whos.pdf
shreeaadithyaacellso
 
i cant figure out this excel equation For the Year Ended December 31-.pdf
shreeaadithyaacellso
 
I am writing a program that will allow the user to move the crosshairs.pdf
shreeaadithyaacellso
 
I need simple java code for the below scenario- UML Diagrams(Class-Use.pdf
shreeaadithyaacellso
 
I need hlep I have posted this proble 4 times have gotten no help can.pdf
shreeaadithyaacellso
 
I need question 1 answer in java language- question 1)Create an applic.pdf
shreeaadithyaacellso
 
Ad

Recently uploaded (20)

PDF
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
PPTX
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
PPTX
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
PPTX
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
PPTX
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
PPTX
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
 
PPTX
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
PPTX
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
PDF
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
PDF
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
PPTX
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
PPTX
How to Add New Item in CogMenu in Odoo 18
Celine George
 
PPTX
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
PPT
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
PPTX
List View Components in Odoo 18 - Odoo Slides
Celine George
 
PPTX
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
PPTX
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
How to Add New Item in CogMenu in Odoo 18
Celine George
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
List View Components in Odoo 18 - Odoo Slides
Celine George
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Ad

I have to understand this code and i have to explain the each line of.pdf

  • 1. I have to understand this code and i have to explain the each line of code to my Project guide Can you plz add comment to each line of code which would be helpful me to understand the code Code for Accident detection using CNN: 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 import numpy as np import winsound main = tkinter.Tk() main.title("Accident Detection") main.geometry("1300x1200") net = cv2.dnn.readNetFromCaffe("model/MobileNetSSD_deploy.prototxt.txt","model/MobileNetSSD _deploy.caffemodel") CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  • 2. "sofa", "train", "tvmonitor"] COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) global filename global detectionGraph global msg def loadModel(): global detectionGraph detectionGraph = tf.Graph() with detectionGraph.as_default(): od_graphDef = tf.compat.v1.GraphDef() with tf.compat.v2.io.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)
  • 3. text.delete('1.0', END) text.insert(END,filename+" loadedn"); 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!' beep() return True else: return False
  • 4. 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.compat.v1.Session(graph=detectionGraph) as sess: while True: ret, image_np = cap.read() (h, w) = image_np.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(image_np, (300, 300)),0.007843, (300, 300), 127.5) net.setInput(blob) detections = net.forward()
  • 5. for i in np.arange(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.2: idx = int(detections[0, 0, i, 1]) box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") if (confidence * 100) > 50: label = "{}: {:.2f}%".format(CLASSES[idx],confidence * 100) cv2.rectangle(image_np, (startX, startY), (endX, endY),COLORS[idx], 2) y = startY - 15 if startY - 15 > 15 else startY + 15 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') if image_np_expanded[0] is not None: (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(5) & 0xFF == ord('q'):
  • 6. 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)
  • 7. 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()