Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions Social Distance Detection
Original file line number Diff line number Diff line change
@@ -0,0 +1,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()