-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathSocial Distance Detection
More file actions
67 lines (58 loc) · 2.64 KB
/
Social Distance Detection
File metadata and controls
67 lines (58 loc) · 2.64 KB
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
import cv2
import numpy as np
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
def calculate_distance(point1, point2):
return np.linalg.norm(np.array(point1) - np.array(point2))
def social_distance_detection(video_source=0):
cap = cv2.VideoCapture(video_source)
while True:
# Read frame from the video source
ret, frame = cap.read()
height, width, _ = frame.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outputs = net.forward(output_layers)
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
# Filter only person class (ID 0 for COCO dataset)
if confidence > 0.5 and class_id == 0:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
detected_points = []
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cx, cy = x + w // 2, y + h // 2
detected_points.append((cx, cy))
cv2.putText(frame, "Person", (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
for i in range(len(detected_points)):
for j in range(i + 1, len(detected_points)):
dist = calculate_distance(detected_points[i], detected_points[j])
if dist < 100: # Distance threshold (e.g., 100 pixels)
cv2.putText(frame, "Maintain distance!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("Social Distance Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
social_distance_detection()