Measuring social distancing using Tensorflow Object Detection API

These days being at the right distance from another person is very important. Due to the COVID-19 situation, we’ve learned a lot about social distancing and how it can help us fight the virus.

Using Tensorflow you can measure how far or close a person is from another person. This will be a relative measure given that the picture can be from different angles and perspectives.

This example will be based on the Object Detection Google Collab Notebook. You can try it out with a few tweaks. In the following paragraphs, I’ll explain the changes and tweaks needed to run the example.

The final result will be something like the following picture. You’ll have some lines and a list of the distances. You can also play with a threshold that way you can only show lines below that threshold (when people are too close).

First of all, you need to add some imports to the import section. You’ll need this to draw the lines:

We will use the show_inference method as a starting point. We’ll also have to create some methods. The main idea is to complete the following steps:

  • Get every detected object from Tensorflow.
  • Filter them by class (we only want people) and score (we only want objects with a confidence higher than 50%).
  • Calculate centroids for the boxes. This is a fancy word that means the center of a rectangle.
  • Calculate permutations between all the centroids.
  • Calculate distance for the different permutations.
  • Apply a threshold to the permutations based on the distance.
  • Draw the lines
  • Show the picture

With the following method we can calculate the centroid for the bounding box (fancy word for rectangle):

To calculate the centroids. I found a very neat trick on Stackoverflow. This will allow us to find the permutation but to avoid adding the inverse permutation. For example, if you have 2 points (A, B). You only need a line from A-B or B-A, not both:

To calculate the distance, we’ll use the Euclidean distance. The formula looks very similar to the hypotenuse form a triangle.

The following method calculates the distances for a group of permutations:

To draw the lines, we’ll need to normalize the centroids using the image width and size.

Once we have everything in place here is the full method:

You can also find the whole code on this repository.

Machine Learning, Humans in Tech and Startups.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store