imaneralo commited on
Commit
7b920eb
1 Parent(s): 0340462

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -273
app.py CHANGED
@@ -1,273 +1,88 @@
1
- # import numpy as np
2
- # from ultralytics import YOLO
3
- # import cv2
4
- # import cvzone
5
- # import math
6
- # from sort import *
7
- # import datetime
8
- # import geocoder
9
-
10
- # #i want to take co ordinates in lat long of this device
11
- # # def get_coordinates():
12
- # # g = geocoder.ip('me')
13
- # # if g.latlng:
14
- # # return {'lat': str(g.latlng[0]), 'long': str(g.latlng[1])}
15
- # # else:
16
- # # return None
17
-
18
- # # currentCoordinates = get_coordinates()
19
- # # if currentCoordinates:
20
- # # print(currentCoordinates)
21
- # # else:
22
- # # print("Unable to get device coordinates.")
23
-
24
- # #calculate distance b/w two coordinates
25
- # def distance_calculations(stationFromCoordinates, stationToCoordinates):
26
- # stationFromCoordinates = {'lat': ' 28.98', 'long': '77.7064'}
27
- # stationToCoordinates = {'lat': '28.66', 'long': '77.22'}
28
- # lat1 = float(stationFromCoordinates['lat'])
29
- # lon1 = float(stationFromCoordinates['long'])
30
- # lat2 = float(stationToCoordinates['lat'])
31
- # lon2 = float(stationToCoordinates['long'])
32
- # R = 6371
33
- # dlat = math.radians(lat2 - lat1)
34
- # dlon = math.radians(lon2 - lon1)
35
- # a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)
36
- # c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
37
- # distance = R * c
38
- # return distance
39
- # print(distance_calculations({'lat': ' 28.98', 'long': '77.7'}, {'lat': '28.66', 'long': '77.22'}))
40
- # totalFare=0
41
- # pricePerKm=1.5
42
-
43
-
44
- # def distanceCalculations(inBetweenDepaturePoints,inBetweenOnBoardingPoints):
45
- # print(inBetweenDepaturePoints,inBetweenOnBoardingPoints ,'inbetween points')
46
-
47
- # return 3
48
-
49
- # def fareCalculations():
50
- # global totalFare
51
- # print(dict)
52
- # index=0
53
- # for i in dict.values():
54
- # print(len(i))
55
- # inBetweenDepaturePoints=[]
56
- # inBetweenOnBoardingPoints=[]
57
- # if(len(i)>3):
58
- # print(True)
59
- # #index of the dict
60
- # print(index,"index")
61
- # print(i[0],i[1],i[2],"values of the dict","key of the dict")
62
-
63
- # if i[0]==True and i[1]==False:
64
- # inBetweenDepaturePoints.append(i[2])
65
- # if i[0]==False and i[1]==True:
66
- # inBetweenOnBoardingPoints.append(i[2])
67
- # fare=distanceCalculations(inBetweenDepaturePoints,inBetweenOnBoardingPoints)*pricePerKm
68
- # print(fare,'fare')
69
- # totalFare+=fare
70
- # index+=1
71
-
72
- # print(totalFare)
73
- # cap = cv2.VideoCapture('./TrialFootage.mp4')
74
-
75
- # model = YOLO("./Yolo-Weights/yolov8n.pt")
76
- # stationFrom='Meerut'
77
- # stationFromCoordinates={"lat":"12.12.54.4","long":"44.36.09"} # Meerut
78
- # stationToCoordinates={'lat':'54.45.56',"long":'45.45.45'}
79
- # currentCoordinates={'lat': '28.98', 'long': '77.7064'}
80
- # stationTo='Delhi'
81
- # reachedDestination=False
82
-
83
-
84
-
85
-
86
- # ListPeople = []
87
- # dict = {}
88
- # width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
89
- # height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
90
- # print(f"Video Resolution: {width}x{height}")
91
- # classNames = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat",
92
- # "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
93
- # "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella",
94
- # "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat",
95
- # "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup",
96
- # "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli",
97
- # "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed",
98
- # "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone",
99
- # "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors",
100
- # "teddy bear", "hair drier", "toothbrush"
101
- # ]
102
-
103
- # # Tracking
104
-
105
- # tracker = Sort(max_age=20, min_hits=3, iou_threshold=0.3)
106
-
107
- # yelloLine = [270, 0, 270, 600]
108
-
109
- # RedLine = [173, 0, 173, 600]
110
-
111
- # totalCountUp = []
112
- # #mask=cv2.imread('mask.jpg')
113
- # entry_count = 0
114
- # while True:
115
-
116
-
117
-
118
- # success, img = cap.read()
119
- # # imgRegion=cv2.bitwise_and(img,mask)
120
-
121
- # results = model(img, stream=True)
122
-
123
- # detections = np.empty((0, 5))
124
-
125
- # for r in results:
126
- # boxes = r.boxes
127
- # for box in boxes:
128
- # # Bounding Box
129
- # x1, y1, x2, y2 = box.xyxy[0]
130
- # x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
131
- # # cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,255),3)
132
- # w, h = x2 - x1, y2 - y1
133
-
134
- # # Confidence
135
- # conf = math.ceil((box.conf[0] * 100)) / 100
136
- # # Class Name
137
- # cls = int(box.cls[0])
138
- # currentClass = classNames[cls]
139
-
140
- # if currentClass == "person" and conf > 0.3:
141
- # # cvzone.putTextRect(img, f'{currentClass} {conf}', (max(0, x1), max(35, y1)),
142
- # # scale=0.6, thickness=1, offset=3)
143
- # # cvzone.cornerRect(img, (x1, y1, w, h), l=9, rt=5)
144
- # currentArray = np.array([x1, y1, x2, y2, conf])
145
- # detections = np.vstack((detections, currentArray))
146
-
147
- # resultsTracker = tracker.update(detections)
148
-
149
- # cv2.line(img, (yelloLine[0], yelloLine[1]), (yelloLine[2], yelloLine[3]), (0, 0, 255), 5)
150
- # cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
151
- # for result in resultsTracker:
152
- # x1, y1, x2, y2, id = result
153
- # x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
154
- # print(result)
155
- # w, h = x2 - x1, y2 - y1
156
- # cvzone.cornerRect(img, (x1, y1, w, h), l=9, rt=2, colorR=(255, 0, 255))
157
- # cvzone.putTextRect(img, f' {int(id)}', (max(0, x1), max(35, y1)),
158
- # scale=2, thickness=3, offset=10)
159
-
160
- # cx, cy = x1 + w // 2, y1 + h // 2
161
- # cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)
162
-
163
- # if yelloLine[0] - 20 < cx < yelloLine[2] + 20:
164
- # if totalCountUp.count(id) == 0:
165
- # totalCountUp.append(id)
166
- # dict[id] = [False]
167
- # cv2.line(img, (yelloLine[0], yelloLine[1]), (yelloLine[2], yelloLine[3]), (0, 0, 255), 5)
168
- # elif totalCountUp.count(id) == 1:
169
- # if (dict[id].count(False) < 1):
170
- # dict[id].append(False)
171
- # cv2.line(img, (yelloLine[0], yelloLine[1]), (yelloLine[2], yelloLine[3]), (0, 0, 255), 5)
172
- # if RedLine[0] - 20 < cx < RedLine[2] + 30:
173
- # if totalCountUp.count(id) == 0:
174
- # totalCountUp.append(id)
175
- # dict[id] = [True]
176
- # dict[id].append(currentCoordinates)
177
- # #adding timestamp
178
- # current_time = datetime.datetime.now()
179
- # dict[id].append(current_time)
180
- # cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
181
- # elif totalCountUp.count(id) == 1:
182
- # if (dict[id].count(True) < 1):
183
- # dict[id].append(True)
184
- # dict[id].append(currentCoordinates)
185
- # #adding timestamp
186
- # current_time = datetime.datetime.now()
187
- # dict[id].append(current_time)
188
-
189
- # cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
190
-
191
- # print(totalCountUp)
192
- # entry_count=0
193
-
194
- # for i in dict.values():
195
- # if (len(i) >= 2):
196
- # if i[0] == True and i[1] == False:
197
- # print('in true/False')
198
- # if entry_count > 0:
199
- # entry_count -= 1
200
-
201
- # if i[0] == False and i[1] == True:
202
- # print('in /False/True')
203
- # entry_count += 1
204
-
205
-
206
-
207
- # # print('count is ', entry_count)
208
- # # print(dict)
209
-
210
-
211
- # cv2.putText(img, str(entry_count), (110, 245), cv2.FONT_HERSHEY_PLAIN, 5, (50, 50, 230), 7)
212
- # print('count is ', entry_count)
213
- # print(dict)
214
- # cv2.imshow("Image", img)
215
- # cv2.waitKey(1)
216
- # print(entry_count)
217
-
218
- # # if currentCoordinates==stationToCoordinates:
219
- # # reachedDestination=True
220
- # # fareCalculations()
221
- # # dict=[]
222
- # # break
223
- # if entry_count>2:
224
- # print('reached destination')
225
- # fareCalculations()
226
- # break
227
-
228
  import numpy as np
