Connect realsense D435 to a PC with ubuntu 16.04 installed and save depth videos with python

Purpose

It is a memorandum when connecting realsense D435 to a PC with ubuntu 16.04 installed and saving a depth video with python.

Preparation

PC with ubuntu 16.04 installed realsenseD435

pyrealsense2 installation

pip install pyrealsense2

code

動画を保存する:record.py 保存した動画を再生する:play.py 保存した動画を連番画像にする:save.py

record.py


import pyrealsense2 as rs
import numpy as np
import cv2
import time
# Configure depth and color streams
config = rs.config()
config.enable_stream(rs.stream.infrared, 1, 640, 480, rs.format.y8, 30)
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_record_to_file('d435data.bag')
# Start streaming
pipeline = rs.pipeline()
pipeline.start(config)
start = time.time()
frame_no = 1
try:
    while True:
        # Wait for a coherent pair of frames: depth and color
        frames = pipeline.wait_for_frames()
        color_frame = frames.get_color_frame()
        depth_frame = frames.get_depth_frame()
        ir_frame = frames.get_infrared_frame()
        fps  = frame_no / (time.time() - start)  
        print(fps)
        frame_no = frame_no+1  
        if not ir_frame or not color_frame  :   
            ir_image = np.asanyarray(ir_frame .get_data())    
            depth_image = np.asanyarray(depth_color_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data()) 

finally:    
    pipeline.stop()

play.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyrealsense2 as rs
import numpy as np
import cv2
#stream(Color/Depth/Infrared)settings of
config = rs.config()
#↓ Set the file name here
config.enable_device_from_file('d435data.bag')
#config.enable_device_from_file('./20191229.bag')
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.infrared, 1, 640, 480, rs.format.y8, 30)

#Start streaming
pipeline = rs.pipeline()
profile = pipeline.start(config)

try:
    while True:
        #Waiting for a frame(Color & Depth)
        frames = pipeline.wait_for_frames()
        ir_frame = frames.get_infrared_frame()
        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()
        if not depth_frame or not color_frame or not ir_frame  :
            continue

        # Convert images to numpy arrays
        ir_image = np.asanyarray(ir_frame .get_data())
        depth_color_frame = rs.colorizer().colorize(depth_frame)
        depth_image = np.asanyarray(depth_color_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())       
        # Show images
        cv2.namedWindow('ir_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('ir_image', ir_image)
        cv2.namedWindow('color_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('color_image', color_image)
        cv2.namedWindow('depth_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('depth_image', depth_image)
        cv2.waitKey(1)
finally:

    # Stop streaming
    pipeline.stop()

save.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyrealsense2 as rs
import numpy as np
import cv2
#stream(Color/Depth/Infrared)settings of
config = rs.config()
#↓ Set the file name here
config.enable_device_from_file('d435data.bag')
#config.enable_device_from_file('./20191229.bag')
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.infrared, 1, 640, 480, rs.format.y8, 30)

#Start streaming
pipeline = rs.pipeline()
profile = pipeline.start(config)

try:
    count = 0
    while True:
        count_padded = '%05d' % count
        count += 1
        
        #Waiting for a frame(Color & Depth)
        frames = pipeline.wait_for_frames()
        ir_frame = frames.get_infrared_frame()
        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()
        if not depth_frame or not color_frame or not ir_frame  :
            continue

        # Convert images to numpy arrays
        ir_image = np.asanyarray(ir_frame .get_data())
        depth_color_frame = rs.colorizer().colorize(depth_frame)
        depth_image = np.asanyarray(depth_color_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())

        write_file_name_color = "color_" + count_padded + ".jpg "
        cv2.imwrite(write_file_name_color, color_image)
        write_file_name_depth = "depth_" + count_padded + ".jpg "
        cv2.imwrite(write_file_name_depth, depth_image)
        
        # Show images
        cv2.namedWindow('ir_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('ir_image', ir_image)
        cv2.namedWindow('color_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('color_image', color_image)
        cv2.namedWindow('depth_image', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('depth_image', depth_image)
        cv2.waitKey(1)
finally:

    # Stop streaming
    pipeline.stop()

Other

To convert the saved image to a video Generate a video from a serial number image with ffmpeg / Generate a serial number image from a video ~ To prevent dropped frames ~ Seems to be good.

Coding Error measures

I am running with python2.7 series, but if it is more than that, an error may occur. ..

reference

Running Intel's Realsense D435 Record and output with Intel Realsense D435 3D sensing starting with Python !! Generate video from serial number image with ffmpeg / Generate serial number image from video ~ How to prevent dropped frames ~

Recommended Posts

Connect realsense D435 to a PC with ubuntu 16.04 installed and save depth videos with python
Connect a commercially available webcam to a PC with ubuntu 16.04 installed via USB and capture video with python
Ssh connect to Cisco Catalyst with CentOS7 + Python3 + netmiko and save config locally
Try to operate DB with Python and visualize with d3
[Python] How to create a 2D histogram with Matplotlib
Connect to BigQuery with Python
Connect to Wikipedia with Python
Try to bring up a subwindow with PyQt5 and Python
Operate Jupyter with REST API to extract and save Python code
Process Splunk execution results using Python and save to a file
Solve ABC166 A ~ D with Python
I tried to make a periodical process with Selenium and Python
I wanted to solve the ABC164 A ~ D problem with Python
[Python] How to save the installed package and install it in a new environment at once Mac environment
Connect to postgreSQL from Python and use stored procedures in a loop.
I get a UnicodeDecodeError when trying to connect to oracle with python sqlalchemy
[Pyenv] Building a python environment with ubuntu 16.04
How to split and save a DataFrame
[Python] How to convert a 2D list to a 1D list
Fractal to make and play with Python
Connect a lot of Python or and and
Connect to MySQL with Python within Docker
I installed and used Numba with Python3.5
Solve AtCoder ABC168 with python (A ~ D)
Connect to s3 with AWS Lambda Python
Python) Save scraping content to local PC
Connect to pepper with PEPPER Mac's python interpreter
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
WEB scraping with python and try to make a word cloud from reviews
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
How to read a CSV file with Python 2/3
Scraping tabelog with python and outputting to CSV
Automatically search and download YouTube videos with Python
Send a message to LINE with Python (LINE Notify)
MessagePack-Try to link Java and Python with RPC
Connect Scratch X and Digispark with a bottle
Building a python environment with virtualenv and direnv
I want to make a game with Python
Try to communicate with EV3 and PC! (MQTT)
Try to make a "cryptanalysis" cipher with Python
Solve A ~ D of yuki coder 247 with python
Decide to assign a laboratory with Python (fiction)
Steps to create a Twitter bot with python
Launch a web server with Python and Flask
Save the object to a file with pickle
Try to make a dihedral group with Python
[Dedicated to Telewa! ] PC operation with a webcam
I want to write to a file with Python
A layman wants to get started with Python
Connect to MySQL with Python on Raspberry Pi
Perform a Twitter search from Python and try to generate sentences with Markov chains.
I made a program to convert images into ASCII art with Python and OpenCV
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
How to convert / restore a string with [] in python
Procedure to load MNIST with python and output to png
A memo connected to HiveServer2 of EMR with python
A story about making 3D space recognition with Python
Get media timeline images and videos with Python + Tweepy