SlideShare a Scribd company logo
1 of 7
Download to read offline
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()

More Related Content

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

Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Tae wook kang
 
Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxLukeQVdGrantg
 
Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Alamgir Hossain
 
DeepLearning ハンズオン資料 20161220
DeepLearning ハンズオン資料 20161220DeepLearning ハンズオン資料 20161220
DeepLearning ハンズオン資料 20161220Mutsuyuki Tanaka
 
Font classification with 5 deep learning models using tensor flow
Font classification with 5 deep learning models using tensor flowFont classification with 5 deep learning models using tensor flow
Font classification with 5 deep learning models using tensor flowDevatanu Banerjee
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Thomas Fan
 
6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demoNAP Events
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdfsrxerox
 
Gaussian Image Blurring in CUDA C++
Gaussian Image Blurring in CUDA C++Gaussian Image Blurring in CUDA C++
Gaussian Image Blurring in CUDA C++Darshan Parsana
 
Hybrid quantum classical neural networks with pytorch and qiskit
Hybrid quantum classical neural networks with pytorch and qiskitHybrid quantum classical neural networks with pytorch and qiskit
Hybrid quantum classical neural networks with pytorch and qiskitVijayananda Mohire
 
Hangman Code.pdf
Hangman Code.pdfHangman Code.pdf
Hangman Code.pdfkyakarega1
 
This face recognition attendance system code for face recogn.pdf
This face recognition attendance system code for face recogn.pdfThis face recognition attendance system code for face recogn.pdf
This face recognition attendance system code for face recogn.pdfadislifestyle
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfarcotstarsports
 
Program implementation and testing
Program implementation and testingProgram implementation and testing
Program implementation and testingabukky52
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
 
Deep learning with C++ - an introduction to tiny-dnn
Deep learning with C++  - an introduction to tiny-dnnDeep learning with C++  - an introduction to tiny-dnn
Deep learning with C++ - an introduction to tiny-dnnTaiga Nomi
 
Import java
Import javaImport java
Import javaheni2121
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxlauracallander
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
 

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

Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화
 
Python program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docxPython program to build deep learning algorithm using a CNNs model to.docx
Python program to build deep learning algorithm using a CNNs model to.docx
 
Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report
 
DeepLearning ハンズオン資料 20161220
DeepLearning ハンズオン資料 20161220DeepLearning ハンズオン資料 20161220
DeepLearning ハンズオン資料 20161220
 
Font classification with 5 deep learning models using tensor flow
Font classification with 5 deep learning models using tensor flowFont classification with 5 deep learning models using tensor flow
Font classification with 5 deep learning models using tensor flow
 
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
Pydata DC 2018 (Skorch - A Union of Scikit-learn and PyTorch)
 
6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo6.3.2 CLIMADA model demo
6.3.2 CLIMADA model demo
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdf
 
Gaussian Image Blurring in CUDA C++
Gaussian Image Blurring in CUDA C++Gaussian Image Blurring in CUDA C++
Gaussian Image Blurring in CUDA C++
 
Hybrid quantum classical neural networks with pytorch and qiskit
Hybrid quantum classical neural networks with pytorch and qiskitHybrid quantum classical neural networks with pytorch and qiskit
Hybrid quantum classical neural networks with pytorch and qiskit
 
Hangman Code.pdf
Hangman Code.pdfHangman Code.pdf
Hangman Code.pdf
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
This face recognition attendance system code for face recogn.pdf
This face recognition attendance system code for face recogn.pdfThis face recognition attendance system code for face recogn.pdf
This face recognition attendance system code for face recogn.pdf
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdf
 
Program implementation and testing
Program implementation and testingProgram implementation and testing
Program implementation and testing
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
 
Deep learning with C++ - an introduction to tiny-dnn
Deep learning with C++  - an introduction to tiny-dnnDeep learning with C++  - an introduction to tiny-dnn
Deep learning with C++ - an introduction to tiny-dnn
 
Import java
Import javaImport java
Import java
 
Need help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docxNeed help filling out the missing sections of this code- the sections.docx
Need help filling out the missing sections of this code- the sections.docx
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 

More from shreeaadithyaacellso

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

More from shreeaadithyaacellso (20)

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

Recently uploaded

How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxCeline George
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MysoreMuleSoftMeetup
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptxVishal Singh
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfJerry Chew
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 

Recently uploaded (20)

How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 

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()