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 diminish. And hence the pixel area enclosed by the object will become smaller and smaller.
Therefore, we will use a method called contouraArea() to find the pixel area enclosed by the object. This method will return the area of the contour. In the Object detection and tracking code, make the following changes.
if len(contours) != 0: cnt = contours area = cv2.contourArea(cnt) M = cv2.moments(cnt) Cx = int(M['m10']/M['m00']) Cy = int(M['m01'] / M['m00']) S = 'Area Of Object: ' + str(area) cv2.putText(frame, S, (5, 50), font, 2, (0, 0, 255), 2, cv2.LINE_AA) cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3)
Run the code and you should see the area of contour on the top of the video.
The next part will be the calibration of object distance with the contour area. Keep the object in front of the camera at some distance and note down the distance manually using a ruler and its corresponding contour area. Now move the object a little farther from the camera and repeat the above process. Do several iterations for different distances. Remember, a large number of data points will give you higher accuracy. The data will be something similar as shown below.
The next step is to plot this data on the x-y axis. The distance must be on Y-axis. Now find a trendline through these data points and find the equation of the trendline in excel. You can choose a linear, exponential or polynomial trendline depending upon which fits best with the data. The trendline which I got is shown below. Remember to check the display equation box in trendline settings. For me, the quadratic equation worked best.
Now the last part is to enter this equation in the code.
distance = 2*(10**(-7))* (area**2) - (0.0067 * area) + 83.487
And finally, display the distance of the object on the screen.
S = 'Distance Of Object: ' + str(distance) cv2.putText(frame, S, (5, 50), font, 2, (0, 0, 255), 2, cv2.LINE_AA)
Run the code. This is it. Enjoy coding.
Check out full code here:- https://github.com/vibhor69meshram/Object-location-finding