Learning Guides
Building a Social Distancing Detection Tool Using OpenCV and Deep Learning
Quick answer: Learn how to build a social distancing detection tool using OpenCV and a pretrained object detection model to measure distances between people in video.
What This Tool Does
A social distancing detection tool identifies people in a video feed, estimates their real-world positions, and flags pairs that are closer together than a defined safe distance threshold. It gained particular attention as a practical computer vision project during the COVID-19 pandemic.
Step 1: Detecting People
import cv2
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = ["person", "car", ...] # loaded from a labels file
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
frame = cv2.imread("street.jpg")
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), swapRB=True)
net.setInput(blob)
outputs = net.forward(output_layers)
A pretrained object detection model such as YOLO identifies bounding boxes for every person detected in each frame.
Step 2: Estimating Ground Positions
The bottom-centre point of each person's bounding box is typically used as an approximation of where their feet touch the ground, giving a consistent reference point for measuring distance between people.
def get_ground_point(box):
x, y, w, h = box
return (x + w // 2, y + h)
Step 3: Correcting for Camera Perspective
A raw pixel distance is misleading, since people further from the camera appear closer together in pixels than people at the same real distance nearer the camera. A perspective transform maps the image into a bird's-eye view, so distances can be measured more fairly across the whole frame.
import numpy as np
src_points = np.float32([[100, 400], [500, 400], [50, 600], [600, 600]])
dst_points = np.float32([[0, 0], [400, 0], [0, 600], [400, 600]])
matrix = cv2.getPerspectiveTransform(src_points, dst_points)
transformed_point = cv2.perspectiveTransform(np.array([[point]], dtype='float32'), matrix)
Step 4: Measuring Distance and Flagging Violations
from itertools import combinations
import math
def calculate_distance(p1, p2):
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
MINIMUM_DISTANCE = 100 # in transformed pixel units, calibrated to a real-world distance
violations = []
for p1, p2 in combinations(transformed_points, 2):
if calculate_distance(p1, p2) < MINIMUM_DISTANCE:
violations.append((p1, p2))
Step 5: Drawing Results
for box in boxes:
color = (0, 0, 255) if box in violating_boxes else (0, 255, 0)
cv2.rectangle(frame, (box[0], box[1]), (box[0]+box[2], box[1]+box[3]), color, 2)
Boxes are typically coloured red for a flagged violation and green otherwise, giving an immediate visual signal.
Genuine Limitations
Accuracy depends heavily on correct camera calibration for the perspective transform, occluded or overlapping people can be missed or double counted, and the tool measures only physical proximity, not actual transmission risk, which depends on many other factors.
Common Interview Questions
Why is a perspective transform necessary in this project?
Raw pixel distances are misleading because people further from the camera appear closer together in pixels than people at the same actual distance nearer the camera. The transform maps the scene to a bird's-eye view so distances can be measured fairly across the frame.
What object detection model is typically used for detecting people in this kind of project?
A pretrained model such as YOLO, chosen for its strong speed-accuracy balance, since the tool ideally needs to process video in close to real time.
FAQ
Frequently Asked Questions
What does a social distancing detection tool do?
It identifies people in a video feed, estimates their real-world positions, and flags pairs that are closer together than a defined safe distance threshold.
Why is a perspective transform needed in this project?
Raw pixel distances are misleading since people further from the camera appear closer together in pixels than people at the same real distance nearer the camera. A perspective transform corrects for this by mapping the scene to a bird's-eye view.
What are the main limitations of this kind of tool?
Accuracy depends on correct camera calibration, occluded people can be missed or double counted, and it measures only physical proximity, not actual transmission risk.
Keep Reading
Related Articles
Learning Guides
INNER JOIN in SQL with Examples: Complete Beginner's Guide
Learn INNER JOIN in SQL with practical examples, syntax, interview questions, and real-world use cases. A complete beginner-friendly SQL JOI
Learning Guides
OUTER JOIN in SQL: Complete Guide with Examples for Beginners
Master OUTER JOIN in SQL with practical examples and real-world scenarios. Learn LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, syntax, use cases,
Learning Guides
Multi-Row Functions in SQL: Complete Guide with Examples
Learn multi-row (aggregate) functions in SQL including SUM, AVG, COUNT, MIN, MAX, GROUP BY and HAVING, with practical examples, NULL handlin