pythonobject-detectioncamera-calibrationopencv

How to convert the distance between the object and the camera from pixels to meter?


I need to convert the distance between the object and the camera from pixels to meter/cm frame by frame and then calculate the speed of the moving object. In the first frame, the distance of the object from the camera is 4 meter, and the Focal length FL = 8mm. The width of the object is 0.0373 meters.

What I did first to calculate the projection of the object:

focal_length_px = 8000/4.8  #Focal length(px): 8mm / (4.8 µm / px) = 1667px =: f

Object :

    real_obj_width = 0.0373 # Width: 0.0373m
    distance = 4       # Distance: 4m
    obj_width_px = (object_reall_width/distance) * focal_length_px  # Projection of object(px): (0.0373 m / 4 m) * focal_length_px = 15.5 px

After object detection, I want to calculate the distance. I used the distance_finder() code in this link.

def distance_finder(focal_length, real_obj_width, obj_width_in_frame):  
    distance = (real_obj_width * focal_length) / obj_width_in_frame  
    return distance

and the output is:

obj_width_in_frame = 17
obj_dst = distance_finder(focal_length_px, obj_width_px, obj_width_in_frame)  # obj_dst = 1523.6928104575165

My question is: how to convert the object distance in the frame from the camera (obj_dst = 1523.69) from pixels to meters/cm?

and then calculate the speed of object in the frame.


Solution

  • We discussed the math before. Now you just need to rearrange some equations.

    Pinhole camera model.

    Object:

    Solve for physical distance, let's call it d.

    => d ~= 3.66 meters

    This equation is already implemented in your function distance_finder(). It is the same expression.