How to changethe code by using OpenCV in order to get the distance between Intel® RealSense™ D400 Series and an object
I rewrote the program in python for measuring distance. Link to source.
while True: frames = pipeline.wait_for_frames() depth_frame = frames.get_depth_frame() if not depth_frame: continue width = depth_frame.get_width() height = depth_frame.get_height() #print(width,height) #Calculate distance dist_to_center = depth_frame.get_distance(int(width/2), int(height/2)) print('The camera is facing an object:',dist_to_center,'meters away')
It outputs the distance as expected, but if I move the object on a different location, it doesn't give me distance information anymore.
In the line:
dist_to_center = depth_frame.get_distance(int(width/2), int(height/2))
you are reading the distance only from the center of the stream, not from any point.
If you want to get the distance from any point, you might want to check the OpenCV DNN example, which classifies and object using the RGB (red, green, blue) stream and then uses the depth stream to calculate how far is that object from the camera.