Skip to main content

How Far You Are From Your Camera? Python | OpenCv


Hello Friends! In this blog, you will learn to find out the distance between you and your webcam. Take a look at the video below. 



Let's get started. For this project, we will be using face detection using the Haar Cascade method. Therefore, we need to download the cascade classifier for face detection from Github. You can download and paste the file from this link.

Let us first understand what is Haar Cascade? 
Haar Cascade is a machine learning object detection algorithm used to identify objects in an image or video and based on various​​ features. 
If you want to read a more detailed version of it, check out this link.

Now, we will start by importing the libraries and define a variable to capture video from my webcam.

import cv2
import numpy as np
cap = cv2.VideoCapture(0)
Let us import our classifier file which we downloaded from Github.

face = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
write a while loop and capture the image frames. Also, we need to mirror the frames so that we can see it right.

while 1:
ret, frame = cap.read() ##Read image frame
frame = cv2.flip(frame, +1) ##Mirror image frame

All we have to do now is to convert the image into grayscale and use the detectMultiScale() method to detect faces in the image frame.

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
detect_face = face.detectMultiScale(gray, 1.2, 1)
detectMultiScale() requires three arguments. The first is the source image, the second is the scale factor which specifies how much the image size is reduced at each image scale and the third is the minimum neighbors which specify how many neighbors each candidate rectangle should have to retain it. This method returns the coordinates of the rectangle detecting a face.

Remember, our goal is to find the distance of the face from the camera. So, for that, we need to find out the area of the enclosed rectangle. This can be done by the following code.

for(x, y, z, h) in detect_face:
cv2.rectangle(frame, (x, y), (x+z, y+h), (0, 255, 0), 2)
ROI = gray[x:x+z, y:y+h]
length = ROI.shape[0]
breadth = ROI.shape[1]
Area = length * breadth
display = 'Area = ' + str(Area)
if Area > 0:
cv2.putText(frame, display, (5, 50), font, 2, (255, 255, 0), 2, cv2.LINE_AA)



We will display the area on our original image. That will help us for calibration.
You can go through the video for the calibration process. 
All we have to do is measure the distance of the camera from your face using a tailor's measuring tape and the corresponding area. Do several iterations of this for various distances and store the data in an excel file. Then we plot the graph and find a trendline for the graph. We find the equation of trendline and insert it in our code.



for(x, y, z, h) in detect_face:
cv2.rectangle(frame, (x, y), (x+z, y+h), (0, 255, 0), 2)
ROI = gray[x:x+z, y:y+h]
length = ROI.shape[0]
breadth = ROI.shape[1]
Area = length * breadth
Distance = 3 * (10 ** (-9)) * (Area ** 2) - 0.001 * Area + 108.6
display = 'Distance = ' + str(Distance)
if Area > 0:
cv2.putText(frame, display, (5, 50), font, 2, (255, 255, 0), 2, cv2.LINE_AA)



That is it. Our code is ready. Don't forget to release the memory and close all the windows.

cap.release()                   ##Release memory
cv2.destroyAllWindows() ##Close all the windows

For full code click here.
For classifier, files click here.

Happy Coding...!!!


Comments

  1. Hi! Love your solution of finding the distance using Object detection! At current stage im pretty new to python, and find your videoed good for tutorial purposes as your projects has a link to the code aswell. May be far fetched, but would you also release this code? Love your tutorial, easy and understandable!

    ReplyDelete

Post a Comment

Popular posts from this blog

Object Distance Calculation Using Contour Area Method In Python - Opencv

Today we will discuss how you can find the distance of an object from the camera using python OpenCV. Check out the video below. Before we continue, you should know how to detect a colored object. Click this link to check out my previous blog on object detection and tracking. I hope after checking out my previous blog, you are able to write your own code to detect and track objects. We will take forward the Object detection and tracking code to find the distance of an object from the camera. So let's start. Let us first understand the principle using which we will find the distance of the object from the camera. Principle:- Area enclosed by the contours of an object decreases as the object moves farther from the camera. This simply means that, if your object is near to the camera, the object will appear bigger. Thus the pixel area occupied by the object will be very large. As you move the object farther from the camera, the object size in the image will start to d...

Iris Detection | Python | OpenCv

 Hello there! Welcome to another blog. In this blog you are going to learn to detect iris using OpenCv python. Here is the video in case you missed it. So, let's get started. We will start by importing the necessary libraries. import cv2 import numpy as np Now, let us import the face and eye classifier files and set the camera resolution as follows. eye = cv2.CascadeClassifier( 'haarcascade_eye.xml' ) face = cv2.CascadeClassifier( 'haarcascade_frontalface_alt.xml' ) Kernal = np.ones(( 3 , 3 ) , np.uint8) #Declare kernal for morphology cap = cv2.VideoCapture( 0 ) cap.set(cv2.CAP_PROP_FRAME_WIDTH , 320 ) ##Set camera resolution cap.set(cv2.CAP_PROP_FRAME_HEIGHT , 240 ) In a while loop let us capture an image frame, flip it(in case your camera captures inverted images) and convert it into a gray scale image. ret , frame = cap.read() ##Read image frame frame = cv2.flip(frame , + 1 ) ##Flip the image in case your camera...

Object Detection And Tracking using Python - Opencv

Let us discuss today how you can detect and track an object in real-time. We will be using Python language and Opencv library for this purpose. Check out the video below. If you have read my previous blogs, you can directly skip down to the contour part. As usual, we need to make a few assumptions for the proper working of this application. This background is always static i.e. there is no addition or subtraction of objects in the background scene. The background-color is always constant. It does not change with time. The object that will be used for writing/painting is of a different color than the background to give us sufficient contrast between foreground and background. We are ready to begin now. Let us start by installing necessary python libraries for our project using  pip install.  We will be needing  Numpy  and  Opencv  libraries. Now create a python project and create a new script. Import the required libraries into python script as...