Search code examples
opencvwebcamobject-recognition

Finding distance from camera to object of known size


I am trying to write a program using opencv to calculate the distance from a webcam to a one inch white sphere. I feel like this should be pretty easy, but for whatever reason I'm drawing a blank. Thanks for the help ahead of time.


Solution

  • You can use triangle similarity to calibrate the camera angle and find the distance.
    You know your ball's size: D units (e.g. cm). Place it at a known distance Z, say 1 meter = 100cm, in front of the camera and measure its apparent width in pixels. Call this width d.
    The focal length of the camera f (which is slightly different from camera to camera) is then f=d*Z/D.

    When you see this ball again with this camera, and its apparent width is d' pixels, then by triangle similarity, you know that f/d'=Z'/D and thus: Z'=D*f/d' where Z' is the ball's current distance from the camera.