Calculate object distance with camera

Firstly I'm unsure whether this question belongs here or on another SE site (but I'll wing it for now).

I've recently been given the job of connecting up a 'smart camera' to a setup where a robotic arm will pick and place objects from point A to point B. The real application for the camera is to check if the objects are out of alignment to their supposed positions.

However I am curious to see if there is any way I can calculate the distance of an object given that I already know the objects actual size. Naturally the camera will see the object as bigger when closer and smaller when farther away but how can I turn this information into depth/distance from the camera?

I have not yet started using the camera. For now it is just an idea. I will assume that I can calculate what percentage of the view frame is taken up by the object.

For example if I have an object of uniform shape, I know that from dist1 it takes up 75% of the view frame and from dist2 it takes up 45% of the view frame.

Should this prove to be possible I imagine that it could have a number of different applications. /Anyway any feedback is appreciated. Thanks! ( :

• You might have better luck at the OpenCV Q&A – Airuno2L Jul 30 '14 at 0:09
• How controlled are the conditions that you plan to work in? – Ian Aug 5 '14 at 2:32

For example, suppose the camera (with focal length $f$) was looking at a ruler of length $l$ with the 0 end at pixel (0,0) and the other end at pixel ($u_x$,0). From trig you get \begin{align} tan(\theta) &= \frac{u_x}{f} \\ &= \frac{l}{d} \\ d &= \frac{l}{tan(\theta)} \\ &= \frac{l f}{u_x} \end{align}
where $d$ is the distance from the camera to the ruler. (someone please double check my math)