librealsense icon indicating copy to clipboard operation
librealsense copied to clipboard

Get number of frames in bag file using pyrealsense2

Open jkenney9a opened this issue 7 years ago • 12 comments

  • Before opening a new issue, we wanted to provide you with some useful suggestions (Click "Preview" above for a better view):

  • All users are welcomed to report bugs, ask questions, suggest or request enhancements and generally feel free to open new issue, even if they haven't followed any of the suggestions above :)


Required Info
Camera Model {D435 }
Firmware Version (Open RealSense Viewer --> Click info)
Operating System & Version {Linux (Ubuntu 16)}
Kernel Version (Linux Only) (e.g. 4.15)
Platform PC
SDK Version { legacy / 2.17.1 }
Language {python}
Segment { }

Issue Description

I'm looking for a way to get the number of frames from a recorded bag file using pyrealsense2. There is this discussion, but not really any resolution.

As I note in #3665, I'm working on pulling out depth information at each frame. What I'd like to do is save the depth info into an hdf5 file, which (I believe) requires/prefers to have the size of the file pre-determined before writing into it (at least it seems like it should process faster). But to do so I need to obtain the number of frames before processing. Seems like there should be some simple way to do this, but I've been unable to find anything.

jkenney9a avatar Apr 04 '19 17:04 jkenney9a


Hi jkenney9a,

Not sure how much would the dump from "rosbag info" command help you? And RS built-in bool rosbag-inspector provides a GUI interface to details.

Thanks!


Hi jkenney9a,

Any update on this one?

Thanks!

Thanks for the follow-up. Was hoping to find a way to do this with just pyrealsense2 but will look into using rosbag info or some other approach.

jkenney9a avatar May 01 '19 16:05 jkenney9a


Hi jkenney9a,

Thanks for the update. I am closing this one if nothing else is needed.

Thanks!

Sure thing...if I come up with some way to do this in Python (using pyrealsense2 or some other package) I'll post.

jkenney9a avatar May 07 '19 16:05 jkenney9a

HI jkenney9a, Did you figure it out?

Thanks

Wjordan2020 avatar Jun 10 '20 16:06 Wjordan2020

No...I ended up not needing to solve this problem as we changed how we were handling our data. Sorry I can't be of more help!

jkenney9a avatar Jun 10 '20 19:06 jkenney9a

Thanks for your answer. Did you find a way to extract all frames within the bag file? I spent so much time, but Python keeps skipping most of the frames during the extraction.

Wjordan2020 avatar Jun 11 '20 00:06 Wjordan2020

Yes, you need to tell set the playback so it's not done in real-time. This is the code I used with the key piece being the last line:

`

#Setup pipeline to read in bag file 
pipe = rs.pipeline()
config = rs.config()
config.enable_device_from_file(bag_file, repeat_playback=False)
profile = pipe.start(config)

#Needed so frames don't get dropped during processing:
profile.get_device().as_playback().set_real_time(False)

`

Happy to share more code (I keep meaning to put it up on github). Basically, immediately following recording, we split out the RGB video to extract certain data. Then we merge the extracted data with the corresponding depth data. We do this to track an animal in 3D.

jkenney9a avatar Jun 11 '20 01:06 jkenney9a

Hi waddelat,

Actually, I'm looking back through my code, and I think I may have solved the above problem with the h5 file. I just didn't realize it because we didn't end up using it, but the code is still there. So the key was in creating the file, you can set a maxshape parameter, and so I made the 'z' parameter = None: `

    depth_scale = profile.get_device().first_depth_sensor().get_depth_scale()
    depth_distance_filename = filename + '_distance.h5'
    f_depth_dist = h5py.File(depth_distance_filename, 'w')
    
    depth_data_group = f_depth_dist.create_group('Camera and Video info')
    depth_data = f_depth_dist.create_dataset('distance', 
                                             (resolution['y'], resolution['x'], 1),
                                             dtype='i8', compression='gzip',
                                             maxshape=(resolution['y'], resolution['x'], None))
    
    #Add depth scale and fps as an attribute to the h5 file
    depth_data_group.attrs['Depth Scale'] = depth_scale
    depth_data_group.attrs['FPS'] = fps

`

Then as I'm looping through the video there is a call:

`

        depth = np.asanyarray(depth_frame_aligned.get_data()).astype('uint8')
        depth_data.resize((resolution['y'], resolution['x'], i+1))
        depth_data[:,:,i] = depth

`

It's been awhile since I've used this part of the code, so not sure if it works. But maybe it'll help...

jkenney9a avatar Jun 11 '20 01:06 jkenney9a

Thank you so much. I really appreciate your help. Could you please share with me the code to extract all the depth frames from the bag file. i tried playback.set_real_time(False) but the code is running very slow. Here is the code (Python) i'm using to extract the depth from every frame at specific location:

   import cv2                            
   import numpy as np                        
   import matplotlib.pyplot as plt          
   import pyrealsense2 as rs                 
   import pandas as pd                
   print("Environment Ready")


   i=0
   left=[]
   right=[]
   framek=[]

try:
    config = rs.config()
    rs.config.enable_device_from_file(config, "test2.bag", repeat_playback=False)
    pipeline = rs.pipeline()
    profile = pipeline.start(config)
    playback = profile.get_device().as_playback()
    playback.set_real_time(False)
    
    while True:
        frames = pipeline.wait_for_frames()
        playback.pause()
        depth_frame = frames.get_depth_frame()
        if not depth_frame:
            continue
      
        print("frame# "+str(i))

        n = depth_frame.get_frame_number()
        framek.append(n)
        print(n)
        zDepth_L = depth_frame.get_distance(int(150),int(50))
        zDepth_R = depth_frame.get_distance(int(650),int(50))
        
        left.append(zDepth_L)
        right.append(zDepth_R)
       
        
        print("Left Depth: "+str(zDepth_L))
        print("Right Depth: "+str(zDepth_R))
        
        i +=1
        playback.resume()
    
    print("Frames Captured")


finally:
    # Stop streaming
    pipeline.stop()
    
data = pd.DataFrame(columns = ['Left', 'Right','Frame']) 
data['Left']=pd.Series(left)
data['Right']=pd.Series(right)
data['Frame']=pd.Series(framek)
data.to_csv(r'test.csv')

Wjordan2020 avatar Jun 11 '20 01:06 Wjordan2020

The way your accessing the distance looks okay to me. The only substantive difference I can see in my code is that I don't use a playback.pause() and a playback.resume(), seems like that shouldn't be necessary if you set the realtime playback to false and could slow things down.

I start my looping with:

`

    while True:

              frame_present, frameset = pipe.try_wait_for_frames()
    
              #End loop once video finishes
              if not frame_present:
                  break

`

The other thing you may want to keep in mind is that if the coordinates your are pulling out are based on the RGB image, you are going to get the wrong depth. You need to align the depth frame to the color frame.

I hope that helps!

jkenney9a avatar Jun 11 '20 01:06 jkenney9a