quick_start.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """快速预览示例。
  2. 同时显示彩色图与深度伪彩图,便于验证相机连接和图像质量。
  3. """
  4. import time
  5. import cv2
  6. import numpy as np
  7. from pyorbbecsdk import *
  8. from utils import frame_to_bgr_image
  9. ESC_KEY = 27
  10. MIN_DEPTH = 20 # 20mm
  11. MAX_DEPTH = 10000 # 10000mm
  12. def main():
  13. """启动实时预览窗口。"""
  14. pipeline = Pipeline()
  15. pipeline.start()
  16. print("Pipeline started successfully. Press 'q' or ESC to exit.")
  17. # 设置窗口大小,左右并排展示彩色图和深度图。
  18. window_width = 1280
  19. window_height = 720
  20. cv2.namedWindow("QuickStart Viewer", cv2.WINDOW_NORMAL)
  21. cv2.resizeWindow("QuickStart Viewer", window_width, window_height)
  22. while True:
  23. try:
  24. frames = pipeline.wait_for_frames(100)
  25. if frames is None:
  26. continue
  27. # 读取彩色帧并转换为 OpenCV BGR 图像。
  28. color_frame = frames.get_color_frame()
  29. if color_frame is None:
  30. continue
  31. color_image = frame_to_bgr_image(color_frame)
  32. # 读取深度帧并校验格式。
  33. depth_frame = frames.get_depth_frame()
  34. if depth_frame is None:
  35. continue
  36. if depth_frame.get_format() != OBFormat.Y16:
  37. print("Depth format is not Y16")
  38. continue
  39. # 深度数据预处理:重塑、按 scale 转毫米、过滤区间外像素。
  40. width = depth_frame.get_width()
  41. height = depth_frame.get_height()
  42. scale = depth_frame.get_depth_scale()
  43. depth_data = np.frombuffer(depth_frame.get_data(), dtype=np.uint16).reshape((height, width))
  44. depth_data = depth_data.astype(np.float32) * scale
  45. depth_data = np.where((depth_data > MIN_DEPTH) & (depth_data < MAX_DEPTH), depth_data, 0).astype(np.uint16)
  46. # 深度伪彩可视化。
  47. depth_image = cv2.normalize(depth_data, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
  48. depth_image = cv2.applyColorMap(depth_image, cv2.COLORMAP_JET)
  49. # 缩放并拼接:左彩色、右深度。
  50. color_image_resized = cv2.resize(color_image, (window_width // 2, window_height))
  51. depth_image_resized = cv2.resize(depth_image, (window_width // 2, window_height))
  52. combined_image = np.hstack((color_image_resized, depth_image_resized))
  53. cv2.imshow("QuickStart Viewer", combined_image)
  54. if cv2.waitKey(1) in [ord("q"), ESC_KEY]:
  55. break
  56. except KeyboardInterrupt:
  57. break
  58. cv2.destroyAllWindows()
  59. pipeline.stop()
  60. print("Pipeline stopped and all windows closed.")
  61. if __name__ == "__main__":
  62. main()