python code for Social Distancing Detector Using OpenCV and Raspberry Pi

 Introduction :

Hey guys How are you in Covid-19 ? I think all is well and Healthy. Today’s project is related to Social Distancing so don’t worry, implement this simple python base project and stay secure : Social Distancing Detector Using OpenCV and Raspberry Pi; Let’s start :

Basically we need to implement this project on factories, banks, buses or railway stations, etc.

Python Code For Social Distancing Detector Using OpenCV And Raspberry Pi
Python Code For Social Distancing Detector Using OpenCV And Raspberry Pi

Pre-Requirement  :

  1. Raspberry Pi
  2. Need to install OpenCV
  3. We will use YOLO v3 Algorithms.  (You Only Look Once)

Procedure (python code for Social Distancing Detector Using OpenCV and Raspberry Pi) :

For implement Social Distancing Detector system using OpenCV and Raspberry Pi we need to use YOLO v3 Object Detection Algorithm with the Deep Neural Network module.

We know that Raspberry Pi is one of the best choice for Image processing and recognization projects because it has more memory and speed than other controllers like Node mcu micro, Arduino. 

What is YOLO Algorithms and how they apply in project ?  YOLO (You Only Look Once) is a smart Convolution neural network (CNN) used in real-time Object Detection project. 

Step 1: How to Installing openCV in Raspberry Pi ?

Remember one thing Before the installing the OpenCV and other dependencies, the Raspberry Pi must needs to be fully updated. we can also use the below commands to update the Raspberry Pi to its latest version:

sudo apt-get update

Step 2 : This time to installed OpenCV ON YOUR Raspberry Pi.

Then use the following commands lines :

sudo apt-get install libhdf5-dev -y 

sudo apt-get install libhdf5-serial-dev –y 

sudo apt-get install libatlas-base-dev –y 

sudo apt-get install libjasper-dev -y 

sudo apt-get install libqtgui4 –y

sudo apt-get install libqt4-test –y

So guys Finally we install the OpenCV on Raspberry Pi using the below commands.

pip3 install opencv-contrib-python==

Step 3: Installing imutils Packages in Raspberry Pi

This package used to make essential image processing functions such asrotation, resizing, translation, skeletonization, and displaying Matplotlib images with OpenCV. 

For install this package use the below command :

pip3 install imutils

Step 4 : python code for Social Distancing Detector Using OpenCV and Raspberry Pi

import numpy as np
import cv2
import imutils
import os
import time
def Check(a,  b):
    dist = ((a[0] - b[0]) ** 2 + 550 / ((a[1] + b[1]) / 2) * (a[1] - b[1]) ** 2) ** 0.5
    calibration = (a[1] + b[1]) / 2      
    if 0 < dist < 0.25 * calibration:
        return True
        return False
def Setup(yolo):
    global net, ln, LABELS
    weights = os.path.sep.join([yolo, "yolov3.weights"])
    config = os.path.sep.join([yolo, "yolov3.cfg"])
    labelsPath = os.path.sep.join([yolo, "coco.names"])
    LABELS = open(labelsPath).read().strip().split("\n")  
    net = cv2.dnn.readNetFromDarknet(config, weights)
    ln = net.getLayerNames()
    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
def ImageProcess(image):
    global processedImg
    (H, W) = (None, None)
    frame = image.copy()
    if W is None or H is None:
        (H, W) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
    starttime = time.time()
    layerOutputs = net.forward(ln)
    stoptime = time.time()
    print("Video is Getting Processed at {:.4f} seconds per frame".format((stoptime-starttime))) 
    confidences = []
    outline = []
    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            maxi_class = np.argmax(scores)
            confidence = scores[maxi_class]
            if LABELS[maxi_class] == "person":
                if confidence > 0.5:
                    box = detection[0:4] * np.array([W, H, W, H])
                    (centerX, centerY, width, height) = box.astype("int")
                    x = int(centerX - (width / 2))
                    y = int(centerY - (height / 2))
                    outline.append([x, y, int(width), int(height)])
    box_line = cv2.dnn.NMSBoxes(outline, confidences, 0.5, 0.3)
    if len(box_line) > 0:
        flat_box = box_line.flatten()
        pairs = []
        center = []
        status = [] 
        for i in flat_box:
            (x, y) = (outline[i][0], outline[i][1])
            (w, h) = (outline[i][2], outline[i][3])
            center.append([int(x + w / 2), int(y + h / 2)])
        for i in range(len(center)):
            for j in range(len(center)):
                close = Check(center[i], center[j])
                if close:
                    pairs.append([center[i], center[j]])
                    status[i] = True
                    status[j] = True
        index = 0
        for i in flat_box:
            (x, y) = (outline[i][0], outline[i][1])
            (w, h) = (outline[i][2], outline[i][3])
            if status[index] == True:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 150), 2)
            elif status[index] == False:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            index += 1
        for h in pairs:
            cv2.line(frame, tuple(h[0]), tuple(h[1]), (0, 0, 255), 2)
    processedImg = frame.copy()
create = None
frameno = 0
filename = "newVideo.mp4"
yolo = "yolov3/"
opname = "output2.avi"
cap = cv2.VideoCapture(filename)
time1 = time.time()
    ret, frame =
    if not ret:
    current_img = frame.copy()
    current_img = imutils.resize(current_img, width=480)
    video = current_img.shape
    frameno += 1
    if(frameno%2 == 0 or frameno == 1):
        Frame = processedImg
        cv2.imshow("Image", Frame)
        if create is None:
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            create = cv2.VideoWriter(opname, fourcc, 30, (Frame.shape[1], Frame.shape[0]), True)
    if cv2.waitKey(1) & 0xFF == ord('s'):
time2 = time.time()
print("Completed. Total Time Taken: {} minutes".format((time2-time1)/60))

Ohhhh Finally we are completed our project ….

Summary :

In this project we saw Python Code For Social Distancing Detector Using OpenCV And Raspberry Pi project so about this section you have any query then free to ask me


I am Mr. Sachin pagar the founder of Pythonslearning, a Passionate Educational Blogger and Author, who love to share the informative content on educational resources.

Leave a Comment