Learn how to build your own Social Distancing Tool using your Deep Learning and Computer Vision skills
Understand the State-of-the-Art architectures (SOTA) for Object Detection
Hands-on with Detectron 2 – FAIR library for Object Detection and Segmentation – required to build the social distancing tool
Introduction
Social Distancing – the term that has taken the world by storm and is transforming the way we live. Social distancing has become a mantra around the world, transcending languages and cultures.
This way of living has been forced upon us by the fastest growing pandemic the world has ever seen – COVID-19. As per the World Health Organization (WHO), COVID-19 has so far infected almost 4 million people and claimed over 230K lives globally. Around 213 countries have been affected so far by the deadly virus.
The biggest cause of concern is that COVID-19 spreads from person to person through contact or if you’re within close proximity of an infected person. Given how densely populated some areas are, this has been quite a challenge.
The only way to prevent the spread of COVID-19 is Social Distancing. Keeping a safe distance from each other is the ultimate way to prevent the spread of this disease (at least until a vaccine is found).
So this got me thinking – I want to build a tool that can potentially detect where each person is in real-time, and return a bounding box that turns red if the distance between two people is dangerously close. This can be used by governments to analyze the movement of people and alert them if the situation turns serious.
Here’s a taste of the social distancing detection tool we’ll be building:
I would recommend going through the below articles and courses if you need a refresher:
Social Distancing Tool – An Use Case of Object Detection and Tracking
What’s Next?
Overview of Object Detection and Tracking
I can vividly recall my initial days learning computer vision. I often got confused between these two terms – Image Classification and Object Detection. I used both of these terms interchangeably assuming the idea behind them was similar. And, as a result, I kept getting confused between deep learning projects. Not ideal!
So, I will kickstart the article by answering this perplexing question – are image classification and object detection one and the same?
Think about it – objects are everywhere! That’s why Object Detection and Image Classification are very popular tasks in computer vision. They have a wide range of applications in defense, healthcare, sports, and the space industry.
The fundamental difference between these two tasks is that image classification identifies an object in an image whereas object detection identifies the object as well as its location in an image. Here’s a classic example to understand this difference:
Well, then how is Object Tracking different from Object Detection?
Object Tracking and Object Detection are similar in terms of functionality. These two tasks involve identifying the object and its location. But, the only difference between them is the type of data that you are using. Object Detection deals with images whereas Object Tracking deals with videos.
Object Detection applied on each and every frame of a video turns into an Object Tracking problem.
As a video is a collection of fast-moving frames, Object Tracking identifies an object and its location from each and every frame of a video.
Evolution of State-of-the-Art (SOTA) for Object Detection
Object Detection is one of the most challenging problems in computer vision. Having said that, there has been an immense improvement over the past 20 years in this field. We can broadly divide this into two generations – before and after deep learning:
History of Object Detection (Reference: Object Detection in 20 Years: A Survey)
Now, I will discuss some of the popular and widely used techniques for Object Detection.
Sliding Window for Object Detection
The simplest approach to build an Object Detection model is through a Sliding Window approach. As the name suggests, an image is divided into regions of a particular size and then every region is classified into the respective classes.
Remember that the regions can be overlapping and varying in size as well. It all depends on the way you want to formulate the problem.
Model Workflow
Consider an image
Divide an image into regions (assume 10 * 10 region)
For each region:
Pass a region to Convolutional Neural Network (CNN)
Extract features from CNN
Pass features to a classifier & regressor
This method is really simple and efficient. But it’s a time-consuming process as it considers the huge number of regions for classification. Now, we will see how we can reduce the number of regions for classification in the next approach.
R-CNN for Object Detection
So how do we make this a non-time consuming task? This can be brought down by discarding the regions that are not likely to contain the object. This process of extracting the regions that are likely to contain the object is known as Region Proposals.
Region proposals have a higher probability of containing an object
Many Region Proposal algorithms have been proposed to select a Region of Interest (ROI). Some of the popular ones are objectness, selective search, category-independent object proposals, etc. So, R-CNN was proposed with an idea of using the exterior region proposal algorithm.
R-CNN stands for Region-based Convolutional Neural Network. It uses one of the external region proposal algorithms to select the region of interest (ROI).
Model Workflow
Consider an image
Select ROI using exterior region proposal algorithm
For each region:
Pass a region to CNN
Extract features from CNN
Pass features to a classifier & regressor
The predicted regions can be overlapping and varying in size as well. So, Maximum Non Suppression is used to ignore the bounding boxes depending upon the Intersection Over Union (IOU) score:
Certainly, R-CNN’s architecture was the State of the Art (SOTA) at the time of the proposal. But it consumes nearly 50 seconds for every test image during inference because of the number of forward passes to a CNN for feature extraction. As you can observe under the model workflow, every region proposal is passed to a CNN for feature extraction.
For example, if an image has 2000 regions of proposals, then the number of forward passes to the CNN is around 2000. This inevitably led to another model architecture known as Fast R-CNN.
Fast R-CNN for Object Detection
In order to reduce the inference speed, a slight change in the R-CNN workflow was made and proposed, known as Fast R-CNN. The modification was done in the feature extraction of region proposals.
In R-CNN, feature extraction takes place for each region proposal whereas, in Fast R-CNN, feature extraction takes place only once for an original image. Then the relevant ROI features are chosen based on the location of the region proposals. These region proposals are constructed before passing an image to CNN.
Remember that the input to CNN is the actual image without any ROI:
Model Workflow
Consider an image
Select Regions of Interest (ROI) using exterior region proposal algorithm
Pass an image to the CNN
Extract the features of an image
Choose relevant ROI features using the location of ROI
For each ROI feature, pass features to a classifier & regressor
During inference, Fast R-CNN consumes nearly 2 seconds for each test image and is about 25 times faster than R-CNN. The reason being the change in the feature extraction of ROI. For example, if an image has a 2000 region of proposals, then the number of forward passes to the CNN is around 1.
Can we still bring down the inference speed? Yes! It’s possible. This led to Faster R-CNN, a SOTA model for object detection tasks.
Faster R-CNN for Object Detection
Faster R-CNN replaces the exterior region proposal algorithm with a Region Proposal Network (RPN). RPN learns to propose the region of interests which in turn saves a lot of time and computation as compared to a Fast R-CNN.
Faster R-CNN = Fast R-CNN + RPN
Model Workflow
Consider an image
Pass an image to CNN
Extract the features of an image
Select ROI features using Region Proposal Network (RPN)
For each ROI feature, pass features to a classifier & regressor
Faster R-CNN takes close to 0.2 seconds for every test image during inference and is about 250 times faster than Fast R-CNN.
Your Social Distancing Tool – A Use Case of Object Detection & Tracking
Social Distancing is the only way to prevent the spread of COVID-19 right now. Recently, Andrew Ng’s Landing AI team created a Social Distancing Tool using the concepts of Computer Vision. This project is inspired by their work. You can download the video from here.
Time to power up your coding skills!
Note: The code is developed on Google Colab. I would recommend using the same. Change the runtime to GPU prior to installing libraries.
Understanding Detectron 2
Detectron 2 is an open-source library for object detection and segmentation created by the Facebook AI Research team, popularly known as FAIR. Detectron 2 implements state of the art architectures like Faster R CNN, Mask R CNN, and RetinaNet for solving different computer vision tasks, such as:
Object Detection
Instance Segmentation
Keypoint Detection
Panoptic Segmentation
The baseline models of Faster R-CNN and Mask R-CNN are available with 3 different backbone combinations. Please refer to this Detectron-2 GitHub repository for additional details.
Let’s begin!
Install Dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Download the pre-trained model for object detection from Detectron 2’s model zoo and then the model is ready for inference:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Read an image and pass it to the model for predictions:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Can you guess the output of the model? Yes, Objects and Locations, since its an object detection model. We can use Visualizer to draw the predictions on the image:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
As you can see here, multiple objects are present in an image, like a person, bicycle, and so on. We are well on our way to building the social distancing detection tool!
Next, understand the objects present in an image:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
As different objects are present in an image, let’s identify classes and bounding boxes related to only the people:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Our ultimate goal is to compute the distance between two people in an image. Once we know the bounding box for each person, we can easily compute the distance between any two people. But the challenge here is to select the right coordinate for representing a person as a bounding box is in the form of a rectangle.
I have chosen the bottom center of a rectangle for representing each person to measure the distance accurately and also this measure is invariant of the height of a person:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Define a function that returns the bottom center of every bounding box:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Compute the bottom center for every bounding box and draw the points on the image:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Define a function to compute the Euclidean distance between every two points in an image:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Compute the distance between every pair of points:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Define a function that returns the closest people based on the given proximity distance. Here, proximity distance refers to the minimum distance between two people:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Set the threshold for the proximity distance. Here, I have chosen that to be 100. Let’s find the people who are within the proximity distance:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
From the output, we can observe that 4 people come under the red zone as the distance between them is less than the proximity threshold.
Define a function to change the color of the closest people to red:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Let’s change the color of the closest people to red:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
So far, we have seen a step by step procedure on how to apply object detection using Detectron-2, compute the distance between every pair of people, and then finally identify the closest people. We will carry out similar steps on each and every frame of the video now:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Define a function that performs all the steps we covered on each and every frame of the video:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Identify the closest people in each frame and change the color to red:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
After identifying the closest people in each frame, convert the frames back to a video. That’s it!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Keep in mind that the projection of the camera also matters a lot while computing the distance between the objects in an image.
In our case, I have not taken into account the projection of the camera since the impact of the camera’s projection on the estimated distance is minimum. However, the universal approach is to convert a video into a top view or birds’ eye view and then compute the distance between two objects in an image. This task is known as Camera Calibration.
Keep that in mind if you want to explore this further and customize your own social distancing detection tool.
End Notes
This brings us to the end of our tutorial on how to build your own social distancing tool using computer vision. I hope you have enjoyed the tutorial and found it useful. If you have any comments/queries, kindly leave them in the comments section below and I will reach out to you. And remember:
Stay SAFE (Stay Away From Everyone) to prevent the spread of the COVID-19 pandemic
The code is not working in Google Colab.
Error:
--------------------------------------------------------------------------
ImportError Traceback (most recent call last)
in ()
14
15 # import some common detectron2 utilities
---> 16 from detectron2 import model_zoo
17 from detectron2.engine import DefaultPredictor
18 from detectron2.config import get_cfg
4 frames
/usr/local/lib/python3.6/dist-packages/detectron2/layers/deform_conv.py in ()
8 from torch.nn.modules.utils import _pair
9
---> 10 from detectron2 import _C
11
12 from .wrappers import _NewEmptyTensorOp
ImportError: libtorch_cpu.so: cannot open shared object file: No such file or directory
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
Karanbir singh
Great work!!
You are using euclidean distance for measuring distance but doesnot variation due to depth of two persons affect it.Two people who are standing one infront of other will appear as they are close but actually they can be wide apart or viceversa.
How to take that into account ? Is there a true need for taking that into account?
Maddula Ravi Prakash
Hi Aravind,
I am trying to run to do installation, packages get installed but when try to import detectron i get the below error. any idea what's this issue.
8 from torch.nn.modules.utils import _pair
9
---> 10 from detectron2 import _C
11
12 from .wrappers import _NewEmptyTensorOp
ImportError: libtorch_cpu.so: cannot open shared object file: No such file or directory
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
Powered By
Cookies
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
brahmaid
It is needed for personalizing the website.
csrftoken
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Identityid
Preserves the login/logout state of users across the whole site.
sessionid
Preserves users' states across page requests.
g_state
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
MUID
Used by Microsoft Clarity, to store and track visits across websites.
_clck
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
_clsk
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
SRM_I
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
SM
Use to measure the use of the website for internal analytics
CLID
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
SRM_B
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
_gid
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
_ga_#
Used by Google Analytics, to store and count pageviews.
_gat_#
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
collect
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
AEC
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
G_ENABLED_IDPS
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
test_cookie
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
_we_us
this is used to send push notification using webengage.
WebKlipperAuth
used by webenage to track auth of webenagage.
ln_or
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
JSESSIONID
Use to maintain an anonymous user session by the server.
li_rm
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
AnalyticsSyncHistory
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
lms_analytics
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
liap
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
visit
allow for the Linkedin follow feature.
li_at
often used to identify you, including your name, interests, and previous activity.
s_plt
Tracks the time that the previous page took to load
lang
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
s_tp
Tracks percent of page viewed
AMCV_14215E3D5995C57C0A495C55%40AdobeOrg
Indicates the start of a session for Adobe Experience Cloud
s_pltp
Provides page name value (URL) for use by Adobe Analytics
s_tslv
Used to retain and fetch time since last visit in Adobe Analytics
li_theme
Remembers a user's display preference/theme setting
li_theme_set
Remembers which users have updated their display / theme preferences
We do not use cookies of this type.
_gcl_au
Used by Google Adsense, to store and track conversions.
SID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
SAPISID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
__Secure-#
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
APISID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
SSID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
HSID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
DV
These cookies are used for the purpose of targeted advertising.
NID
These cookies are used for the purpose of targeted advertising.
1P_JAR
These cookies are used to gather website statistics, and track conversion rates.
OTZ
Aggregate analysis of website visitors
_fbp
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
fr
Contains a unique browser and user ID, used for targeted advertising.
bscookie
Used by LinkedIn to track the use of embedded services.
lidc
Used by LinkedIn for tracking the use of embedded services.
bcookie
Used by LinkedIn to track the use of embedded services.
aam_uuid
Use these cookies to assign a unique ID when users visit a website.
UserMatchHistory
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
li_sugr
Used to make a probabilistic match of a user's identity outside the Designated Countries
MR
Used to collect information for analytics purposes.
ANONCHK
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
We do not use cookies of this type.
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
The code is not working in Google Colab. Error: -------------------------------------------------------------------------- ImportError Traceback (most recent call last) in () 14 15 # import some common detectron2 utilities ---> 16 from detectron2 import model_zoo 17 from detectron2.engine import DefaultPredictor 18 from detectron2.config import get_cfg 4 frames /usr/local/lib/python3.6/dist-packages/detectron2/layers/deform_conv.py in () 8 from torch.nn.modules.utils import _pair 9 ---> 10 from detectron2 import _C 11 12 from .wrappers import _NewEmptyTensorOp ImportError: libtorch_cpu.so: cannot open shared object file: No such file or directory --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below.
Please install torch 1.5 to resolve the error
Great work!! You are using euclidean distance for measuring distance but doesnot variation due to depth of two persons affect it.Two people who are standing one infront of other will appear as they are close but actually they can be wide apart or viceversa. How to take that into account ? Is there a true need for taking that into account?
Hi Aravind, I am trying to run to do installation, packages get installed but when try to import detectron i get the below error. any idea what's this issue. 8 from torch.nn.modules.utils import _pair 9 ---> 10 from detectron2 import _C 11 12 from .wrappers import _NewEmptyTensorOp ImportError: libtorch_cpu.so: cannot open shared object file: No such file or directory
Hi, installing torch 1.5 resolves the error