Realtime Distance Estimation Using OpenCV – Python
Prerequisite: Introduction to OpenCV
In this article, we are going to see how to calculate the distance with a webcam using OpenCV in Python. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. This article focuses on detecting objects.
We will do object detection in this article using something known as haar cascades.
Haar Cascade classifiers are an effective way for object detection. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.
The file can be downloaded from here: Forrontalface.
Steps for Distance Estimation:
- Capture Reference Image: Measure the distance from the object(face) to the camera, capture a Reference image and note down the measured distance
- Measure the object (face) width, make sure that measurement units are kept for reference image and object(face) width. Mine Reference Image
This function will detect the face and return the face width in the pixels values. This face data function simply takes one argument, which image, returns the face width in the pixels, which is a requirement for the focal length finder and distance finder function.
Focal Length Finder:
The Focal Length finder Function Tacks Three Arguments:
- Measured_distance: It is the distance from the camera to object while capturing the Reference image, Known_distance = 72.2 #centimeter
- Real_width: Its measure the width of an object in real-world, here we measure the width of the face which is around Known_width =14.3 #centimeter
- Width_in_rf_image: It is the width of the object in the image/frame it will be in pixels
This function will return the focal length, which is used to find the distance.
This function has three arguments.
- Focal length in pixel, which is a return from the Focal length finder function
- Real_width measures the width of an object in real-world, here we measure the width of the face which is around Known_width =14.3 #centimeter
- Width_in_rf_image is the width of the object in the image/frame it will be in pixels
The distance finder function will return the distance in the centimeters
Below is the full implementation:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course