§ 2.5 彩图获取与动态更新
1. 导入依赖
# - 矩阵运算
import numpy as np
# - 图像处理
import cv2
# - Open3D点云处理
import open3d as o3d
# - 绘图可视化
from matplotlib import pyplot as plt
# 自定义库
# 从阿凯机器人工具箱导入Astra类
from kyle_robot_toolbox.camera import Astra
2. 相机初始化
将视频流初始化为彩图模式
"color"
# 创建相机对象
# config_path要写的是Astra 3D相机的配置文件夹路径
camera = Astra(config_path="../astra-config/config/")
# 初始相机视频流
camera.init_video_stream(video_mode="color")
如果想要去除相机畸变,则需要载入相机标定参数。
# 读取相机参数(相机内参)
camera.load_cam_calib_data()
3. 获取彩图
读取彩图,图像的色彩空间为BGR。
# 采集彩图, 色彩空间BGR
img_bgr = camera.read_color_img()
4. 显示彩图
在Jupyter Notebook里,通过Matplotlib显示彩图
# 显示画面
# 将图像从BGR空间转换为RGB空间
plt.imshow(img_bgr[:, :, ::-1])
5. 去除畸变
# 图像移除畸变
img_bgr_undistor = camera.rgb_camera.remove_distortion(img_bgr)
# 显示去除畸变的彩图
plt.imshow(img_bgr_undistor[:, :, ::-1])
6. 保存彩图
在脚本所在的文件夹里,创建
data
文件夹,
data
文件夹里创建文件夹
read_color_image
用于存储本案例的数据。
# 图像保存路径
img_path = "data/read_color_image/demo.png"
# 图像保存
ret = cv2.imwrite(img_path, img_bgr)
# 输出日志
if ret:
print("图像保存成功")
else:
print("检查图像保存路径是否存在,且路径不可以有中文。")
输出日志:
图像保存成功
7. 读取彩图
# 图像保存路径
img_path = "data/read_color_image/demo.png"
# 图像载入
img_bgr2 = cv2.imread(img_path)
if img_bgr2 is None:
print("图像读取失败")
else:
print("图片读取成功")
输出日志:
图片读取成功
# 显示从文件里读取的彩图
plt.imshow(img_bgr2[:, :, ::-1])
8. 关闭Jupyter Notebook脚本
Astra相机设备,每次只能被一个程序使用。如果要运行新的脚本,需要将原有的Jupyter Notebook关闭。
Jupyter Notebook脚本关闭后:
9. 彩图动态刷新
在终端里面运行彩图动态刷新的示例代码:
python read_color_img.py
read_color_img.py
'''
Astra 3D相机 - 测试彩图读取与动态更新
----------------------------------------------
@作者: 阿凯爱玩机器人
@QQ: 244561792
@微信: xingshunkai
@邮箱: xingshunkai@qq.com
@网址: deepsenserobot.com
@B站: "阿凯爱玩机器人"
'''
# - 矩阵运算
import numpy as np
# - 图像处理
import cv2
# - Open3D点云处理
import open3d as o3d
# - 绘图可视化
from matplotlib import pyplot as plt
# 自定义库
# 从阿凯机器人工具箱导入Astra类
from kyle_robot_toolbox.camera import Astra
# 配置项
# - 移除图像畸变
rm_distortion = False
# 创建相机对象
# config_path要写的是Astra 3D相机的配置文件夹路径
camera = Astra(config_path="../astra-config/config/")
try:
# 初始相机视频流
camera.init_video_stream(video_mode="color")
except Exception as e:
print("[错误] 没有发现Astra设备, 请检查接线或驱动")
exit(-1)
if rm_distortion:
# 读取相机参数(相机内参)
camera.load_cam_calib_data()
# 创建窗口
win_flag = cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED
cv2.namedWindow("color", flags=win_flag)
while True:
# 采集彩图, 色彩空间BGR
img_bgr = camera.read_color_img()
# 去除彩图畸变
if rm_distortion:
img_bgr = camera.rgb_camera.remove_distortion(img_bgr)
# 显示图像
cv2.imshow('color', img_bgr)
key = cv2.waitKey(1)
if key == ord('q'):
# 如果按键为q 代表quit 退出程序
break
# 关闭摄像头
camera.release()
# 销毁所有的窗口
cv2.destroyAllWindows()