#include <librealsense2/rs.hpp>
#include <opencv2/opencv.hpp>
#include <thread>
void capture_thread(rs2::pipeline pipe, rs2::frame_queue& queue) {
while (true) {
rs2::frameset frameset = pipe.wait_for_frames();
queue.enqueue(frameset);
}
}
void process_thread(rs2_intrinsics color_intrinsics, rs2_intrinsics depth_intrinsics, rs2::frame_queue& queue) {
cv::namedWindow("color", cv::WINDOW_NORMAL);
cv::resizeWindow("color", color_intrinsics.width, color_intrinsics.height);
cv::namedWindow("depth", cv::WINDOW_NORMAL);
cv::resizeWindow("depth", depth_intrinsics.width, depth_intrinsics.height);
while (cv::getWindowProperty("color", cv::WND_PROP_AUTOSIZE) >= 0 && cv::getWindowProperty("depth", cv::WND_PROP_AUTOSIZE) >= 0) {
rs2::frameset frameset;
if (queue.poll_for_frame(&frameset)) {
rs2::frame color_frame = frameset.get_color_frame();
rs2::frame depth_frame = frameset.get_depth_frame();
cv::Mat color_image(cv::Size(color_intrinsics.width, color_intrinsics.height), CV_8UC3, (void*)color_frame.get_data(), cv::Mat::AUTO_STEP);
cv::Mat depth_image(cv::Size(depth_intrinsics.width, depth_intrinsics.height), CV_16UC1, (void*)depth_frame.get_data(), cv::Mat::AUTO_STEP);
// 在这里对每一帧图像进行处理
cv::Mat processed_color_image;
cv::cvtColor(color_image, processed_color_image, cv::COLOR_BGR2GRAY);
cv::Mat processed_depth_image = depth_image * 10;
// 显示处理后的图像
cv::imshow("color", processed_color_image);
cv::imshow("depth", processed_depth_image);
}
cv::waitKey(1);
}
}
int main() {
// 初始化 SDK
rs2::context ctx;
// 连接设备
rs2::device_list devices = ctx.query_devices();
if (devices.size() == 0) {
std::cerr << "Error: no device detected" << std::endl;
return 1;
}
rs2::device device = devices[0];
// 配置流
rs2::config cfg;
cfg.enable_stream(rs2_stream::RS2_STREAM_COLOR, 640, 480, rs2_format::RS2_FORMAT_BGR8, 30);
cfg.enable_stream(rs2_stream::RS2_STREAM_DEPTH, 640, 480, rs2_format::RS2_FORMAT_Z16, 30);
// 开始流
rs2::pipeline pipe;
rs2::pipeline_profile profile = pipe.start(cfg);
// 获取相机内参
rs2::video_stream_profile color_profile = profile.get_stream(rs2_stream::RS2_STREAM_COLOR).as<rs2::video_stream_profile>();
rs2_intrinsics color_intrinsics = color_profile.get_intrinsics();
rs2::video_stream_profile depth_profile = profile.get_stream(rs2_stream::RS2_STREAM_DEPTH).as<rs2::video_stream_profile>();
rs2_intrinsics depth_intrinsics = depth_profile.get_intrinsics();
// 创建队列并启动线程
rs2::frame_queue queue;
std::thread capture_thread_obj(capture_thread, pipe, std::ref(queue));
std::thread process_thread_obj(process_thread, color_intrinsics, depth_intrinsics, std::ref(queue));
// 等待线程结束
capture_thread_obj.join();
process_thread_obj.join();
// 停止流
pipe.stop();
return 0;
}