处理思路:通过realsense D435相机返回的深度距离值,获取自定义深度距离范围内的所有点,并在创建的图像中以自定义的颜色显示出来。
具体代码如下:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <librealsense2/rs.hpp>
#include <librealsense2/rsutil.h>
#include <iostream>
#include <sstream>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace cv;
using namespace std;
using namespace rs2;
float get_depth_scale(device dev) //获取深度像素对应长度单位(米)的换算比例
{
for (sensor& sensor : dev.query_sensors()) //检查设备的传感器
{
if (depth_sensor dpt = sensor.as<depth_sensor>()) //检查传感器是否为深度传感器
{
return dpt.get_depth_scale();
}
}
}
Mat depth_interception(Mat depth,pipeline_profile profile) //深度截取函数
{
float depth_scale = get_depth_scale(profile.get_device()); //获取深度像素与现实单位比例
Mat roi_img (depth.rows, depth.cols, CV_8UC3, Scalar::all(0));
for(int row=0;row<depth.rows;row++) //对深度图像遍历
{
for(int col=0;col<depth.cols;col++)
{
uint16_t depth_value=depth.at<uint16_t>(row,col); //取当前点对应的深度值
float depth_m = depth_value*depth_scale;
if( depth_m >0.3 && depth_m < 0.5) //自定义深度范围
{
roi_img.at<Vec3b>(row,col)[0]=250; //自定义颜色
roi_img.at<Vec3b>(row,col)[1]=5;
roi_img.at<Vec3b>(row,col)[2]=55;
}
}
}
return roi_img;
}
int main()
{
colorizer color_map; //帮助着色深度图像
pipeline pipe; //创建数据管道
config pipe_config;
pipe_config.enable_stream(RS2_STREAM_DEPTH,640,480,RS2_FORMAT_Z16,30);
pipe_config.enable_stream(RS2_STREAM_COLOR,640,480,RS2_FORMAT_BGR8,30);
pipeline_profile profile = pipe.start(pipe_config); //start()函数返回数据管道的profile
while (1)
{
frameset frameset = pipe.wait_for_frames(); //堵塞程序直到新的一帧捕获
frame depth_frame = frameset.get_depth_frame(); //取深度图
frame depth_frame_tee = frameset.get_depth_frame().apply_filter(color_map);
const int depth_w=depth_frame.as<video_frame>().get_width(); //获取宽高
const int depth_h=depth_frame.as<video_frame>().get_height();
Mat depth_image(Size(depth_w,depth_h), //创建OPENCV类型 并传入数据
CV_16U,(void*)depth_frame.get_data(),Mat::AUTO_STEP);
Mat depth_image_tee(Size(depth_w,depth_h),
CV_8UC3,(void*)depth_frame_tee.get_data(),Mat::AUTO_STEP);
Mat result = depth_interception(depth_image,profile); //实现深度截取
imshow("depth_image",depth_image_tee);
imshow("result",result);
int key = waitKey(1);
if(char(key) == 27)break;
}
return 0;
}
更多资料请点击:我的目录