229
  from ultralytics import YOLO
230
  import cv2
231
  import cvzone
232
  import math
233
  from sort import *
234
-
235
-
236
-
237
- # MongoDB connection URI with a default database (replace with your actual values)
238
-
239
- # def connectMongo() -> pymongo.database.Database:
240
- # try:
241
-
242
-
243
- # try:
244
-
245
- # client = pymongo.MongoClient('mongodb+srv://INFINIX:INFINIX@cluster0.rubyoda.mongodb.net/?retryWrites=true&w=majority')
246
- # db = client["INFINIX"]
247
- # print(db)
248
- # if db != None:
249
- # print("connected to db")
250
- # return db
251
- # except Exception as e:
252
- # print(e)
253
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
- # except Exception as e:
256
- # return "Error in Connecting to MongoDB" + str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- # db=connectMongo()
 
 
 
 
 
 
 
 
 
259
 
260
- # collection=db['BUS_DETS']
261
 
262
- # Create a collection to store entry count
263
- # entry_count_collection = db.entry_count
264
 
265
- cap = cv2.VideoCapture('./trialFootage.mp4')
266
 
267
- model = YOLO("../Yolo-Weights/yolov8n.pt")
268
- occupancy = 0
269
- coming = 0
270
- goin = 0
271
  ListPeople = []
