| import pyrealsense2 as rs
|
| import numpy as np
|
| import cv2
|
| import os
|
| import time
|
| import paramiko
|
| from datetime import datetime
|
|
|
|
|
| SERVER_CONFIG = {
|
| 'host': '10.103.69.239',
|
| 'port': 27277,
|
| 'username': 'chubin',
|
| 'password': 'ZQSg7YOAeCqGPRky=Aa0#',
|
| 'remote_dir': '/mnt/disk_3/chubin/img/'
|
| }
|
|
|
| def configure_camera():
|
|
|
| pipeline = rs.pipeline()
|
| config = rs.config()
|
|
|
|
|
| config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
|
| config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
|
|
|
|
|
| profile = pipeline.start(config)
|
|
|
|
|
| depth_sensor = profile.get_device().first_depth_sensor()
|
| depth_scale = depth_sensor.get_depth_scale()
|
| print(f"深度比例系数为: {depth_scale}")
|
|
|
|
|
| align_to = rs.stream.color
|
| align = rs.align(align_to)
|
|
|
| return pipeline, align, profile
|
|
|
| def create_video_writer(width, height, fps=30):
|
| """创建视频写入器,用于保存彩色和深度视频"""
|
|
|
| if not os.path.exists("videos"):
|
| os.makedirs("videos")
|
|
|
|
|
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| color_filename = f"videos/color_{timestamp}.avi"
|
| depth_filename = f"videos/depth_{timestamp}.avi"
|
|
|
|
|
| fourcc = cv2.VideoWriter_fourcc(*'XVID')
|
| color_out = cv2.VideoWriter(color_filename, fourcc, fps, (width, height))
|
| depth_out = cv2.VideoWriter(depth_filename, fourcc, fps, (width, height))
|
|
|
|
|
| if not color_out.isOpened():
|
| raise Exception(f"无法创建彩色视频文件: {color_filename}")
|
| if not depth_out.isOpened():
|
| raise Exception(f"无法创建深度视频文件: {depth_filename}")
|
|
|
| print(f"视频将保存到:")
|
| print(f" 彩色视频: {color_filename}")
|
| print(f" 深度视频: {depth_filename}")
|
|
|
| return color_out, depth_out
|
|
|
| def create_sftp_connection(server_config):
|
| """创建并返回SSH和SFTP连接对象"""
|
| try:
|
|
|
| ssh = paramiko.SSHClient()
|
|
|
| ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
|
| ssh.connect(
|
| server_config['host'],
|
| port=server_config['port'],
|
| username=server_config['username'],
|
| password=server_config['password']
|
| )
|
|
|
|
|
| sftp = ssh.open_sftp()
|
|
|
|
|
| try:
|
| sftp.stat(server_config['remote_dir'])
|
| except FileNotFoundError:
|
| sftp.mkdir(server_config['remote_dir'])
|
| print(f"已创建远程目录: {server_config['remote_dir']}")
|
|
|
| print("SFTP连接已建立")
|
| return ssh, sftp
|
| except Exception as e:
|
| print(f"创建SFTP连接时发生错误: {e}")
|
|
|
| if 'ssh' in locals():
|
| ssh.close()
|
| raise
|
|
|
| def upload_to_server(sftp, local_path, remote_path):
|
| """通过已建立的SFTP连接上传文件"""
|
| try:
|
|
|
| sftp.put(local_path, remote_path)
|
| print(f"文件 {local_path} 已成功上传到 {remote_path}")
|
| return True
|
| except Exception as e:
|
| print(f"上传文件时发生错误: {e}")
|
| return False
|
|
|
| def main():
|
|
|
| ssh = None
|
| sftp = None
|
| pipeline = None
|
| color_out = None
|
| depth_out = None
|
|
|
| try:
|
|
|
| pipeline, align, profile = configure_camera()
|
|
|
|
|
| color_stream = profile.get_stream(rs.stream.color)
|
| video_profile = color_stream.as_video_stream_profile()
|
| width, height = video_profile.width(), video_profile.height()
|
|
|
|
|
| color_out, depth_out = create_video_writer(width, height)
|
|
|
|
|
| if not os.path.exists("captures"):
|
| os.makedirs("captures")
|
|
|
|
|
| ssh, sftp = create_sftp_connection(SERVER_CONFIG)
|
|
|
| print("正在录制视频... 按 's' 停止录制,按 'q' 退出程序")
|
|
|
| recording = True
|
| last_capture_time = 0
|
| capture_interval = 5
|
|
|
|
|
| cv2.namedWindow('RealSense - 彩色 (左) | 深度 (右)', cv2.WINDOW_AUTOSIZE)
|
|
|
| while True:
|
|
|
| frames = pipeline.wait_for_frames()
|
|
|
|
|
| aligned_frames = align.process(frames)
|
|
|
|
|
| aligned_depth_frame = aligned_frames.get_depth_frame()
|
| color_frame = aligned_frames.get_color_frame()
|
|
|
|
|
| if not aligned_depth_frame or not color_frame:
|
| continue
|
|
|
|
|
| depth_image = np.asanyarray(aligned_depth_frame.get_data())
|
| color_image = np.asanyarray(color_frame.get_data())
|
|
|
|
|
| depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
|
|
|
|
|
| if recording:
|
| cv2.putText(color_image, "REC", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
|
| cv2.putText(depth_colormap, "REC", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
|
|
|
|
|
| if recording:
|
| color_out.write(color_image)
|
| depth_out.write(depth_colormap)
|
|
|
|
|
| current_time = time.time()
|
| if current_time - last_capture_time >= capture_interval:
|
|
|
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
| color_capture_path = f"captures/color_capture_{timestamp}.jpg"
|
| depth_capture_path = f"captures/depth_capture_{timestamp}.jpg"
|
|
|
|
|
| cv2.imwrite(color_capture_path, color_image)
|
| cv2.imwrite(depth_capture_path, depth_colormap)
|
| print(f"已保存截图: {color_capture_path}, {depth_capture_path}")
|
|
|
|
|
| if recording and sftp is not None:
|
| remote_color_path = os.path.join(SERVER_CONFIG['remote_dir'], f"color_capture_{timestamp}.jpg")
|
| remote_depth_path = os.path.join(SERVER_CONFIG['remote_dir'], f"depth_capture_{timestamp}.jpg")
|
|
|
|
|
| color_success = upload_to_server(sftp, color_capture_path, remote_color_path)
|
| depth_success = upload_to_server(sftp, depth_capture_path, remote_depth_path)
|
|
|
|
|
| if color_success:
|
| os.remove(color_capture_path)
|
| if depth_success:
|
| os.remove(depth_capture_path)
|
|
|
|
|
| last_capture_time = current_time
|
|
|
|
|
| cv2.imshow('RealSense - 彩色 (左) | 深度 (右)', np.hstack((color_image, depth_colormap)))
|
|
|
|
|
| key = cv2.waitKey(1)
|
| if key & 0xFF == ord('q'):
|
| break
|
| elif key & 0xFF == ord('s'):
|
| recording = not recording
|
| status = "继续录制" if recording else "暂停录制"
|
| print(status)
|
|
|
| except Exception as e:
|
| print(f"发生错误: {e}")
|
| finally:
|
|
|
| if sftp is not None:
|
| try:
|
| sftp.close()
|
| print("SFTP连接已关闭")
|
| except Exception as e:
|
| print(f"关闭SFTP连接时发生错误: {e}")
|
|
|
|
|
| if ssh is not None:
|
| try:
|
| ssh.close()
|
| print("SSH连接已关闭")
|
| except Exception as e:
|
| print(f"关闭SSH连接时发生错误: {e}")
|
|
|
|
|
| if color_out is not None:
|
| color_out.release()
|
| if depth_out is not None:
|
| depth_out.release()
|
|
|
|
|
| if pipeline is not None:
|
| pipeline.stop()
|
|
|
|
|
| cv2.destroyAllWindows()
|
| print("视频录制已结束,文件已保存。")
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|