|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") |
| 4 | +layer_names = net.getLayerNames() |
| 5 | +output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] |
| 6 | +def calculate_distance(point1, point2): |
| 7 | + return np.linalg.norm(np.array(point1) - np.array(point2)) |
| 8 | +def social_distance_detection(video_source=0): |
| 9 | + cap = cv2.VideoCapture(video_source) |
| 10 | + |
| 11 | + while True: |
| 12 | + # Read frame from the video source |
| 13 | + ret, frame = cap.read() |
| 14 | + height, width, _ = frame.shape |
| 15 | + |
| 16 | + # Detecting objects |
| 17 | + blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False) |
| 18 | + net.setInput(blob) |
| 19 | + outputs = net.forward(output_layers) |
| 20 | + |
| 21 | + boxes = [] |
| 22 | + confidences = [] |
| 23 | + class_ids = [] |
| 24 | + for output in outputs: |
| 25 | + for detection in output: |
| 26 | + scores = detection[5:] |
| 27 | + class_id = np.argmax(scores) |
| 28 | + confidence = scores[class_id] |
| 29 | + |
| 30 | + # Filter only person class (ID 0 for COCO dataset) |
| 31 | + if confidence > 0.5 and class_id == 0: |
| 32 | + center_x = int(detection[0] * width) |
| 33 | + center_y = int(detection[1] * height) |
| 34 | + w = int(detection[2] * width) |
| 35 | + h = int(detection[3] * height) |
| 36 | + # Rectangle coordinates |
| 37 | + x = int(center_x - w / 2) |
| 38 | + y = int(center_y - h / 2) |
| 39 | + |
| 40 | + boxes.append([x, y, w, h]) |
| 41 | + confidences.append(float(confidence)) |
| 42 | + class_ids.append(class_id) |
| 43 | + |
| 44 | + indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) |
| 45 | + detected_points = [] |
| 46 | + for i in range(len(boxes)): |
| 47 | + if i in indexes: |
| 48 | + x, y, w, h = boxes[i] |
| 49 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
| 50 | + cx, cy = x + w // 2, y + h // 2 |
| 51 | + detected_points.append((cx, cy)) |
| 52 | + cv2.putText(frame, "Person", (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) |
| 53 | + |
| 54 | + for i in range(len(detected_points)): |
| 55 | + for j in range(i + 1, len(detected_points)): |
| 56 | + dist = calculate_distance(detected_points[i], detected_points[j]) |
| 57 | + if dist < 100: # Distance threshold (e.g., 100 pixels) |
| 58 | + cv2.putText(frame, "Maintain distance!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) |
| 59 | + cv2.imshow("Social Distance Detection", frame) |
| 60 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 61 | + break |
| 62 | + |
| 63 | + cap.release() |
| 64 | + cv2.destroyAllWindows() |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + social_distance_detection() |
0 commit comments