CmvrControlStation/patches/cmvr-es-metric-rgbd.patch

279 lines
15 KiB
Diff

diff --git a/cmvr-es/devices/camera/abstract_camera.h b/cmvr-es/devices/camera/abstract_camera.h
index d807b658..a0e1f224 100644
--- a/cmvr-es/devices/camera/abstract_camera.h
+++ b/cmvr-es/devices/camera/abstract_camera.h
@@ -26,6 +26,14 @@ namespace cmvr::device {
float coeffs[5]{};
};
+ struct RgbdGeometry {
+ double metres_per_unit = 0;
+ bool aligned_to_color = false;
+ bool color_axial_z = false;
+ std::string distortion_model;
+ int64_t color_capture_utc_ns = 0;
+ int64_t depth_capture_utc_ns = 0;
+ };
struct StreamFrameData
{
//原始图像数据
@@ -102,6 +110,9 @@ namespace cmvr::device {
virtual void getRGBImage(cv::Mat &color, Rs2Intrinsics& intrinsics) {}
virtual void getDepthImage(cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
virtual void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) {}
+ // Unsupported drivers deliberately return no metric geometry.
+ virtual void getMetricRGBDImages(cv::Mat &color, cv::Mat &depth,
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) {}
virtual void startRecording(const std::string &video_path) {}
virtual void stopRecording() {}
virtual void pauseRecording() {}
diff --git a/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h b/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
index ec700d96..597b9814 100644
--- a/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
+++ b/cmvr-es/devices/camera/realsense_camera/include/realsense_camera.h
@@ -28,6 +28,8 @@ namespace cmvr::device{
void getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) override;
void getDepthImage(cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
void getRGBDImages(cv::Mat &color, cv::Mat &depth, Rs2Intrinsics& intrinsics) override;
+ void getMetricRGBDImages(cv::Mat &color, cv::Mat &depth,
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) override;
void startRecording(const std::string &video_path) override;
void stopRecording() override;
void pauseRecording() override;
@@ -71,6 +73,7 @@ namespace cmvr::device{
rs2_intrinsics intrinsics_;
std::mutex frame_mtx_;
+ rs2::frameset latest_metric_frames_; // Owned SDK frames before display alignment.
cv::Mat dist_coeffs_;
cv::Mat latest_rgb_;
diff --git a/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp b/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
index a22918c1..4733b7f4 100644
--- a/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
+++ b/cmvr-es/devices/camera/realsense_camera/src/realsense_camera.cpp
@@ -6,6 +6,9 @@
#include "../include/realsense_camera.h"
#include <cstring>
+#include <cmath>
+#include <stdexcept>
+#include <librealsense2/rsutil.h>
using namespace std;
using namespace cmvr::device;
@@ -232,6 +235,14 @@ bool RealsenseCamera::start() {
// 使用相同的同步策略启动
profile_ = pipe_.start(rs_cfg_);
+ for (auto sensor : profile_.get_device().query_sensors()) {
+ try {
+ if (sensor.supports(RS2_OPTION_GLOBAL_TIME_ENABLED))
+ sensor.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, 1.f);
+ } catch (const rs2::error& e) {
+ CMVR_LOG(WARNING) << "Metric RGBD global time unavailable: " << e.what();
+ }
+ }
if (stream_mode_ == RGBD_MODE){
auto sp_depth = profile_.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>();
@@ -350,6 +361,126 @@ bool RealsenseCamera::stop() {
return true;
}
+void RealsenseCamera::getMetricRGBDImages(cv::Mat& color, cv::Mat& depth,
+ Rs2Intrinsics& intrinsics, RgbdGeometry& geometry) {
+ rs2::frameset frames;
+ {
+ std::lock_guard lock(ctrl_mtx_);
+ if (!state_.is_opened || stream_mode_ != RGBD_MODE)
+ throw std::runtime_error("Metric RGBD requires an opened RGBD camera");
+ if (state_.is_streaming) {
+ std::lock_guard<std::mutex> frame_lock(frame_mtx_);
+ frames = latest_metric_frames_;
+ } else {
+ frames = get_frameset(false);
+ }
+ }
+ if (!frames) throw std::runtime_error("Waiting for a complete RGBD frameset");
+ const auto rgb = frames.get_color_frame();
+ const auto raw = frames.get_depth_frame();
+ if (!rgb || !raw) throw std::runtime_error("RGBD frameset is incomplete");
+ const auto capture = [](const rs2::frame& frame) -> int64_t {
+ const auto domain = frame.get_frame_timestamp_domain();
+ const double ms = frame.get_timestamp();
+ if ((domain != RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME && domain != RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)
+ || !std::isfinite(ms) || ms <= 0 || ms > 9e12)
+ throw std::runtime_error("RGBD requires SDK global/system capture timestamps");
+ return static_cast<int64_t>(ms * 1000000.0);
+ };
+ geometry.color_capture_utc_ns = capture(rgb);
+ geometry.depth_capture_utc_ns = capture(raw);
+ if (std::abs(geometry.color_capture_utc_ns - geometry.depth_capture_utc_ns) > 33000000)
+ throw std::runtime_error("RGB and depth captures differ by more than 33 ms");
+ const auto color_profile = rgb.get_profile().as<rs2::video_stream_profile>();
+ const auto depth_profile = raw.get_profile().as<rs2::video_stream_profile>();
+ auto kc = color_profile.get_intrinsics();
+ const auto kd = depth_profile.get_intrinsics();
+ if (kc.model != RS2_DISTORTION_NONE && kc.model != RS2_DISTORTION_BROWN_CONRADY
+ && kc.model != RS2_DISTORTION_MODIFIED_BROWN_CONRADY
+ && kc.model != RS2_DISTORTION_INVERSE_BROWN_CONRADY)
+ throw std::runtime_error("Unsupported RGB distortion model: " + std::to_string(kc.model));
+ if (kd.model != RS2_DISTORTION_NONE && kd.model != RS2_DISTORTION_BROWN_CONRADY
+ && kd.model != RS2_DISTORTION_INVERSE_BROWN_CONRADY)
+ throw std::runtime_error("Unsupported depth deprojection model");
+ const auto extrinsics = depth_profile.get_extrinsics_to(color_profile);
+ const double scale = raw.get_units(); // Real sensor units, never assume millimetres.
+ if (!std::isfinite(scale) || scale <= 0 || scale > .1)
+ throw std::runtime_error("Invalid sensor depth units");
+ if (rgb.get_profile().format() != RS2_FORMAT_BGR8 || raw.get_profile().format() != RS2_FORMAT_Z16)
+ throw std::runtime_error("Metric RGBD requires BGR8 and Z16 sensor frames");
+ color = cv::Mat(rgb.get_height(), rgb.get_width(), CV_8UC3,
+ const_cast<void*>(rgb.get_data()), rgb.get_stride_in_bytes()).clone();
+ cv::Mat valid_color;
+ if (kc.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY
+ && std::all_of(std::begin(kc.coeffs),std::end(kc.coeffs),[](float v) { return v==0.f; }))
+ kc.model = RS2_DISTORTION_NONE;
+ if (kc.model == RS2_DISTORTION_MODIFIED_BROWN_CONRADY
+ || kc.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY) {
+ // These models differ from OpenCV's standard Brown. Rectify with SDK
+ // geometry, then project depth into the same pinhole image.
+ const auto original = kc;
+ cv::Mat map_x(color.size(), CV_32FC1), map_y(color.size(), CV_32FC1);
+ valid_color = cv::Mat::zeros(color.size(), CV_8UC1);
+ for (int y = 0; y < color.rows; ++y) for (int x = 0; x < color.cols; ++x) {
+ const float ray[3] = {(x-kc.ppx)/kc.fx, (y-kc.ppy)/kc.fy, 1.f};
+ float uv[2];
+ bool converged = true;
+ if (original.model == RS2_DISTORTION_INVERSE_BROWN_CONRADY) {
+ // Inverse Brown supports SDK deprojection. Find the source
+ // pixel whose SDK ray matches this rectified pinhole ray.
+ uv[0]=float(x); uv[1]=float(y); converged=false;
+ for (int iteration=0; iteration<12; ++iteration) {
+ float actual[3]; rs2_deproject_pixel_to_point(actual,&original,uv,1.f);
+ const float dx=(ray[0]-actual[0])*original.fx;
+ const float dy=(ray[1]-actual[1])*original.fy;
+ if (!std::isfinite(dx)||!std::isfinite(dy)) break;
+ if (std::abs(dx)<.001f && std::abs(dy)<.001f) { converged=true; break; }
+ uv[0]+=dx; uv[1]+=dy;
+ }
+ } else rs2_project_point_to_pixel(uv, &original, ray);
+ if (!converged) { uv[0]=-1.f; uv[1]=-1.f; }
+ map_x.at<float>(y,x) = uv[0]; map_y.at<float>(y,x) = uv[1];
+ if (std::isfinite(uv[0]) && std::isfinite(uv[1]) && uv[0]>=0 && uv[1]>=0
+ && uv[0]<color.cols-1 && uv[1]<color.rows-1)
+ valid_color.at<uint8_t>(y,x) = 1;
+ }
+ cv::Mat rectified;
+ cv::remap(color, rectified, map_x, map_y, cv::INTER_LINEAR, cv::BORDER_CONSTANT);
+ color = rectified;
+ kc.model = RS2_DISTORTION_NONE;
+ std::fill(std::begin(kc.coeffs), std::end(kc.coeffs), 0.f);
+ }
+ depth = cv::Mat::zeros(color.rows, color.cols, CV_32FC1);
+ // Reproject raw depth into RGB, including the baseline translation. Store
+ // RGB-camera Z, not the original depth-camera Z. Nearest-depth z-buffer;
+ // unobserved/occluded pixels stay zero instead of inventing a surface.
+ const auto* bytes = static_cast<const uint8_t*>(raw.get_data());
+ for (int y = 0; y < raw.get_height(); ++y) for (int x = 0; x < raw.get_width(); ++x) {
+ uint16_t sample = 0;
+ std::memcpy(&sample, bytes + y * raw.get_stride_in_bytes() + x * 2, 2);
+ if (!sample) continue;
+ const float z = static_cast<float>(sample * scale);
+ if (z < .05f || z > 5.f) continue;
+ const float pixel[2] = {static_cast<float>(x), static_cast<float>(y)};
+ float pd[3], pc[3], uv[2];
+ rs2_deproject_pixel_to_point(pd, &kd, pixel, z);
+ rs2_transform_point_to_point(pc, &extrinsics, pd);
+ if (!std::isfinite(pc[0]) || !std::isfinite(pc[1]) || !std::isfinite(pc[2]) || pc[2] <= 0) continue;
+ rs2_project_point_to_pixel(uv, &kc, pc);
+ if (!std::isfinite(uv[0]) || !std::isfinite(uv[1]) || uv[0] < 0 || uv[1] < 0
+ || uv[0] > color.cols - 1 || uv[1] > color.rows - 1) continue;
+ const int target_y=static_cast<int>(std::lround(uv[1])), target_x=static_cast<int>(std::lround(uv[0]));
+ if (!valid_color.empty() && !valid_color.at<uint8_t>(target_y,target_x)) continue;
+ float& stored = depth.at<float>(target_y,target_x);
+ if (stored == 0 || pc[2] < stored) stored = pc[2];
+ }
+ intrinsics.fx = kc.fx; intrinsics.fy = kc.fy; intrinsics.cx = kc.ppx; intrinsics.cy = kc.ppy;
+ for (int i = 0; i < 5; ++i) intrinsics.coeffs[i] = kc.model == RS2_DISTORTION_NONE ? 0.f : kc.coeffs[i];
+ geometry.metres_per_unit = 1.;
+ geometry.aligned_to_color = true; geometry.color_axial_z = true;
+ geometry.distortion_model = kc.model == RS2_DISTORTION_NONE ? "none" : "brown_conrady";
+}
+
void RealsenseCamera::getRGBImage(cv::Mat& color, Rs2Intrinsics& intrinsics) {
intrinsics.cx = intrinsics_.ppx;
intrinsics.cy = intrinsics_.ppy;
@@ -727,6 +858,7 @@ rs2::frameset RealsenseCamera::get_frameset(bool align) {
std::lock_guard<std::mutex> lock(frame_mtx_);
constexpr unsigned int kWaitTimeoutMs = 300;
rs2::frameset frames = pipe_.wait_for_frames(kWaitTimeoutMs);
+ latest_metric_frames_ = frames;
// 如果需要对齐,添加对齐逻辑
if (align_ && align && stream_mode_ == RGBD_MODE) {
frames = align_->process(frames);
diff --git a/cmvr-es/service/grpc/src/grpc_camera_service.cpp b/cmvr-es/service/grpc/src/grpc_camera_service.cpp
index d209fe13..1857fc1c 100644
--- a/cmvr-es/service/grpc/src/grpc_camera_service.cpp
+++ b/cmvr-es/service/grpc/src/grpc_camera_service.cpp
@@ -320,7 +320,24 @@ grpc::Status gRPCCameraServiceImpl::GetRGBDImages(grpc::ServerContext* context,
return failResponse(response, "Camera device not found: " + dev_id);
}
Rs2Intrinsics intrinsics = {0};
- dev->getRGBDImages(color_image,depth_image, intrinsics);
+ RgbdGeometry geometry;
+ if (request->require_metric_depth())
+ dev->getMetricRGBDImages(color_image, depth_image, intrinsics, geometry);
+ else
+ dev->getRGBDImages(color_image,depth_image, intrinsics);
+ if (request->require_metric_depth()) {
+ if (!geometry.aligned_to_color || !geometry.color_axial_z || geometry.metres_per_unit <= 0)
+ return failResponse(response, "Camera driver does not provide metric RGB-aligned depth");
+ response->mutable_depth_geometry()->set_metres_per_unit(geometry.metres_per_unit);
+ response->mutable_depth_geometry()->set_aligned_to_color(geometry.aligned_to_color);
+ response->mutable_depth_geometry()->set_color_axial_z(geometry.color_axial_z);
+ const uint16_t endian_probe = 1;
+ response->mutable_depth_geometry()->set_byte_order(
+ *reinterpret_cast<const uint8_t*>(&endian_probe) == 1 ? "little" : "big");
+ response->mutable_depth_geometry()->set_distortion_model(geometry.distortion_model);
+ response->mutable_color_frame()->set_capture_utc_ns(geometry.color_capture_utc_ns);
+ response->mutable_depth_frame()->set_capture_utc_ns(geometry.depth_capture_utc_ns);
+ }
if (color_image.empty()) {
return failResponse(response, "Camera returned an empty RGB image: " + dev_id);
}
diff --git a/protos/cmvr/api/camera_command.proto b/protos/cmvr/api/camera_command.proto
index 7305955a..276994ce 100644
--- a/protos/cmvr/api/camera_command.proto
+++ b/protos/cmvr/api/camera_command.proto
@@ -107,6 +107,8 @@ message GetDepthImageCommand {
message GetRGBDImagesCommand {
message Request {
CommandHeader.Request header = 1;
+ // Opt-in metric snapshot; legacy requests retain their existing format.
+ bool require_metric_depth = 2;
}
message Feedback {
@@ -114,9 +116,20 @@ message GetRGBDImagesCommand {
FrameData color_frame = 2;
FrameData depth_frame = 3;
CameraIntrinsics intrinsics = 4;
+ DepthGeometry depth_geometry = 5;
}
}
+// Raw little-endian depth samples, aligned to the accompanying native RGB.
+// sample * metres_per_unit is RGB optical-axis Z (not range along the ray).
+message DepthGeometry {
+ double metres_per_unit = 1;
+ bool aligned_to_color = 2;
+ bool color_axial_z = 3;
+ string byte_order = 4;
+ string distortion_model = 5;
+}
+
message StartCameraRecordingCommand {
message Request {
CommandHeader.Request header = 1;