Untitled
unknown
plain_text
3 years ago
13 kB
7
Indexable
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
import cv2
import dlib
import time
import threading
import math
import xlsxwriter
from datetime import datetime
import os
import shutil
from zipfile import ZipFile
from tkinter import *
from PIL import ImageTk, Image
import tkinter
from tkinter import *
from PIL import Image, ImageTk
# Create a workbook and add a worksheet.
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.configure(background="#A2A2CD")
app = Application()
app.geometry("1300x600")
image1 = Image.open("police.png")
image1 = image1.resize((1100, 450), Image.ANTIALIAS)
test = ImageTk.PhotoImage(image1)
my_label = Label(app,image=test)
my_label.place(x=0,y=0, relwidth=1,relheight=1)
app.title("Smart Traffic Admin Panel")
WIDTH = 640
HEIGHT = 480
def overspeeding():
file = "sss.mp3"
os.system(file)
os.remove(file)
speedlimit = 100
def startproject(inputfilename):
carCascade = cv2.CascadeClassifier('myhaar.xml')
video = cv2.VideoCapture(inputfilename)
global WIDTH
global HEIGHT
global speedlimit
def estimateSpeed(location1, location2):
d_pixels = math.sqrt(math.pow(location2[0] - location1[0], 2) + math.pow(location2[1] - location1[1], 2))
# ppm = location2[2] / carWidht
ppm = 8.8
d_meters = d_pixels / ppm
#print("d_pixels=" + str(d_pixels), "d_meters=" + str(d_meters))
fps = 18
speed = d_meters * fps * 3.6
return speed
def trackMultipleObjects():
rectangleColor = (0, 255, 0)
frameCounter = 0
currentCarID = 0
fps = 0
carTracker = {}
carNumbers = {}
carLocation1 = {}
carLocation2 = {}
speed = [None] * 1000
# Write output to video file
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (WIDTH,HEIGHT))
now = datetime.now()
workbook = xlsxwriter.Workbook('Stats.xlsx')
worksheet = workbook.add_worksheet()
row = 0
column = 0
worksheet.write(row, column, "Car ID")
worksheet.write(row, column+1, "Status")
worksheet.write(row, column+2, "Speed")
worksheet.write(row, column+3, "Date and time")
worksheet.write(row, column+4, "Car Type")
row+=1
while True:
start_time = time.time()
rc, image = video.read()
if type(image) == type(None):
break
image = cv2.resize(image, (WIDTH, HEIGHT))
resultImage = image.copy()
frameCounter = frameCounter + 1
carIDtoDelete = []
for carID in carTracker.keys():
trackingQuality = carTracker[carID].update(image)
if trackingQuality < 7:
carIDtoDelete.append(carID)
for carID in carIDtoDelete:
print ('Removing carID ' + str(carID) + ' from list of trackers.')
print ('Removing carID ' + str(carID) + ' previous location.')
print ('Removing carID ' + str(carID) + ' current location.')
carTracker.pop(carID, None)
carLocation1.pop(carID, None)
carLocation2.pop(carID, None)
if not (frameCounter % 10):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cars = carCascade.detectMultiScale(gray, 1.1, 13, 18, (24, 24))
for (_x, _y, _w, _h) in cars:
x = int(_x)
y = int(_y)
w = int(_w)
h = int(_h)
x_bar = x + 0.5 * w
y_bar = y + 0.5 * h
matchCarID = None
for carID in carTracker.keys():
trackedPosition = carTracker[carID].get_position()
t_x = int(trackedPosition.left())
t_y = int(trackedPosition.top())
t_w = int(trackedPosition.width())
t_h = int(trackedPosition.height())
t_x_bar = t_x + 0.5 * t_w
t_y_bar = t_y + 0.5 * t_h
if ((t_x <= x_bar <= (t_x + t_w)) and (t_y <= y_bar <= (t_y + t_h)) and (x <= t_x_bar <= (x + w)) and (y <= t_y_bar <= (y + h))):
matchCarID = carID
if matchCarID is None:
print ('Creating new tracker ' + str(currentCarID))
tracker = dlib.correlation_tracker()
tracker.start_track(image, dlib.rectangle(x, y, x + w, y + h))
carTracker[currentCarID] = tracker
carLocation1[currentCarID] = [x, y, w, h]
currentCarID = currentCarID + 1
#cv2.line(resultImage,(0,480),(1280,480),(255,0,0),5)
for carID in carTracker.keys():
trackedPosition = carTracker[carID].get_position()
t_x = int(trackedPosition.left())
t_y = int(trackedPosition.top())
t_w = int(trackedPosition.width())
t_h = int(trackedPosition.height())
cv2.rectangle(resultImage, (t_x, t_y), (t_x + t_w, t_y + t_h), rectangleColor, 4)
# speed estimation
carLocation2[carID] = [t_x, t_y, t_w, t_h]
end_time = time.time()
if not (end_time == start_time):
fps = 1.0/(end_time - start_time)
#cv2.putText(resultImage, 'FPS: ' + str(int(fps)), (620, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
for i in carLocation1.keys():
if frameCounter % 1 == 0:
[x1, y1, w1, h1] = carLocation1[i]
[x2, y2, w2, h2] = carLocation2[i]
# print 'previous location: ' + str(carLocation1[i]) + ', current location: ' + str(carLocation2[i])
carLocation1[i] = [x2, y2, w2, h2]
# print 'new previous location: ' + str(carLocation1[i])
if [x1, y1, w1, h1] != [x2, y2, w2, h2]:
if (speed[i] == None or speed[i] == 0) and y1 >= 275 and y1 <= 285:
speed[i] = estimateSpeed([x1, y1, w1, h1], [x2, y2, w2, h2])
#if y1 > 275 and y1 < 285:
if speed[i] != None and y1 >= 180:
if int(speed[i])>speedlimit:
cv2.putText(resultImage, str(int(speed[i])) + f" km/hr", (int(x1 + w1/2), int(y1-5)),cv2.FONT_HERSHEY_SIMPLEX, 0.75, (49, 49, 232), 2)
cv2.putText(resultImage, f"CAR ID {currentCarID} Status : OVERSPEEDING", (int(x1 + w1/4), int(y1-50)),cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
worksheet.write(row, column, f"{currentCarID}")
worksheet.write(row, column+1, "OverSpeeding")
worksheet.write(row, column+2, str(int(speed[i]))+" Km/h")
worksheet.write(row, column+3, f"{dt_string}")
worksheet.write(row, column+4, "Sedan")
row+=1
try:
overspeeding()
except:
a = 1
else:
cv2.putText(resultImage, str(int(speed[i])) + " km/hr", (int(x1 + w1/2), int(y1-5)),cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
cv2.putText(resultImage, f"CAR ID {currentCarID} Status : Normal", (int(x1 + w1/4), int(y1-50)),cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
#print ('CarID ' + str(i) + ': speed is ' + str("%.2f" % round(speed[i], 0)) + ' km/h.\n')
#else:
# cv2.putText(resultImage, "Far Object", (int(x1 + w1/2), int(y1)),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
#print ('CarID ' + str(i) + ' Location1: ' + str(carLocation1[i]) + ' Location2: ' + str(carLocation2[i]) + ' speed is ' + str("%.2f" % round(speed[i], 0)) + ' km/h.\n')
cv2.imshow('result', resultImage)
# Write the frame into the file 'output.avi'
#out.write(resultImage)
if cv2.waitKey(33) == 27:
break
cv2.destroyAllWindows()
workbook.close()
with ZipFile("temp.zip", 'r') as zObject:
zObject.extractall()
if __name__ == '__main__':
trackMultipleObjects()
# image1 = Image.open("zwz.png")
# image1 = image1.resize((300, 300), Image.ANTIALIAS)
# test = ImageTk.PhotoImage(image1)
# label1 = tk.Label(image=test)
# label1.image = test
# # Position image
# label1.place(x=10, y=10)
def setresolution(x,y):
global WIDTH
global HEIGHT
WIDTH = x
HEIGHT = y
showinfo(
title='Screen size updated',
message=f"Screen Size updated to {x} X {y}"
)
def updarespeedlimit():
global entry
userspeedlimit = entry.get()
speedlimit = int(userspeedlimit)
showinfo(
title='Speed Limit updated',
message=f"New speed limit was set to {speedlimit} KM/H"
)
#Initialize a Label to display the User Input
label=Label(app, text="", font=("Courier 22 bold"))
label.pack()
#Create an Entry widget to accept User Input
entry= Entry(app, width= 20)
entry.focus_set()
entry.place(x=560,y=440)
#Create a Button to validate Entry Widget
setspeed = tk.Button(app, text= "Set Speed Limit",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 18, 'bold'),width= 16, command= updarespeedlimit)
setspeed.place(x=500,y=491)
setwindowhighquality = tk.Button(app, text= "1280",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 21, 'bold'),width= 8, command= lambda: setresolution(1280,720))
setwindowhighquality.place(x=160,y=191)
setwindowhighquality = tk.Button(app, text= "720",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 21, 'bold'),width= 8, command= lambda: setresolution(720,480))
setwindowhighquality.place(x=320,y=191)
setwindowhighquality = tk.Button(app, text= "560",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 21, 'bold'),width= 8, command= lambda: setresolution(576,360))
setwindowhighquality.place(x=160,y=290)
setwindowhighquality = tk.Button(app, text= "480",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 21, 'bold'),width= 8, command= lambda: setresolution(480,240))
setwindowhighquality.place(x=320,y=290)
def saverecs():
showinfo(
title='Record Files Saved',
message="Speeding Files saved to stats.xlsx"
)
SaveRecords = tk.Button(app, text= "Save Speeding Records",background="#0000B2",font=('Articulat CF Extra Bold Oblique', 21, 'bold'),width= 20, command= saverecs)
SaveRecords.place(x=140,y=360)
ProjectTitle = tk.Label(text='ADMIN PANEL',background="#0000B2", font=('Articulat CF Extra Bold Oblique', 25, 'bold'))
ProjectTitle.place(x=730,y=32)
Projectname = tk.Label(text='AI SMART TRAFFIC MONITORING',background="#0000B2", font=('Articulat CF Extra Bold Oblique', 18, 'bold'))
Projectname.place(x=640,y=110)
setwindowsizelabel = tk.Label(text='Set Operation size',background="#0000B2", font=('Articulat CF Extra Bold Oblique', 18, 'bold'))
setwindowsizelabel.place(x=210,y=110)
def select_file():
filetypes = (
('text files', '*.mp4'),
('All files', '*.*')
)
filename = fd.askopenfilename(
title='Open a file',
initialdir='/',
filetypes=filetypes)
print(filename)
showinfo(
title='Selected File',
message=filename
)
startproject(filename)
# open button
startimage = Image.open("start.png")
startimage = startimage.resize((300, 100), Image.ANTIALIAS)
sratbut = ImageTk.PhotoImage(startimage)
b4=tk.Button(app,command=select_file,image=sratbut,bd=0,bg='#0000B2',activebackground='#000064')
b4.place(x=800,y=440)
app.mainloop()Editor is loading...