272
  dict = {}
273
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
@@ -295,9 +110,10 @@ RedLine = [173, 0, 173, 600]
295
 
296
  totalCountUp = []
297
  #mask=cv2.imread('mask.jpg')
298
-
299
  while True:
300
 
 
301
 
302
  success, img = cap.read()
303
  # imgRegion=cv2.bitwise_and(img,mask)
@@ -330,7 +146,8 @@ while True:
330
 
331
  resultsTracker = tracker.update(detections)
332
 
333
-
 
334
  for result in resultsTracker:
335
  x1, y1, x2, y2, id = result
336
  x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
@@ -356,38 +173,59 @@ while True:
356
  if totalCountUp.count(id) == 0:
357
  totalCountUp.append(id)
358
  dict[id] = [True]
 
 
 
 
359
  cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
360
  elif totalCountUp.count(id) == 1:
361
  if (dict[id].count(True) < 1):
362
  dict[id].append(True)
 
 
 
 
 
363
  cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
364
 
365
  print(totalCountUp)
366
- entry_count = 0
367
 
368
  for i in dict.values():
369
- if (len(i) == 2):
370
  if i[0] == True and i[1] == False:
 
371
  if entry_count > 0:
372
  entry_count -= 1
 
373
  if i[0] == False and i[1] == True:
 
374
  entry_count += 1
 
375
 
376
 
377
- print('count is ', entry_count)
378
- print(dict)
379
- # # Update the MongoDB collection with the current count
380
- # entry_count_collection.update_one({}, {"$set": {"count":entry_count}}, upsert=True)
381
- # collection.update_one({"id": "your_document_id"}, {"$set": {"entry_count": entry_count}})
382
 
383
  cv2.putText(img, str(entry_count), (110, 245), cv2.FONT_HERSHEY_PLAIN, 5, (50, 50, 230), 7)
384
  print('count is ', entry_count)
385
  print(dict)
386
- #cv2.imshow("Image", img)
387
- #cv2.waitKey(1)
388
  print(entry_count)
389
- # collection.update_one({"id":"826587"},
390
- # {"$set": {
391
- # "entry_count":entry_count,
392
- # }})
 
 
 
 
 
 
 
 
 
 
393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import numpy as np
2
  from ultralytics import YOLO
3
  import cv2
4
  import cvzone
5
  import math
6
  from sort import *
7
+ import datetime
8
+ import geocoder
9
+
10
+ #i want to take co ordinates in lat long of this device
11
+ # def get_coordinates():
12
+ # g = geocoder.ip('me')
13
+ # if g.latlng:
14
+ # return {'lat': str(g.latlng[0]), 'long': str(g.latlng[1])}
15
+ # else:
16
+ # return None
17
+
18
+ # currentCoordinates = get_coordinates()
19
+ # if currentCoordinates:
20
+ # print(currentCoordinates)
21
+ # else:
22
+ # print("Unable to get device coordinates.")
23
+
24
+ #calculate distance b/w two coordinates
25
+ def distance_calculations(stationFromCoordinates, stationToCoordinates):
26
+ stationFromCoordinates = {'lat': ' 28.98', 'long': '77.7064'}
27
+ stationToCoordinates = {'lat': '28.66', 'long': '77.22'}
28
+ lat1 = float(stationFromCoordinates['lat'])
29
+ lon1 = float(stationFromCoordinates['long'])
30
+ lat2 = float(stationToCoordinates['lat'])
31
+ lon2 = float(stationToCoordinates['long'])
32
+ R = 6371
33
+ dlat = math.radians(lat2 - lat1)
34
+ dlon = math.radians(lon2 - lon1)
35
+ a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)
36
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
37
+ distance = R * c
38
+ return distance
39
+ print(distance_calculations({'lat': ' 28.98', 'long': '77.7'}, {'lat': '28.66', 'long': '77.22'}))
40
+ totalFare=0
41
+ pricePerKm=1.5
42
+
43
+
44
+ def distanceCalculations(inBetweenDepaturePoints,inBetweenOnBoardingPoints):
45
+ print(inBetweenDepaturePoints,inBetweenOnBoardingPoints ,'inbetween points')
46
+
47
+ return 3
48
 
