You can get an approximate distance to an object in the image by using the pinhole camera model:
from the similarity of triangles you get:
x/f=X/Z
where:
f - focal length of the camera (in pixels),
x - size of the observed object in the image (in pixels),
X - size of the observed object in the real world (in meters, for example),
Z - distance between the camera and the object in the real world (same unit as X).
In order to calculate the distance you are looking for, you need to know f, x, and X.
You can get f by calibrating the camera with OpenCV or Matlab or whatever or you can estimate it quickly by putting an object of known size (X) at a known distance (Z) and measuring its size in the image (x).
Since you can detect cars (with a deep network, I presume) you also get their bounding rectangle. The width of this rectangle is the width of the car in the image (x).
Since you don't know the make and model of the detected car, you do not know it's real width. You have to assume it to some average value around, say, 2 meters.
Having all these numbers, you can estimate the distance to the car you see in the image. Of course it will not be very precise, but you don't need a centimeter precision, I suppose. I would say the distance error will be around +-10% but it is a very rough estimate. If you need more accuracy, the first thing you need to do is to recognize the make and model or at least the type of the vehicle you detect. The estimate of the real car size is the main contributor to error (unless you have a very wide angle lens, but with a standard webcam lens distortions will have negligible effect here).
helo, it's unclear, what youre doing, and where the problem is.
you want to find the distance to cars in front of your car from a dash cam?
yes witek i want find distance in real time can you please help me i am very new in this field i have already one program which can just detect things but no distance
I couldn't find link for you. Also I'm unable attempting to find my file that was about 4 yrs. ago
so you worked on same project may be you remember somehow ,how to do it?
https://www.pyimagesearch.com/2016/04... this is the link which is the code which i am using help me how i can edit it to find distance in real time
No. it is not pyimagesearch. There is university teacher posting on blog dating back to 2010. I was using raspberry pi 2B+. I was going to do raspberry pi 4b .Firstly, I was going to install OpenCV 4.1.2 by this weeken end.
Is calculating the distance in pixels an acceptable unit of measure? If yes, then it is a simple Euclidean distance calculation from detected box's edges or centroid to the next one
@eshirima. The answer is NO!
@Ayeshayounis. I found link and github. It was dating back to 2016. I am away from home. I be back soon.