69 lines
1.8 KiB
Python
Executable File
69 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
查看相机画面的简单脚本
|
||
按空格键保存当前帧,按'q'键退出
|
||
"""
|
||
import sys
|
||
import cv2
|
||
import numpy as np
|
||
try:
|
||
import pyrealsense2 as rs
|
||
except ImportError:
|
||
print("错误: 未安装pyrealsense2,请运行: pip install pyrealsense2")
|
||
sys.exit(1)
|
||
|
||
def main():
|
||
# 配置相机
|
||
pipeline = rs.pipeline()
|
||
config = rs.config()
|
||
|
||
# 启用彩色流
|
||
config.enable_stream(rs.stream.color, 640, 480, rs.format.rgb8, 30)
|
||
|
||
# 启动管道
|
||
pipeline.start(config)
|
||
print("相机已启动,按空格键保存图片,按'q'键退出")
|
||
|
||
frame_count = 0
|
||
try:
|
||
while True:
|
||
# 等待一帧
|
||
frames = pipeline.wait_for_frames()
|
||
color_frame = frames.get_color_frame()
|
||
|
||
if not color_frame:
|
||
continue
|
||
|
||
# 转换为numpy数组 (RGB格式)
|
||
color_image = np.asanyarray(color_frame.get_data())
|
||
|
||
# OpenCV使用BGR格式,需要转换
|
||
bgr_image = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR)
|
||
|
||
# 显示图像
|
||
cv2.imshow('Camera View', bgr_image)
|
||
|
||
# 等待按键
|
||
key = cv2.waitKey(1) & 0xFF
|
||
|
||
if key == ord('q'):
|
||
print("退出...")
|
||
break
|
||
elif key == ord(' '): # 空格键保存
|
||
frame_count += 1
|
||
filename = f'camera_frame_{frame_count:04d}.jpg'
|
||
cv2.imwrite(filename, bgr_image)
|
||
print(f"已保存: {filename}")
|
||
|
||
except KeyboardInterrupt:
|
||
print("\n中断...")
|
||
finally:
|
||
pipeline.stop()
|
||
cv2.destroyAllWindows()
|
||
print("相机已关闭")
|
||
|
||
if __name__ == '__main__':
|
||
main()
|
||
|
||
|