49
+ def fareCalculations():
50
+ global totalFare
51
+ print(dict)
52
+ index=0
53
+ for i in dict.values():
54
+ print(len(i))
55
+ inBetweenDepaturePoints=[]
56
+ inBetweenOnBoardingPoints=[]
57
+ if(len(i)>3):
58
+ print(True)
59
+ #index of the dict
60
+ print(index,"index")
61
+ print(i[0],i[1],i[2],"values of the dict","key of the dict")
62
+
63
+ if i[0]==True and i[1]==False:
64
+ inBetweenDepaturePoints.append(i[2])
65
+ if i[0]==False and i[1]==True:
66
+ inBetweenOnBoardingPoints.append(i[2])
67
+ fare=distanceCalculations(inBetweenDepaturePoints,inBetweenOnBoardingPoints)*pricePerKm
68
+ print(fare,'fare')
69
+ totalFare+=fare
70
+ index+=1
71
 
72
+ print(totalFare)
73
+ cap = cv2.VideoCapture('./trialFootage.mp4')
74
+
75
+ model = YOLO("../Yolo-Weights/yolov8n.pt")
76
+ stationFrom='Meerut'
77
+ stationFromCoordinates={"lat":"12.12.54.4","long":"44.36.09"} # Meerut
78
+ stationToCoordinates={'lat':'54.45.56',"long":'45.45.45'}
79
+ currentCoordinates={'lat': '28.98', 'long': '77.7064'}
80
+ stationTo='Delhi'
81
+ reachedDestination=False
82
 
 
83
 
 
 
84
 
 
85
 
 
 
 
 
86
  ListPeople = []
87
  dict = {}
88
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
 
110
 
111
  totalCountUp = []
112
  #mask=cv2.imread('mask.jpg')
113
+ entry_count = 0
114
  while True:
115
 
116
+
117
 
118
  success, img = cap.read()
119
  # imgRegion=cv2.bitwise_and(img,mask)
 
146
 
147
  resultsTracker = tracker.update(detections)
148
 
149
+ cv2.line(img, (yelloLine[0], yelloLine[1]), (yelloLine[2], yelloLine[3]), (0, 0, 255), 5)
150
+ cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
151
  for result in resultsTracker:
152
  x1, y1, x2, y2, id = result
153
  x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
 
173
  if totalCountUp.count(id) == 0:
174
  totalCountUp.append(id)
175
  dict[id] = [True]
176
+ dict[id].append(currentCoordinates)
177
+ #adding timestamp
178
+ current_time = datetime.datetime.now()
179
+ dict[id].append(current_time)
180
  cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
181
  elif totalCountUp.count(id) == 1:
182
  if (dict[id].count(True) < 1):
183
  dict[id].append(True)
184
+ dict[id].append(currentCoordinates)
185
+ #adding timestamp
186
+ current_time = datetime.datetime.now()
187
+ dict[id].append(current_time)
188
+
189
  cv2.line(img, (RedLine[0], RedLine[1]), (RedLine[2], RedLine[3]), (0, 255, 200), 5)
190
 
191
  print(totalCountUp)
192
+ entry_count=0
193
 
194
  for i in dict.values():
195
+ if (len(i) >= 2):
196
  if i[0] == True and i[1] == False:
197
+ print('in true/False')
198
  if entry_count > 0:
199
  entry_count -= 1
200
+
201
  if i[0] == False and i[1] == True:
202
+ print('in /False/True')
203
  entry_count += 1
204
+
205
 
206
 
207
+ # print('count is ', entry_count)
208
+ # print(dict)
209
+
 
 
210
 
211
  cv2.putText(img, str(entry_count), (110, 245), cv2.FONT_HERSHEY_PLAIN, 5, (50, 50, 230), 7)
212
  print('count is ', entry_count)
213
  print(dict)
214
+ cv2.imshow("Image", img)
215
+ cv2.waitKey(1)
216
  print(entry_count)
217
+
218
+ # if currentCoordinates==stationToCoordinates:
219
+ # reachedDestination=True
220
+ # fareCalculations()
221
+ # dict=[]
222
+ # break
223
+ if entry_count>2:
224
+ print('reached destination')
225
+ fareCalculations()
226
+ break
227
+
228
+
229
+
230
+
231