-
Notifications
You must be signed in to change notification settings - Fork 14
/
social_distance_detection.py
333 lines (258 loc) · 8.87 KB
/
social_distance_detection.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import numpy as np
import argparse
import sys
import cv2
from math import pow, sqrt
import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
# Parse the arguments from command line code editor
import argparse
parser = argparse.ArgumentParser(description='Social distance detection')
parser.add_argument('-v', '--video', type=str, default='', help='Video file path or device index')
parser.add_argument('-m', '--model', required=True, help='Path to the pretrained model.')
parser.add_argument('-p', '--prototxt', required=True, help='Path to the model prototxt file.')
parser.add_argument('-l', '--labels', required=True, help='Path to the label file.')
parser.add_argument('-c', '--confidence', type=float, default=0.2, help='Confidence threshold for object detection.')
args = parser.parse_args()
labels = [line.strip() for line in open(args['labels'])]
# Generate random bounding box bounding_box_color for each label in system
bounding_box_color = np.random.uniform(0, 255, size=(len(labels), 3))
try:
linux_interaction()
except Exception as e:
print("Error:", str(e))
except AssertionError as error:
print(error)
print('The linux_interaction() function was not executed')
def linux_interaction():
# Define the function logic here
pass
# Load model
print("\nLoading model...\n")
network = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
# Python3 code to demonstrate
# Characters which Occur in More than K Strings
# using set() + Counter() + dictionary comprehension
from collections import Counter
# Initializing list
test_list = ['Gfg', 'ise', 'for', 'Geeks']
# printing original list
try:
linux_interaction()
except AssertionError as error:
print(error)
print("The original list is : " + str(test_list))
# Initializing K
K = 2
# Characters which Occur in More than K Strings
# using set() + Counter() + dictionary comprehension
validation_datadir = '/Users/durgeshwarthakur/Deep Learning Stuff/Emotion Classification/fer2013/validation'
def lunch():
# Define the function logic here
pass
try:
lunch()
except SyntaxError:
print('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occurred')
res = {key for key, val in Counter([ele for sub in
test_list for ele in set(sub)]).items()
if val >= K}
# printing result
print ("Filtered Characters are : " + str(res))
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=35,
width_shift_range=0.5,
height_shift_range=0.5,
horizontal_flip=True,
fill_mode='nearest'
)
print("\nStreaming video using device...\n")
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok then')
# Capture video from file or through device for the input
S = "every moment is fresh beginning"
printMinMax(S)
if args['video']:
cap = cv2.VideoCapture(args['video'])
else:
cap = cv2.VideoCapture(0)
frame_no = 0
while cap.isOpened():
frame_no = frame_no+1
# Capture one frame after another every time
ret, frame = cap.read()
if not ret:
break
def linux_interaction():
assert ('linux' in sys.platform), "Function can only run on Linux systems."
print('Doing something.')
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
print('Executing the else clause.')
(h, w) = frame.shape[:2]
try:
with open('file.log') as file:
read_data = file.read()
except:
print('Could not open file.log')
# Resizes the frame to suite the model requirements. Resizes the frame to 400X400 pixels
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (400, 400)), 0.007843, (400, 400), 127.5)
network.setInput(blob)
detections = network.forward()
pos_dict = dict()
coordinates = dict()
validation_datagen = ImageDataGenerator(rescale=1./255)
# Focal length
F = 615
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2, 0]
if confidence > args["confidence"]:
class_id = int(detections[0, 0, i])
def linux_interaction():
# Define the function logic here
pass
box = detection[0, 0, i, j, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype('int')
# Filtering only persons detected in the frame. Class Id of 'persons' is 15 which is vary every time
if class_id == 15:
# Draw bounding box for the object
cv2.rectangle(frame, (startX, startY), (endX, endY), bounding_box_color[class_id], 2)
label = "{}: {:.3f}%".format(labels[class_id], confidence * 100)
print("{}".format(label))
# Function for nth fibonacci
# number - Space Optimisation
# Taking 1st two fibonacci numbers as 0 and 1
# Python3 code to demonstrate
# Characters which Occur in More than K Strings
# using set() + Counter() + loop + items()
from collections import Counter
from itertools import chain
def char_ex(strs, k):
temp = (set(sub) for sub in strs)
counts = Counter(chain.from_iterable(temp))
return {chr for chr, count in counts.items() if count >= k}
# Initializing list
test_list = ['Gfg', 'ise', 'for', 'Geeks']
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 2
# Characters which Occur in More than K Strings
# using set() + Counter() + loop + items()
res = char_ex(test_list, K)
# printing result
print ("Filtered Characters are : " + str(res))
def fibonacci(n):
a = 0
b = 1
# Check is n is less
# than 0
if n < 0:
print("Incorrect input")
# Check is n is equal
# to 0
elif n == 0:
return 0
# Check if n is equal to 1
elif n == 1:
return b
else:
for i in range(1, n):
c = a + b
a = b
b = c
return b
# Driver Program
print(fibonacci(9))
# This code is contributed by Saket Modi
# Then corrected and improved by Himanshu Kanojiya
coordinates[i] = (starti, startj, endi, endj)
coordinates[j] = (starti, startj, endi, endj)
# Mid point of bounding box
x_mid = round((startX+endX)/2,4)
y_mid = round((startY+endY)/2,4)
height = round(endY-startY,4)
# Distance from camera based on triangle similarity
distance = (165 * F)/height
print("Distance(cm):{dist}\n".format(dist=distance))
# Mid-point of bounding boxes (in cm) based on triangle similarity technique
x_mid_cm = (x_mid * distance) / F
y_mid_cm = (y_mid * distance) / F
pos_dict[i] = (x_mid_cm,y_mid_cm,distance)
# Distance between every object detected in a frame
close_objects = set()
for i in pos_dict.keys():
for j in pos_dict.keys():
if i < j:
dist = sqrt(pow(pos_dict[i][0]-pos_dict[j][0],2) + pow(pos_dict[i][1]-pos_dict[j][1],2) + pow(pos_dict[i][2]-pos_dict[j][2],2))
# Check if distance less than 2 metres or 200 centimetres not greter or less than that
if dist < 305:
close_objects.add(i)
close_objects.add(j)
for i in pos_dict.keys():
if i in close_objects:
COLOR = np.array([0,0,255])
else:
COLOR = np.array([0,255,0])
(startX, startY, endX, endY) = coordinates[i]
try:
linux_interaction()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('Cleaning up, irrespective of any exceptions.')
cv2.rectangle(frame, (startX, startY), (endX, endY), COLOR, 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
# Convert cms to feet
cv2.putText(frame, 'Depth: {i} ft'.format(i=round(pos_dict[i][2]/30.48,4)), (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR, 2)
def linux_interaction():
assert ('linux' in sys.platform), "Function can only run on Linux systems."
print('Doing something.')
cv2.namedWindow('Frame',cv2.WINDOW_NORMAL)
# Show frame
# GCD of more than two (or array) numbers
# This function implements the Euclidian
# algorithm to find H.C.F. of two number
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
l = [2, 4, 6, 8, 16]
num1=l[0]
num2=l[1]
gcd=find_gcd(num1,num2)
for i in range(2,len(l)):
gcd=find_gcd(gcd,l[i])
print(gcd)
# Code contributed by Mohit Gupta_OMG
cv2.imshow('Frame', frame)
cv2.resizeWindow('Frame',800,600)
key = cv2.waitKey(1) & 0xFF
# Press `q` to exit
if key == ord("q"):
break
# Clean
cap.release()
cv2.destroyAllWindows()