§ 2.4 Gemini2 - 通过OpenCV读取彩图与深度图
1. 导入依赖
import numpy as np
import cv2
from matplotlib import pyplot as plt
# 打印当前OpenCV的版本号
print(cv2.__version__)
4.7.0-dev
注意事项:OpenCV版本必须4.7及其以上。
2. 创建视频对象
# 打开奥比中光相机
capture = cv2.VideoCapture(0, cv2.CAP_OBSENSOR)
# capture = cv2.VideoCapture(0, cv2.CAP_OBSENSOR_)
if capture is None:
print("无效设备ID")
print(f"设备是否打开: {capture.isOpened()}")
输出日志 :
设备是否打开: True
3. 设置相机分辨率
# ## 设置画面的尺寸
# # 画面宽度设定为 1920
# capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
# # 画面高度度设定为 1080
# capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 800)
4. 获取相机内参
fx = capture.get(cv2.CAP_PROP_OBSENSOR_INTRINSIC_FX)
fy = capture.get(cv2.CAP_PROP_OBSENSOR_INTRINSIC_FY)
cx = capture.get(cv2.CAP_PROP_OBSENSOR_INTRINSIC_CX)
cy = capture.get(cv2.CAP_PROP_OBSENSOR_INTRINSIC_CY)
print(f"相机内参: fx {fx} fy {fy} cx {cx} cy {cy}")
输出日志 :
相机内参: fx 516.6519775390625 fy 516.6920166015625 cx 322.9880065917969 cy 235.78700256347656
5. 数据获取
注意事项:每执行一次
grab()
函数,只能使用
retrieve()
函数获取一次彩图与深度图
# 捕获下一帧
ret_grab = capture.grab()
print(f"下一帧是否捕获成功 {ret_grab}")
下一帧是否捕获成功 True
返回捕获到的RGB彩图
ret_bgr, img_bgr = capture.retrieve(flag=cv2.CAP_OBSENSOR_BGR_IMAGE)
print(f"读取RGB图是否成功: {ret_bgr}")
if ret_bgr:
# 注: 获取的RGB图是uint16类型的, 而默认数据类型应该为uint8
# 因此可以做一下类型转换
img_bgr = np.uint8(img_bgr)
print(f"彩图的分辨率: {img_bgr.shape}")
print(f"彩图的数据类型: {img_bgr.dtype}")
# 展示下图像
plt.imshow(img_bgr[:, :, ::-1])
输出日志 :
读取RGB图是否成功: True 彩图的分辨率: (480, 640, 3) 彩图的数据类型: uint8
捕获深度图
ret_depth, img_depth = capture.retrieve(flag=cv2.CAP_OBSENSOR_DEPTH_MAP)
print(f"读取深度图是否成功: {ret_depth}")
if ret_depth:
print(f"深度图的分辨率: {img_depth.shape}")
print(f"深度图数据类型: {img_depth.dtype}")
# 展示下图像
plt.imshow(img_depth)
输出日志 :
读取深度图是否成功: True 深度图的分辨率: (480, 640) 深度图数据类型: uint16